Я пытаюсь обновить таблицу в mysql из java-программы. Я успешно пробовал соединение, запустив запрос SELECT.Неспособность вставить в SQL-таблицу из java
Со следующим кодом я не получаю никаких исключений, и программа не сбой. Но таблица не обновляется после запуска метода insert.
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");
}
}
}
метод подключения():
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;
}
Попробуйте опубликовать свой метод connect() – Abdelhak
Вы должны использовать try-with-resources, поэтому вам не придется называть 'close()' самостоятельно, и, следовательно, не нужно их исключать. – Andreas
Я отредактировал исходное сообщение и вставил метод connect() –