JDBC的使用(一)

news/2024/7/7 16:26:28
Java 中的数据存储技术
       在Java中,数据库存取技术可分为如下几类:
          ①JDBC直接访问数据库
          ②JDO技术
          ③第三方O/R工具,如Hibernate, ibatis 等

       JDBC是java访问数据库的基石,JDO, Hibernate等只是更好的封装了JDBC。


几种常用数据库的JDBC URL
对于 Oracle 数据库连接,采用如下形式: jdbc:oracle:thin:@localhost:1521:sid

对于 SQLServer 数据库连接,采用如下形式: jdbc:microsoft:sqlserver//localhost:1433; DatabaseName=sid

对于 MYSQL 数据库连接,采用如下形式:   jdbc:mysql://localhost:3306/sid


连接mysql数据库
加入 mysql 驱动
1). 解压 mysql-connector-java-5.1.7.zip 
2).在当前项目下新建 lib 目录 
3).把 mysql-connector-java-5.1.7-bin.jar 复制到 lib 目录下
4).右键 build-path , add to buildpath 加入到类路径下


1.Driver连接数据库

        1. 创建一个 Driver 实现类的对象
        Driver driver = new com.mysql.jdbc.Driver();
        2. 准备连接数据库的基本信息: url, user, password
        String url = "jdbc:mysql://localhost:3306/test";
        Properties info = new Properties();
        info.put("user", "root");
        info.put("password", "123456");
        3. 调用 Driver 接口的 connect(url, info) 获取数据库连接
        Connection connect = driver.connect(url, info);
        System.out.println(connect);

        完整代码:

@Test
public void testDriver() throws SQLException {
//1. 创建一个 Driver 实现类的对象
Driver driver = new com.mysql.jdbc.Driver();
//2. 准备连接数据库的基本信息: url, user, password
String url = "jdbc:mysql://localhost:3306/test";
Properties info = new Properties();
info.put("user", "root");
info.put("password", "123456");
//3. 调用 Driver 接口的 connect(url, info) 获取数据库连接
Connection connect = driver.connect(url, info);
System.out.println(connect);
}

编写一个通用的方法, 在不修改源程序的情况下, 可以获取任何数据库的连接
解决方案: 把数据库驱动 Driver 实现类的全类名、url、user、password 放入一个配置文件中, 通过修改配置文件的方式实现和具体的数据库解耦.


通用方法代码

public Connection getConnection() throws Exception {
String driverClass = null;
String jdbcUrl = null;
String user = null;
String password = null;
//读取类路径下的 jdbc.properties 文件
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties=new Properties();
properties.load(inputStream);
user=properties.getProperty("user");
driverClass=properties.getProperty("driver");
jdbcUrl=properties.getProperty("jdbcUrl");
password = properties.getProperty("password");
//通过反射常见 Driver 对象
Driver diver = (Driver) Class.forName(driverClass).newInstance();
Properties info=new Properties();
info.put("user", user);
info.put("password", password);
//通过 Driver 的 connect 方法获取数据库连接. 
Connection connect = diver.connect(jdbcUrl, info);
return connect;
}
  新建文件(jdbc.properties)

driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/test
user=root
password=123456

2.DriverManager连接数据库
1).可以通过重载的 getConnection() 方法获取数据库连接. 较为方便 
1.准备连接数据库的四个字符串

                            //JDBC URL
       String jdbcUrl = "jdbc:mysql://localhost:3306/test";
                       //user
                       String user = "root";
                       //password
                        String password = "123456";
            // 1. 准备连接数据库的 4 个字符串.
           // 驱动的全类名.
           String driverClass = "com.mysql.jdbc.Driver";
           2.加载数据库驱动程序:Class.forName(driverClass);
           3. 通过 DriverManager 的 getConnection() 方法获取数据库连接: 

                      Connection connection = DriverManager.getConnection(jdbcUrl, user,password);


2).可以同时管理多个驱动程序: 若注册了多个数据库连接, 则调用 getConnection() 方法时传入的参数不同, 即返回不同的数据库连接。
1. 准备连接数据库的 4 个字符串. 

                                //1). 创建 Properties 对象
Properties properties = new Properties();

//2). 获取 jdbc.properties 对应的输入流
InputStream in = 
this.getClass().getClassLoader().getResourceAsStream("jdbc.properties");

//3). 加载 2) 对应的输入流
properties.load(in);

//4). 具体决定 user, password 等4 个字符串. 
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String jdbcUrl = properties.getProperty("jdbcUrl");
String driver = properties.getProperty("driver");


2. 加载数据库驱动程序(对应的 Driver 实现类中有注册驱动的静态代码块.):Class.forName(driver);


3. 通过 DriverManager 的 getConnection() 方法获取数据库连接:                    

                       return DriverManager.getConnection(jdbcUrl, user, password);


 3. Statement: 用于执行 SQL 语句的对象 
1). 通过 Connection 的 createStatement() 方法来获取
2). 通过 executeUpdate(sql) 可以执行 SQL 语句. 3). 传入的 SQL 可以是 INSRET, UPDATE 或DELETE. 但不能是 SELECT
2. Connection、Statement 都是应用程序和数据库服务器的连接资源. 使用后一定要关闭. 需要在 finally 中关闭Connection 和 Statement 对象.
3. 关闭的顺序是: 先关闭后获取的. 即先关闭 Statement 后关闭 Connection

          结果代码:

           @Test
    public void testStatement() throws Exception {
//1. 获取数据库连接
Connection conn = null;
Statement statement = null;

try {
conn = getConnection();

//3. 准备插入的 SQL 语句
String sql = null;

// sql = "INSERT INTO customers (NAME, EMAIL, BIRTH) " +
// "VALUES('XYZ', 'xyz@atguigu.com', '1990-12-12')";
// sql = "DELETE FROM customers WHERE id = 1";
sql = "UPDATE customers SET name = 'TOM' " +
"WHERE id = 4";
System.out.println(sql);

//4. 执行插入. 
//1). 获取操作 SQL 语句的 Statement 对象: 
//调用 Connection 的 createStatement() 方法来获取
statement = conn.createStatement();

//2). 调用 Statement 对象的 executeUpdate(sql) 执行 SQL 语句进行插入
statement.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
//5. 关闭 Statement 对象.
if(statement != null)
statement.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
//2. 关闭连接
if(conn != null)
conn.close();
}
}
}


ResultSet: 结果集. 封装了使用 JDBC 进行查询的结果. 

1. 调用 Statement 对象的 executeQuery(sql) 可以得到结果集.
2. ResultSet 返回的实际上就是一张数据表. 有一个指针指向数据表的第一样的前面.可以调用 next() 方法检测下一行是否有效. 若有效该方法返回 true, 且指针下移. 相当于Iterator 对象的 hasNext() 和 next() 方法的结合体
3. 当指针对位到一行时, 可以通过调用 getXxx(index) 或 getXxx(columnName)
获取每一列的值. 例如: getInt(1), getString("name")
4. ResultSet 当然也需要进行关闭

               完整代码:

         @Test
public void testResultSet(){
//获取 id=4 的 customers 数据表的记录, 并打印

Connection conn = null;
Statement statement = null;
ResultSet rs = null;

try {
//1. 获取 Connection
conn = JDBCTools.getConnection();
System.out.println(conn);

//2. 获取 Statement
statement = conn.createStatement();
System.out.println(statement);

//3. 准备 SQL
String sql = "SELECT id, name, email, birth " +
"FROM customers";

//4. 执行查询, 得到 ResultSet
rs = statement.executeQuery(sql);
System.out.println(rs);

//5. 处理 ResultSet
while(rs.next()){
int id = rs.getInt(1);
String name = rs.getString("name");
String email = rs.getString(3);

System.out.println(id);
System.out.println(name);
System.out.println(email);
}

} catch (Exception e) {
e.printStackTrace();
} finally{
//6. 关闭数据库资源. 
JDBCTools.release(rs, statement, conn);
}

}


操作 JDBC 的工具类. 其中封装了一些工具方法 Version 1

         public class JDBCTools {
public static void release(ResultSet rs, Statement statement,
Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}


if (statement != null) {
try {
statement.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}


if (conn != null) {
try {
conn.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}


/**
* 关闭 Statement 和 Connection

* @param statement
* @param conn
*/
public static void release(Statement statement, Connection conn) {
if (statement != null) {
try {
statement.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}


if (conn != null) {
try {
conn.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
}


/**
* 编写一个通用的方法, 在不修改源程序的情况下, 可以获取任何数据库的连接 解决方案: 把数据库驱动 Driver
* 实现类的全类名、url、user、password 放入一个 配置文件中, 通过修改配置文件的方式实现和具体的数据库解耦.

* @throws Exception
*/
public static Connection getConnection() throws Exception {
String driverClass = null;
String jdbcUrl = null;
String user = null;
String password = null;
// 读取类路径下的 jdbc.properties 文件
InputStream inputStream = JDBCTools.class.getClassLoader()
.getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(inputStream);
user = properties.getProperty("user");
driverClass = properties.getProperty("driver");
jdbcUrl = properties.getProperty("jdbcUrl");
password = properties.getProperty("password");


// 通过反射常见 Driver 对象
Driver diver = (Driver) Class.forName(driverClass).newInstance();
Properties info = new Properties();
info.put("user", user);
info.put("password", password);


// 通过 Driver 的 connect 方法获取数据库连接.
Connection connect = diver.connect(jdbcUrl, info);
return connect;
}
}


http://www.niftyadmin.cn/n/3649305.html

相关文章

若依项目(前后端分离)

最近在基于若依项目二次开发中,遇到表设计问题,然后看了若依想项目前后端分离视频中,也是不太懂表的设计问题

Android常用Adapter代码例子

ArrayAdapter   总是感觉写自己的博客才更能够学到东西,网上尽管有很多好的资料,但是参差不齐,需要浪费大量时间才能够找到最需要的,索性写自己最需要的东西。 Adapter是适配器的意思,在Android中大量的使用到了List…

node中的数据持久化之mongoDB

一、什么是mongoDB MongoDB是一种开源的非关系型数据库,正如它的名字所表示的,MongoDB支持的数据结构非常松散,是一种以bson格式(一种json的存储形式)的文档存储方式为主,支持的数据结构类型更加丰富的NoS…

在JavaScript中将toLocaleString与数字,数组或日期一起使用

toLocaleString is a built-in JavaScript method used to convert the date and time to a string using the system locales. 🤓🚀 toLocaleString是内置JavaScript方法,用于使用系统区域设置将日期和时间转换为字符串。 🤓&…

Android开发过程中的几个小知识点

1. 在程序的Manifest里面对应的Activity里面添加android:windowSoftInputMode"adjustResize"属性,可以实现打开输入法时,界面自动上移,不被输入法遮盖。 2. 添加按钮的按下效果时,可以在drawable文件夹下新建一个xml文件…

[dotNET]如何利用ConfigurationSettings.AppSettings.GetValues读取配置文件中多个同Key的value

编写者:郑昀Ultrapower默认情况下,string[] strArray System.Configuration.ConfigurationSettings.AppSettings.GetValues("Uri");是无法读取配置文件中多个同Key的value的。如下所示的配置:用MSDN告诉我们的GetValues是读不到的…

node.js 模块_如何创建Node.js模块

node.js 模块The author selected the Open Internet/Free Speech Fund to receive a donation as part of the Write for DOnations program. 作者选择了“ 开放互联网/言论自由基金会”作为“ Write for DOnations”计划的一部分来接受捐赠。 介绍 (Introduction) In Node.j…

[收藏]Matt Powell的《Server-Side 异步Web Methhods》

Server-Side 异步Web Methhods http://msdn.microsoft.com/library/en-us/dnservice/html/service10012002.asp?frametrueMatt PowellMicrosoft CorporationOctober 2, 2002摘要:Matt Powell 介绍了如何在服务器端使用异步 Web 方法,来创建高性能的 Mic…