DriverManager类-驱动管理者
Connection接口-连接
Statement接口-命令
ResultSet接口-结果
连接数据库步骤:
注册驱动(只做一次)
建立连接(Connection)
创建执行SQL的语句(Statement)
执行语句
处理执行结果(ResiltSet)
释放资源
每个功能都需要获得连接
也需要关闭连接
这个代码是重复的
将所有的代码放到这个类里面来
在其他类中直接调用这个类就行了
使用静态代码块加载驱动
static {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
定义连接语句
private static final String URL = "jdbc:sqlserver://localhost:1433;databasename=api_284";
获得连接的方法
public static Connection getCon() {
try {
return DriverManager.getConnection(URL, "sa", "sa123");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
关闭资源:
连接con,执行对象ps,结果集rs
public static void close(Connection con, PreparedStatement ps, ResultSet rs) {
try {
if (con != null && !con.isClosed()) {
con.close();
}
if (ps != null) {
ps.close();
}
if (rs != null) {
rs.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}