import sun.security.provider.SHA;
import java.sql.*;
import java.util.ArrayList;
public class Test{
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
//ResultSet rs = null;
try {
// Driver driver = new com.mysql.jdbc.Driver();
// DriverManager.deregisterDriver(driver);
//注册mysql的驱动
Class.forName("com.mysql.jdbc.Driver");
//获取连接对象
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","123");
//手动提交事务
conn.setAutoCommit(false);
//获取预编译的数据库操作对象
//String sql = "select empno,ename,sal from emp";
String sql = "insert into dept(deptno,dname,loc) values(?,?,?)";
ps = conn.prepareStatement(sql);
//rs = ps.executeQuery(sql);
//完成赋值
ps.setInt(1,1000);
ps.setString(2,"销售");
ps.setString(3,"西安");
//执行sql
int count = ps.executeUpdate();
//提交事务
conn.commit();
// while(rs.next()){
// String empno = rs.getString("empno");
// String ename = rs.getString("ename");
// String sal = rs.getString("sal");
// System.out.println(empno + "," + ename + "," + sal);
// }
} catch (ClassNotFoundException | SQLException e) {
if(conn != null){
//遇到异常手动回滚
try {
conn.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
e.printStackTrace();
}finally {
if(ps != null){
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn != null){
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}