用java将数据写入mysql

6ljaweal  于 2021-06-23  发布在  Mysql
关注(0)|答案(5)|浏览(414)

我做了一个简单的类来测试我是否能够将数据写入我的数据库

package climaxinvoice;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Calendar;

public class InsertValues {

    public static void main(String args[]) throws ClassNotFoundException, SQLException
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/cxinvoice.invoice_list","admin","admin");
            Calendar cdr = Calendar.getInstance();
            java.sql.Date startDate = new java.sql.Date(cdr.getTime().getTime());
            String query = " insert into cxinvoice.invoice_list (number, company, date, payment, quantity, subtotal_five, cgst_five, sgst_five, subtotal_twelve, cgst_twelve, sgst_twelve, total, items)" + " value (?,?,?,?,?,?,?,?,?,?,?,?,?)";
            PreparedStatement st = conn.prepareStatement(query);
            st.setInt(1,1);
            st.setString(2,"Climax Exclusive");
            st.setDate(3,startDate);
            st.setString(4,"CASH");
            st.setString(5,"5");
            st.setString(6,"1000");
            st.setString(7,"250");
            st.setString(8,"250");
            st.setString(9,"2000");
            st.setString(10,"750");
            st.setString(11,"750");
            st.setString(12,"3000");
            st.setString(13,"a|b|c|d");
            st.execute();
            conn.close();
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}

该文件运行,但我无法看到我的表中有任何更改我是mysql新手,为我的工作台输出附加了一个屏幕截图

bf1o4zei

bf1o4zei1#

更改连接字符串,从'jdbc:mysql://localhost:3306/cxinvoice.invoice_list'收件人'jdbc:mysql://localhost:3306/cxinvoice'
另外,insert语句不正确。将“value”更改为“values”。

Insert into cxinvoice.invoice_list (number, company, date, payment, quantity, subtotal_five, cgst_five, sgst_five, subtotal_twelve, cgst_twelve, sgst_twelve, total, items)" + " values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
w1e3prcc

w1e3prcc2#

不要使用calender类,而是像这样使用date类和simpleddateformatter类,然后执行插入。

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
    Date date = new Date();
    System.out.println(dateFormat.format(date));
z9ju0rcb

z9ju0rcb3#

很抱歉给您添麻烦,驱动程序出现了一些问题,我想我把jarformysql连接器添加到了我的库中,它开始工作了,谢谢大家的帮助,这个问题可以结束了,再次谢谢大家

mwyxok5s

mwyxok5s4#

通常,默认情况下autocommit为true。
如果不使用:

con.autocommit(true)

或者 con.commit() 交易结束时
但我不认为这会完美地执行:
更新sql查询中的输入错误 VALUES 而不是价值。确保没有其他打字错误。
在发票清单(编号、公司、日期、付款、数量、小计五、现金五、新加坡元五、小计十二、现金十二、新加坡元十二、合计、项目)中插入“+”值(?,?,?,?,?,?,?,?,?)”;

8yoxcaq7

8yoxcaq75#

生成成功
“build is successful”(构建成功)仅表示您构建了它。你还没有执行这个。如果有,就会出现异常,因为值处的sql语法错误。

相关问题