使用PreparedStatement 更新添加数据:
package JDBC;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.mysql.jdbc.PreparedStatement;
public class jdbc3 {
public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub
Connection con=null;
PreparedStatement psta=null;
String sql="insert into worker(id,name,age)values(?,?,?)";
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root","");
psta=(PreparedStatement) con.prepareStatement(sql);
psta.setInt(1, 4);
psta.setString(2, "hupeng");
psta.setInt(3, 27);
int n=psta.executeUpdate();
if(n==0)
{
System.out.println("没有添加成功!");
}
else
{
System.out.println("添加成功");
}
con.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
结果: