Prepared Statement Failing

2019-08-23 11:17发布

问题:

I'm using a prepared statment that should (using SQL & JDBC) insert data into a dataTable. I am using one that deletes data that works fine, but the insert one is not inserting any data into the data table and does not produce an error or warning. What could cause a prepared statement to fail in this way? Could inserting a null value into the prepared statement cause this?

回答1:

What do you mean by "failing, but does not produce an error"? How do you know it's failing then - is data not actually being inserted? Perhaps you're not committing a transaction?



回答2:

Two ways to solve your problem.

1st way:

    Connection con = DriverManager.getConnection(DB_host, DB_UserName, DB_UserPassword);
    con.setAutoCommit(true);
String sql = "INSERT INTO Users (fName, lastName, userName, password) VALUES (?, ?, ?, ?)";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, "fName" );
stmt.setString(2, "lastName" );
stmt.setString(3, "userName" );
stmt.setString(4, "password" );
stmt.executeUpdate();

2nd way:

Connection con = DriverManager.getConnection(DB_host, DB_UserName, DB_UserPassword);
String sql = "INSERT INTO Users (fName, lastName, userName, password) VALUES (?, ?, ?, ?)";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.setString(1, "fName" );
stmt.setString(2, "lastName" );
stmt.setString(3, "userName" );
stmt.setString(4, "password" );
stmt.executeUpdate();
con.commit();

That is while creating connection object itself enable autocommit true for it. So tat it ll make the changes immediately reflect into ur database.

Else after ur transaction make the connection as commit to ensure your transaction to be saved in database