I am trying to insert data into mysql database using Java. I am using the following code to fetch data from database and it is working fine.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class DbTest {
public static void main (String[] args) throws Exception{
// Accessing Driver From Jar File
Class.forName("com.mysql.jdbc.Driver");
//DB Connection
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");
// MySQL Query
PreparedStatement statement= con.prepareStatement("SELECT * FROM jam WHERE id='1'");
//Creating Variable to execute query
ResultSet result=statement.executeQuery();
while(result.next()){
System.out.println(result.getString(2));
}
}
}
To Insert data, I have tried the above code only replacing
PreparedStatement statement= con.prepareStatement("SELECT * FROM jam
WHERE id='1'");
with
PreparedStatement statement= con.prepareStatement("INSERT INTO jam(id,name)
VALUES ('','Charlie Sheen')");
But its showing some errors. Could you please tell me where is the problem in my code.
Thanks :)
解决方案
If your primary key is auto increment,you can try this;
PreparedStatement statement= con.prepareStatement("INSERT INTO jam(name)
VALUES (?)");
statement.setString(1,"Charlie Sheen");
statement.execute();