package com.bjpowernode.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* 使用preparedStatement完成增删改
*/
public class 使用预编译完成增删改操作 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
try {
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","******");
//3.获取预编译的数据库操作对象
//增加一条记录
/*
String sql = "insert into dept(deptno,dname,loc) values(?,?,?)";
ps = conn.prepareStatement(sql);
//传值给占位符?,?,?
ps.setInt(1,50);
ps.setString(2,"销售部");
ps.setString(3,"秦皇岛");
*/
/*
//修改一条记录
String sql = "update dept set dname = ?,loc = ? where deptno = ?";
ps = conn.prepareStatement(sql);
//给占位符传值
ps.setString(1,"人事部");
ps.setString(2,"上海");
ps.setInt(3,50);
*/
//删除一条记录
String sql = "delete from dept where deptno = ?";
ps = conn.prepareStatement(sql);
//传值
ps.setInt(1,50);
//4.执行sql语句
int count = ps.executeUpdate();
System.out.println(count);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
if (ps != null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}