2、首先获取Connection
获取连接代码
private static Connection getConn() {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://ip:端口/数据库名?连接参数";
String username = "用户名";
String password = "密码";
Connection conn = null;
try {
Class.forName(driver); //classLoader,加载对应驱动
conn = (Connection) DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
2、使用连接进行增删
2.1 insert示例
private static void insert() throws SQLException {
//1.获取连接
Connection conn = getConn();
try {
conn.setAutoCommit(false);
//2.获得预处理对象
String sql = "insert into table_user (id,name) values (?,?)";
PreparedStatement pstmt;
pstmt = (PreparedStatement) conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
//3.SQL语句占位符设置实际参数
pstmt.setLong(1, 1L);
pstmt.setString(2, "Tony Stark");
//4.执行SQL语句
int line = pstmt.executeUpdate();
conn.commit();
System.out.println("更新记录数"+ line);
} catch (SQLException e) {
e.printStackTrace();
}finally {
//5.关闭资源
conn.close();
}
}
delete示例
private static void delete() {
//1.获取连接
Connection conn = getConn();
try {
//2.获得预处理对象
String sql = "delete from table_user where id = 1";
Statement statement = connection.createStatement();
//4.执行SQL语句
int result = statement.executeUpdate(sql);
if (result != 0) {
System.out.println("操作成功,受影响" + result + "行");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
//5.关闭资源
conn.close();
}
}