首页 > 代码库 > PreparedStatemnet预编译操作数据库的增删改
PreparedStatemnet预编译操作数据库的增删改
/**************PreparedStatemnet使用******************/
/*特点:相当于ADO.NET中的参数化命令对象
* 1、预编译,执行相同的sql语句,提高执行效率
* 2、能将数据中的特殊字符当作普通字符进行处理
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入学号:");
int stuNum = input.nextInt();
System.out.println("请输入姓名:");
String stuName = input.next();
System.out.println("请输入年龄:");
int stuAge = input.nextInt();
System.out.println("请输入性别:");
String stuSex = input.next();
System.out.println("请输入地址:");
String address = input.next();
//参数化sql语句
String sql = "insert into stuInfo values(?,?,?,?,?)";//ADO.NET中参数是用 @参数名 JDBC中参数用 ?表示
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection conn = null;
PreparedStatement pstm = null;
try {
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=StuDB","sa","sasa");
pstm = conn.prepareStatement(sql);//注意:prepareStatement方法需要参数
//给sql语句中的参数赋值
pstm.setInt(1, stuNum);
pstm.setString(2, stuName);
pstm.setInt(3, stuAge);
pstm.setString(4, stuSex);
pstm.setString(5,address);
//执行sql语句
int result = pstm.executeUpdate();
if(result>0){
System.out.println("添加成功!");
}else{
System.out.println("添加失败!");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
pstm.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}