【问题标题】:Java insert to mySQL workbenchJava 插入到 mySQL 工作台
【发布时间】:2018-10-03 04:07:57
【问题描述】:

我有一个名为 Customer 的 mySQL 数据库,我正在尝试从 GUI 中的文本字段插入数据。我运行了下面的代码,在控制台中显示“连接成功”,没有错误。我检查了信息是否已插入到 mySQL 数据库的 Customer 表中,但没有插入任何内容。有谁知道为什么?

         button.setOnAction(e -> {


         Connection dbConnection = null;
            PreparedStatement preparedStatement = null;

         try {


           Customer cust = new Customer();
          dbConnection = Connect();
            String sql="Insert into CIS3270.Customer(firstName,lastName, email,userNAME,Address,Zip,State,SecurityQ,  Password, ConfirmPassword,SSN)VALUES (?,?,?,?,?,?,?,?,?,?,?)"; 
            preparedStatement =  dbConnection.prepareStatement(sql);


            preparedStatement.setString(1,cust.getFirstName()); 
            preparedStatement.setString(2,cust.getLastName()); 
            preparedStatement.setString(3,cust.getEmail()); 
            preparedStatement.setString(4,cust.getUserNAME()); 
            preparedStatement.setString(5,cust.getAddress());
            preparedStatement.setString(6,cust.getZip()); 
            preparedStatement.setString(7,cust.getState());
            preparedStatement.setString(8,cust.getSecurityQuestion());
            preparedStatement.setString(9,cust.getPassWORD()); 
            preparedStatement.setString(10,cust.getConfirmPassword());
            preparedStatement.setString(11,cust.getSSN()); 

            preparedStatement.executeBatch(); 
            preparedStatement.executeUpdate();

            dbConnection.close(); 
            preparedStatement.close(); 



        LoginScreen loginPage = new LoginScreen();

        loginPage.start(primaryStage);

         }
         catch(Exception e1) {
            e1.printStackTrace();
         }
    });

       public static Connection Connect() {
       Connection con = null;
    try {
        Class.forName("com.mysql.jdbc.Driver");
        con = (Connection) DriverManager.getConnection("jdbc:mysql://(ip adress):3306/CIS3270", "root", "password");
    } catch (Exception e) {
        System.out.println("Can not connect");
    }
    if (con != null) {
        System.out.println("Connected Successfully");
    }
    return con;
}

【问题讨论】:

  • 你是否在 close() 之前尝试提交 (dbConnection.commit())?
  • 添加Connect()的代码

标签: java mysql eclipse


【解决方案1】:

您不需要批量插入,因为您插入的是单行。

您的代码没有执行任何操作的原因是您正在执行一个空批处理。您也需要致电preparedStatement.addBatch()。或者只是删除 executeBatch() 调用,因为您似乎也调用了 executeUpdate()

【讨论】:

  • 是的,我尝试删除 executeBatch() 并添加它并得到相同的结果 - 连接成功,但实际上没有插入任何内容
  • 代码真的在执行吗?首先检查日志记录或调试。
  • 好吧,你试过dbConnection.commit()吗,虽然默认情况下应该启用自动提交。
  • 我刚刚添加了 dbConnection.commit() 并运行了它。当我单击 GUI 中的按钮时,我的控制台中出现错误提示“当 autocommit=true 时无法调用提交。这基本上是说当自动提交已经为真时不需要调用提交?
  • 我终于让插入工作(部分)。我说部分是因为每次我在 eclipse 中插入一个新行时都会在 mySQL Workbench 上创建一个新行,但是所有的值都是 NULL。目前有什么建议吗?
猜你喜欢
  • 2011-09-10
  • 1970-01-01
  • 2022-12-13
  • 2014-03-04
  • 1970-01-01
  • 2021-12-15
  • 2021-04-11
  • 1970-01-01
  • 2014-06-28
相关资源
最近更新 更多