There is a fundamental mistake in your code.
Once the PreparedStatement
is created, we need to call preparedStatement.executeUpdate();
with out passing SQL again
Here is the full code for your question.
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class SampleMysql {
public static Connection getConnection() throws SQLException {
Driver drv = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(drv);
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sample","sample", "sample");
return con;
}
public static int saveUser(int userId, String userName){
int saveStatus = 0;
Connection connection = null;
try {
connection = getConnection();
connection.setAutoCommit(true);
String sql = "INSERT INTO testtable VALUES(?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, userId);
preparedStatement.setString(2, userName);
saveStatus = preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return saveStatus;
}
public static void main(String[] a) {
System.out.println(saveUser(1, "sample"));
}
}
The table script is given below.
CREATE TABLE testtable(user_ID INT(10), user_name VARCHAR(10));