JDBC连接数据库操作

目录

一、JDBC介绍

二、程序编写步骤

三、获取数据库连接

四、CRUD操作

一、JDBC介绍
1、JDBC
Java数据库连接,(Java Database Connectivity,简称JDBC)是Java语言中用来规范客户端程序如何来访问数据库的应用程序接口,提供了诸如查询和更新数据库中数据的方法。JDBC也是Sun Microsystems的商标。我们通常说的JDBC是面向关系型数据库的。

2、数据持久化
持久化(persistence):把数据保存到可掉电式存储设备中以供之后使用。大多数情况下,特别是企业级应用,数据持久化意味着将内存中的数据保存到硬盘上加以”固化”,而持久化的实现过程大多通过各种关系数据库来完成。

持久化的主要应用是将内存中的数据存储在关系型数据库中,当然也可以存储在磁盘文件、XML数据文件中。

3、Java中的数据存储技术
JDBC直接访问数据库

JDO (Java Data Object )技术

第三方O/R工具,如Hibernate, Mybatis 等

4、Java与SQL对应数据类型转换表

5、两种思想
面向接口编程思想
ORM思想(object relational mapping)
一个数据表对应一个Java类

    表中的一条记录对应Java类的一个对象

    表中的一个字段对应Java类的一个属性

6、两种技术
JDBC结果集的元数据:ResultSetMetaData

获取列数:getColumnCount()

获取列的别名:getColumnLabel()

通过反射,创建指定类的对象,获取指定的属性并赋值

二、程序编写步骤

三、获取数据库连接
连接方式一:

@Test
public void connection01() throws SQLException {
    Driver driver = new com.mysql.jdbc.Driver();
    String url = "jdbc:mysql://localhost:3306/test";
    Properties info = new Properties();
    info.setProperty("user","root");
    info.setProperty("password","000000");
    Connection conn = driver.connect(url,info);
    System.out.println(conn);
}

显式出现了第三方数据库的API.

连接方式二:

@Test
public void connection02() throws Exception {
    Class clazz = Class.forName("com.mysql.jdbc.Driver");
    Driver driver = (Driver) clazz.newInstance();
    Properties info = new Properties();
    info.setProperty("user","root");
    info.setProperty("password","000000");
    Connection conn = driver.connect("jdbc:mysql://localhost:3306/test",info);
    System.out.println(conn);
}

相较于方式一,这里使用反射实例化Driver,不在代码中体现第三方数据库的API。体现了面向接口编程思想。

连接方式三:

@Test
public void connection03() throws Exception{
    String url = "jdbc:mysql://localhost:3306/test";
    String user = "root";
    String password = "000000";
    Class clazz = Class.forName("com.mysql.jdbc.Driver");
    Driver driver = (Driver) clazz.newInstance();
    DriverManager.registerDriver(driver);
    Connection conn = DriverManager.getConnection(url,user,password);
    System.out.println(conn);
}

使用DriverManager实现数据库的连接。体会获取连接必要的4个基本要素。

连接方式四:

@Test
public void connection04() throws Exception{
    String url = "jdbc:mysql://localhost:3306/test";
    String user = "root";
    String password = "000000";

// Class clazz = Class.forName(“com.mysql.jdbc.Driver”);
// Driver driver = (Driver) clazz.newInstance();
// DriverManager.registerDriver(driver);
Connection conn = DriverManager.getConnection(url,user,password);
System.out.println(conn);
}
不必显式的注册驱动了。因为在DriverManager的源码中已经存在静态代码块,实现了驱动的注册。

连接方式五:

@Test
/*
* 好处:1、实现数据与代码分离,实现了解耦
*       2、如果需要修改配置文件信息,可以避免程序重新打包
* */
public void connection05() throws Exception{
    InputStream is = Test.class.getClassLoader().getResourceAsStream("jdbc.properties");
    Properties p = new Properties();
    p.load(is);
    String url = p.getProperty("url");
    String user = p.getProperty("user");
    String password = p.getProperty("password");
    String driver = p.getProperty("driverClass");

    Class.forName(driver);
    Connection conn = DriverManager.getConnection(url,user,password);
    System.out.println(conn);

}

其中,配置文件声明在工程的src目录下:【jdbc.properties】

四、CRUD操作
什么是CRUD?

C:Create(增加) 对应 create table table_name;
R:Retrieve(查询)对应 select * from table_name;
U:Update(更新) 对应 update table_name set elem1=value1 where id=value2;
D:Delete(删除)对应 delete from table_name where id=value1;
通用的增删改操作:

// 通用——增删改数据库
public static void executeSql(String sql ,Object ...args) throws Exception{
    // 1 获取数据库连接
    Connection conn = getConnection();
    // 2 创建PreparedStatement对象进行sql预编译
    PreparedStatement ps = conn.prepareStatement(sql);
    // 3 补充占位符
    for (int i = 0; i <args.length ; i++) {
        ps.setObject(i+1,args[i]);
    }
    // 4 执行
    ps.execute();
    // 5 关闭接口
    conn.close();
    ps.close();
}

通用的查询操作:

// 通用查询操作
public static <T> List<T> querySql(Class<T> clazz,String sql, Object ...args) throws Exception{
    // 1 创建对象集合
    List<T> list = new ArrayList<T>();
    // 2 连接数据库
    Connection conn = getConnection();
    // 3 补充占位符
    PreparedStatement ps = conn.prepareStatement(sql);
    for (int i = 0; i < args.length ; i++) {
        ps.setObject(i+1,args[i]);
    }
    // 4  获取查询数据集
    ResultSet rs = ps.executeQuery();
    // 5 获取元数据
    ResultSetMetaData rsmd = rs.getMetaData();
    // 6 获取列数
    int columnCount = rsmd.getColumnCount();

    while(rs.next()){
        T t = clazz.newInstance();
        for (int i = 0; i < columnCount ; i++) {
            Object columnValue = rs.getObject(i+1);
            String columnName = rsmd.getColumnLabel(i+1);
            Field field = clazz.getDeclaredField(columnName);
            field.setAccessible(true);
            field.set(t,columnValue);
        }
        list.add(t);
    }
    conn.close();
    ps.close();
    rs.close();
    return list;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Tzhu1987

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值