John Smith
John Smith

Reputation: 321

Finishing MySQL prepared statement in JAVA

I am learning MySQL with JAVA, and don't understand prepared statements. Abstracting from I shall learn it, I want to ask for help in finishing this code to be "prepared stated" :-)

String stringQuery = "INSERT INTO banlist (name, reason, admin, time, temptime, IP) VALUES (testNick, testPowod, testAdmin, CURRENT_TIMESTAMP, NOW(), NULL);=?";

PreparedStatement statement = this.connection.prepareStatement( stringQuery );
statement.setString( 1,  ); // after ' 1, ' we define what we want to get
ResultSet resultSet = statement.executeUpdate(); 

Upvotes: 0

Views: 596

Answers (2)

JB Nizet
JB Nizet

Reputation: 692181

String stringQuery = 
    "INSERT INTO banlist (name, reason, admin, time, temptime, IP)"
    + " VALUES (?, ?, ?, CURRENT_TIMESTAMP, NOW(), NULL)";

PreparedStatement statement = this.connection.prepareStatement(stringQuery);
statement.setString(1, testNick);
statement.setString(2, testPowod);
statement.setString(3, testAdmin);
int inserted = statement.executeUpdate();

Read the JDBC tutorial.

Upvotes: 1

duffymo
duffymo

Reputation: 309008

Here's how I'd do it:

String insertQuery = "INSERT INTO banlist(name, reason, admin, time, temptime, IP) VALUES (?, ?, ?, ?, ?, ?)";
PreparedStatement statement = this.connection.prepareStatement( stringQuery );
statement.setString(1, name);  // These values come from your code; dynamic
statement.setString(2, reason);
statement.setString(3, admin);
statement.setString(4, time);
statement.setString(5, tempTime);
statement.setString(6, ip); 
int numRowsAffected = statement.executeUpdate(); 

Be sure to close your statement appropriately.

Upvotes: 1

Related Questions