学习笔记——JDBC及对增删改查的封装
JDBC流程:
首先需要导包(驱动、版本),创建lib文件夹,右键Add as Library
-
加载驱动
-
获取连接对象
-
获取执行的sql语句对象
-
执行sql语句
-
释放资源
资源的释放应当先开后关
public static void main(String[] args) {
Connection conn = null;
Statement st = null;
// 1. 加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
// 2. 获取连接对象
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
// 3. 获取执行sql语句对象
st = conn.createStatement();
// 4. 执行sql语句
int j = st.executeUpdate("insert into student values(null,\'" + "南桐" + "\')");
System.out.println(j);
// int i = st.executeUpdate("insert into student values(null,'龙泽')");
// 5. 释放资源 先开后关
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (st!=null){
st.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
try {
if (conn!=null){
conn.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
面试题:
Collection,Collections和Connection区别?Collection是数组的实现类接口,提供了对集合对象进行基本操作的通用接口方法
Collections是集合类的一个工具类/帮助类,其中提供了一系列静态方法,用于对集合中元素进行排序、搜索以及线程安全等各种操作。
Connection是一个接口,主要用于实现应用程序和DBMS之间进行通信的一个通道,通过该通道可以向数据库服务器发送可以执行sql脚本,并且可以将执行结果返回到程序中,可以获取一个用于处理sql语句的执行器(statement),
Connection就是一个程序与数据库之间会话(session)。
初步封装
对重复语句进行封装,简化之后的代码量
public class JDBCUtil {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
static {
Properties p = new Properties();
try {
// 读取properties中的配置文件
p.load(JDBCUtil.class.getResourceAsStream("/db.properties"));
driver = p.getProperty("driverClassName");
url = p.getProperty("url");
username = p.getProperty("username");
password = p.getProperty("password");
} catch (IOException e) {
e.printStackTrace();
}
}
public static Connection getConn(){
try {
Class.forName(driver);
// 2. 获取连接对象
return DriverManager.getConnection(url, username, password);
} catch (Exception throwables) {
throwables.printStackTrace();
}
return null;
}
public static void close(Statement st, Connection conn){
try {
if (st!=null){
st.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
try {
if (conn!=null){
conn.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close(ResultSet rs,PreparedStatement ps, Connection conn){
try {
if (rs!=null){
rs.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
try {
if (ps!=null){
ps.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
try {
if (conn!=null){
conn.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}