文章目录
概述
实现步骤
1.注册数据库驱动
2.获取数据库连接
3.创建传输器
4.传输sql语句并且返回结果
5.遍历结果
6.关闭资源
代码实现
版本一:
版本二
捕获异常:
选中异常代码,然后【Ctrl+Alt+T】
终极模板
工具类
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
//工具类
public class JDBCUtils {
//私有化构造方法
private JDBCUtils(){}
//创建Properties类对象
//静态属性(对象)---全局统一---只需要创建一次对象就可以读取配置内容
private static Properties p=new Properties();
//静态代码块---保证先读取配置文件内容
static {
//JDBCUtils.class---获取当前类的字节码对象
//getClassLoader()---获取类加载器
//getResource("src目录下的文件名称")---获取当前工程的src目录
//getPath()---把URL类型转换成String类型
try {
p.load(new FileInputStream(new File(JDBCUtils.class.
getClassLoader().getResource("conf.properties").getPath())));
} catch (IOException e) {
e.printStackTrace();
}
}
//定义静态方法---注册驱动以及获取数据库连接
public static Connection getConnection() throws ClassNotFoundException, SQLException {
//注册数据库驱动
//获取配置文件的driver键对应值
Class.forName(p.getProperty("driver"));
//获取数据库连接
///通过配置文件的键对来获取对应值
return DriverManager.getConnection(p.getProperty("url"),p.getProperty("user"),p.getProperty("password"));
}
//定义静态方法---关闭资源
public static void close(Connection conn, Statement stat, ResultSet rs){
if(rs!=null)
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
rs=null;
}
if(stat!=null)
try {
stat.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
stat=null;
}
if(conn!=null)
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
conn=null;
}
}
}
conf.properties配置文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb1
user=root
password=root
测试类
//删除数据
@Test
public void delete(){
Connection conn=null;
Statement stat=null;
try {
//通过工具类调用静态方法注册数据库驱动并且返回数据库连接
conn = JDBCUtils.getConnection();
//创建传输器
stat = conn.createStatement();
//传输sql语句并且返回结果
int i = stat.executeUpdate("delete from exam where id=6");
if(i>0){
System.out.println("删除成功受影响的行数:"+i);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
//通过工具类来调用静态方法来关闭资源
JDBCUtils.close(conn,stat,null);
}
}
//更新数据
@Test
public void update(){
Connection conn=null;
Statement stat=null;
try {
//调用工具类里静态方法来注册驱动并且返回数据库连接
conn = JDBCUtils.getConnection();
stat = conn.createStatement();
int i = stat.executeUpdate("update exam set name='诸葛亮' where id=3");
if(i>0){
System.out.println("更新成功受影响的行数:"+i);
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}finally {
//调用工具类静态方法来关闭资源
JDBCUtils.close(conn,stat,null);
}
}
JDBC详解
DriverManager
常用数据库URL地址的写法:
Connection
Statement
ResultSet
常用数据类型转换表
ResultSet中的api
释放资源