JDBC的使用步骤
2020-03-22 本文已影响0人
风中小酌
加载数据库驱动 -->
使用反射注册驱动
Class.forName("com.mysql.jdbc.Driver");
建立数据库连接 Connection -->
Connection conn = null;
String url = "jdbc:mysql://localhost:3366/bjsxt?useUnicode=true&characterEncoding=utf8";
String user = "root";
String pwd = "123456";
conn = DriverManager.getConnection(url, user, pwd);
创建执行SQL的语句 Statement -->
String sql = "insert into department values(1, '研发部');";
Statement stat = conn.createStatement();
int res = stat.executeUpdate(sql);
处理执行结果 ResultSet -->
释放资源
if(stat != null){
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}