JDBC使用模板
//1.导入驱动jar包
//2.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//3.获取数据库连接对象
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/school", "root", "123456");
//4.定义sql语句
String sql = "update user set username = 'qiqi' where userId = 1";
//5.获取执行sql的对象 Statement
Statement stmt = conn.createStatement();
//6.执行sql
int count = stmt.executeUpdate(sql);
//7.处理结果
System.out.println(count);
//8.释放资源
stmt.close();
conn.close();
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
//1.导入驱动jar包
//2.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//3.获取数据库连接对象
conn = DriverManager.getConnection("jdbc:mysql:///school", "root", "123456");
//4.定义sql语句
String sql1 = "update user set username = 'zhier' where userId = 2";
String sql2 = "Insert into user(userId,username,password) values (3,'sansan','123456')";
String sql3 = "delete from user where userId = 3";
//5.获取执行sql的对象 Statement
stmt = conn.createStatement();
//6.执行sql
int i = stmt.executeUpdate(sql3);
//7.处理结果
System.out.println(i);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
//8.释放资源
// stmt.close();
// conn.close()
if (stmt != null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
还没有评论,来说两句吧...