2016-02-29 68 views
-1

我試圖從java程序中更新mysql中的表。 我已經通過運行SELECT查詢成功地嘗試了連接。未能從java插入到SQL表中

用下面的代碼,我沒有得到任何異常,程序沒有崩潰。但是在運行插入方法後表格不會更新。

public void insert() throws SQLException, ParseException { 

    PreparedStatement stmt = null; 
    Connection con = null; 

    in = new Scanner(System.in); 

    System.out.println("Write name: "); 
    String name = in.nextLine(); 

    System.out.println("Write date: "); 
    String dateString = in.nextLine(); 

    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 
    Date myDate = formatter.parse(dateString); 
    java.sql.Date sqlDate = new java.sql.Date(myDate.getTime()); 


    // Set the SQL statement into the query variable 
    String query = "INSERT INTO Kopers (name, date) VALUES (?, ?)"; 



    try { 
     con = connect(); 


     stmt = con.prepareStatement(query); 

     stmt.setString(1, name); 
     stmt.setDate(2, sqlDate); 


     // Execute the SQL statement that is prepared in the variable stmt 
     stmt.executeUpdate(); 

     System.out.println("Inserting " + name + " with date: " + sqlDate + " into database."); 


    } finally { 
     try { 
      stmt.close(); 
      con.close(); 
      System.out.println("Connection closed."); 
     } 
     catch (Exception e) { 
      System.out.printf("Error message: " + e + "\n"); 
    } 
    } 

} 

connect()方法:

public Connection connect() 
{ 
    try 
    { 
     // register the driver with DriverManager 
     Class.forName(driver); 
     //create a connection to the database 
     Connection con = DriverManager.getConnection(url, username, password); 
     // Set the auto commit of the connection to false. 
     // An explicit commit will be required in order to accept 
     // any changes done to the DB through this connection. 
     con.setAutoCommit(false); 
     return con; 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 
    return null; 
} 
+0

嘗試發佈你的connect()方法 – Abdelhak

+0

你應該使用try-with-resources,所以你不必自己調用close(),因此不必去捕獲它們的異常。 – Andreas

+0

我編輯了原文並粘貼connect()方法 –

回答

3

你應該使用commit()方法上的連接明確承諾連接

con.commit() 

正如你已經在你的connect()方法設置autoCommit(false)

+0

只有當connect()承諾。 – Andreas

+0

感謝您的回答,我已將連接設置爲autoCommit(false) –

+0

@Andreas是的。我應該提到在答案..謝謝 – Pragnani