我正在尝试从java程序更新mysql中的表。 我已经通过运行SELECT查询成功地尝试了连接。
使用以下代码,我没有得到任何异常,程序也没有崩溃。但是在运行insert-method之后表没有更新。
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 :(得分:3)
您应该在Connection
上使用commit()
方法显式提交连接
即
con.commit()
正如您在autoCommit(false)
方法中设置了connect()