一、JDBC实现增删改查

### --- JDBC工具类

~~~ # 什么时候自己创建工具类?
——> 如果一个功能经常要用到,我们建议把这个功能做成一个工具类,可以在不同的地方重用。
——> 获得数据库连接”操作,将在以后的增删改查所有功能中都存在,可以封装工具类JDBCUtils。提供获取连接对象的方法,从而达到代码的重复利用。
~~~ # 工具类包含的内容
——> 1) 可以把几个字符串定义成常量:用户名,密码,URL,驱动类
——> 2) 得到数据库的连接:getConnection()
——> 3) 关闭所有打开的资源:

二、代码示例

/**
* JDBC 工具类
*/
public class JDBCUtils {

//1. 定义字符串常量, 记录获取连接所需要的信息
public static final String DRIVERNAME = "com.mysql.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/db4?characterEncoding=UTF-8";
public static final String USER = "root";
public static final String PASSWORD = "123456";

//2. 静态代码块, 随着类的加载而加载
static{
try {
//注册驱动
Class.forName(DRIVERNAME);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

//3.获取连接的静态方法
public static Connection getConnection(){

try {
//获取连接对象
Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);

//返回连接对象
return connection;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}

//关闭资源的方法
public static void close(Connection con, Statement st){
if(con != null && st != null){
try {
st.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

public static void close(Connection con, Statement st, ResultSet rs){

if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}

close(con,st);
}
}

三、sql语句

package com.yanqi.jdbc05;

import java.sql.*;

/**
* JDBC工具类
*/
public class JdbcUtils {

//1. 将连接信息定义为 字符串常量
public static final String DRIVERNAME = "com.mysql.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/db4?characterEncoding=UTF-8";
public static final String USER = "root";
public static final String PASSWORD = "123456";

//2.静态代码块
static{
try {
//1.注册驱动
Class.forName(DRIVERNAME);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

//3.获取连接的 静态方法
public static Connection getConnection(){
try {
//获取连接对象 并返回
Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
return connection;

} catch (SQLException e) {
e.printStackTrace();
return null;
}
}

//4.关闭资源的方法
public static void close(Connection con, Statement statement){

if(con != null && statement != null){

try {
statement.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

public static void close(Connection con, Statement statement, ResultSet resultSet){

if(con != null && statement != null){

try {
resultSet.close();
statement.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

}











Walter Savage Landor:strove with none,for none was worth my strife.Nature I loved and, next to Nature, Art:I warm'd both hands before the fire of life.It sinks, and I am ready to depart

                                                                                                                                                   ——W.S.Landor