1、JDBC中如何获取数据库链接Connection?

Driver 是一个接口: 数据库厂商必须提供实现的接口. 能从其中获取数据库连接.

可以通过 Driver 的实现类对象获取数据库连接.

1. 加入 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 加入到类路径下.s

几种常用数据库的JDBC URL:

@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", "1230"); //3. 调用 Driver 接口的 connect(url, info) 获取数据库连接 Connection connection = driver.connect(url, info); System.out.println(connection);
}

获取数据库链接最简单方法

/**
JDBC.properties文件中的内容: #driver=oracle.jdbc.driver.OracleDriver
#jdbcUrl=jdbc:oracle:thin:@localhost:1521:orcl
#user=scott
#password=java driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/atguigu
user=root
password=1230
*/ public Connection getConnection() throws Exception{ String driverClass = null;
String jdbcUrl = null;
String user = null;
String password = null; //读取类路径下的 jdbc.properties 文件
InputStream in =
getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(in);
driverClass = properties.getProperty("driver");
jdbcUrl = properties.getProperty("jdbcUrl");
user = properties.getProperty("user");
password = properties.getProperty("password"); //通过反射常见 Driver 对象.
Driver driver =
(Driver) Class.forName(driverClass).newInstance();
Properties info = new Properties();
info.put("user", user);
info.put("password", password); //通过 Driver 的 connect 方法获取数据库连接. Connection connection = driver.connect(jdbcUrl, info);
return connection;
} @Test
public void testGetConnection() throws Exception{
System.out.println(getConnection());
}

在不修改源程序的情况下,获取任何数据库链接的通用方法(原始方法)

解决方案: 把数据库驱动 Driver 实现类的全类名、url、user、password 放入一个

配置文件中, 通过修改配置文件的方式实现和具体的数据库解耦.

    @Test
public void testDriverManager() throws SQLException, IOException {
String driverClass = null;
String jdbcUrl = null;
String user = null;
String password = null;
InputStream in = getClass().getClassLoader().getResourceAsStream(
"jdbc.properties");
Properties proper = new Properties();
proper.load(in);
driverClass = proper.getProperty("driver");
jdbcUrl = proper.getProperty("jdbcUrl");
user = proper.getProperty("user");
password = proper.getProperty("password");
Connection connection = DriverManager.getConnection(jdbcUrl, user,
password);
System.out.println(connection); }

使用DriverManager获取数据库链接的方法

    @Test
public void testDriverManager() throws ClassNotFoundException, SQLException {
String driverClass = "com.mysql.jdbc.Driver";
// String driverClass2 = "oracle.jdbc.driver.OracleDriver"; String jdbcUrl = "jdbc:mysql://localhost:3306/test";
// String jdbcUrl2 = "jdbc:oracle:thin:@localhost:1521:orcl"; String user = "root";
// String user2 = "scott"; String password = "123";
// String password2 = "tiger";
Class.forName(driverClass);
Connection connection = DriverManager.getConnection(jdbcUrl, user,
password);
System.out.println(connection);
}

更为简便的使用DriverManager获取数据库链接的方法

 @Test
public void testGetConnection2() throws Exception{
System.out.println(getConnection2());
} public Connection getConnection2() throws Exception{
//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);
}

获取数据库连接的最终版本,既解耦又利用到了DriverManager

2、如何通过 JDBC 向指定的数据表中插入一条记录?
 1. 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 = getConnection2(); //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();
}
} }

通过Statement获取连接,执行更新操作(包括insert,update,delete

    public void update(String sql){
Connection conn = null;
Statement statement = null;
String sql = null; try {
conn = JDBCTools.getConnection();
statement = conn.createStatement();
statement.executeUpdate(sql);
} catch (Exception e) {
e.printStackTrace();
} finally{
JDBCTools.release(statement, conn);
}
}

通用的更新的方法: 包括 INSERT、UPDATE、DELETE(即是要建立一个数据库工具类:获取数据库连接,关闭连接)

package com.shellway.jdbc;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties; /**
* 操作 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();
}
}
} /**
* 1. 获取连接的方法. 通过读取配置文件从数据库服务器获取一个连接.
*
* @return
* @throws Exception
*/
public static Connection getConnection() throws Exception {
// 1. 准备连接数据库的 4 个字符串.
// 1). 创建 Properties 对象
Properties properties = new Properties(); // 2). 获取 jdbc.properties 对应的输入流
InputStream in = JDBCTools.class.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);
} }

附上:要建立的数据库工具类:JDBCTools 

3、总结:

1、Connection:代表应用程序和数据库的一个连接.

2、Statement:是用于操作 SQL 的对象.

3、ResultSet:封装 JDBC 的查询结果.

package com.shellway.jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.security.interfaces.RSAKey;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties; import org.junit.Test; public class ReviewTest { /**
* 1. ResultSet 封装 JDBC 的查询结果.
*/
@Test
public void testResultSet(){ Connection connection = null;
Statement statement = null;
ResultSet resultSet = null; try {
//1. 获取数据库连接
connection = getConnection(); //2. 调用 Connection 对象的 createStatement() 方法获取 Statement 对象
statement = connection.createStatement(); //3. 准备 SQL 语句
String sql = "SELECT id, name, email, birth FROM customers"; //4. 发送 SQL 语句: 调用 Statement 对象的 executeQuery(sql) 方法.
//得到结果集对象 ResultSet
resultSet = statement.executeQuery(sql); //5. 处理结果集:
//5.1 调用 ResultSet 的 next() 方法: 查看结果集的下一条记录是否有效,
//若有效则下移指针
while(resultSet.next()){
//5.2 getXxx() 方法获取具体的列的值.
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
String email = resultSet.getString(3);
Date birth = resultSet.getDate(4); System.out.println(id);
System.out.println(name);
System.out.println(email);
System.out.println(birth); System.out.println();
} } catch (Exception e) {
e.printStackTrace();
} finally{
//6. 关闭数据库资源
releaseDB(resultSet, statement, connection);
}
} /**
* 1. Statement 是用于操作 SQL 的对象
*/
@Test
public void testStatement(){
Connection connection = null;
Statement statement = null; try {
//1. 获取数据库连接
connection = getConnection(); //2. 调用 Connection 对象的 createStatement() 方法获取 Statement 对象
statement = connection.createStatement(); //3. 准备 SQL 语句
String sql = "UPDATE customers SET name = 'Jerry' " +
"WHERE id = 5"; //4. 发送 SQL 语句: 调用 Statement 对象的 executeUpdate(sql) 方法
statement.executeUpdate(sql); } catch (Exception e) {
e.printStackTrace();
} finally{
//5. 关闭数据库资源: 由里向外关闭.
releaseDB(null, statement, connection);
}
} public void releaseDB(ResultSet resultSet, Statement statement,
Connection connection){ if(resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
} if(statement != null){
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
} if(connection != null){
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
} @Test
public void testGetConnection2() throws Exception{ Connection connection = getConnection(); System.out.println(connection);
} public Connection getConnection() throws IOException,
ClassNotFoundException, SQLException {
//0. 读取 jdbc.properties
/**
* 1). 属性文件对应 Java 中的 Properties 类
* 2). 可以使用类加载器加载 bin 目录(类路径下)的文件
*/
Properties properties = new Properties();
InputStream inStream = ReviewTest.class.getClassLoader()
.getResourceAsStream("jdbc.properties");
properties.load(inStream); //1. 准备获取连接的 4 个字符串: user, password, jdbcUrl, driverClass
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String jdbcUrl = properties.getProperty("jdbcUrl");
String driverClass = properties.getProperty("driverClass"); //2. 加载驱动: Class.forName(driverClass)
Class.forName(driverClass); //3. 调用
//DriverManager.getConnection(jdbcUrl, user, password)
//获取数据库连接
Connection connection = DriverManager
.getConnection(jdbcUrl, user, password);
return connection;
} /**
* Connection 代表应用程序和数据库的一个连接.
* @throws Exception
*/
@Test
public void testGetConnection() throws Exception{
//1. 准备获取连接的 4 个字符串: user, password, jdbcUrl, driverClass
String user = "root";
String password = "123";
String jdbcUrl = "jdbc:mysql:///test";
String driverClass = "com.mysql.jdbc.Driver"; //2. 加载驱动: Class.forName(driverClass)
Class.forName(driverClass); //3. 调用
//DriverManager.getConnection(jdbcUrl, user, password)
//获取数据库连接
Connection connection = DriverManager
.getConnection(jdbcUrl, user, password); System.out.println(connection);
}
}

总复习(包括获取与数据库的连接Connection,然后创建Statement,最后得到结果集ResultSet)

jdbc.properties文件内容:

user=root
password=123
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/test

#user=scott
#password=tiger
#driverClass=oracle.jdbc.driver.OracleDriver
#jdbcUrl=jdbc:oracle:thin:@127.0.0.1:1521:orcl

吾时而躬身自省,自省使知已之不足,知不足而奋起,未为晚也!

java攻城狮之路--复习JDBC的更多相关文章

  1. java攻城狮之路--复习JDBC(数据库连接池 : C3P0、DBCP)

    复习数据库连接池 : C3P0.DBCP 1.数据库连接池技术的优点: •资源重用:      由于数据库连接得以重用,避免了频繁创建,释放连接引起的大量性能开销.在减少系统消耗的基础上,另一方面也增 ...

  2. java攻城狮之路--复习JDBC(利用BeanUtils、JDBC元数据编写通用的查询方法;元数据;Blob;事务;批量处理)

    1.利用BeanUtils的前提得要加入以下两个jar包: commons-beanutils-1.8.0.jar commons-logging-1.1.1.jar package com.shel ...

  3. java攻城狮之路--复习JDBC(PrepareStatement)

    PreparedStatement: 1.可以通过调用 Connection 对象的 preparedStatement() 方法获取 PreparedStatement 对象 2.PreparedS ...

  4. java攻城狮之路--复习xml&dom_pull编程续

    本章节我们要学习XML三种解析方式: 1.JAXP DOM 解析2.JAXP SAX 解析3.XML PULL 进行 STAX 解析 XML 技术主要企业应用1.存储和传输数据 2.作为框架的配置文件 ...

  5. java攻城狮之路--复习xml&dom_pull编程

    xml&dom_pull编程: 1.去掉欢迎弹窗界面:在window项的preferences选项中输入“configuration center” 找到这一项然后     把复选框勾去即可. ...

  6. java攻城狮之路(Android篇)--BroadcastReceiver&Service

    四大组件:activity 显示. contentProvider 对外暴露自己的数据给其他的应用程序.BroadcastReceiver 广播接收者,必须指定要接收的广播类型.必须明确的指定acti ...

  7. java攻城狮之路(Android篇)--Activity生命

    一:Activity的激活 1.写一个类 extends Activity Activity是android的四大组件之一.Activity的激活分为显式意图激活和隐式意图激活.如果一个activit ...

  8. java攻城狮之路(Android篇)--与服务器交互

    一.图片查看器和网页源码查看器 在输入地址的是不能输入127.0.0.1 或者是 localhost.ScrollView :可以看成一个滚轴 可以去包裹很多的控件在里面 练习1(图片查看器): pa ...

  9. java攻城狮之路(Android篇)--widget_webview_metadata_popupwindow_tabhost_分页加载数据_菜单

    一.widget:桌面小控件1 写一个类extends AppWidgetProvider 2 在清单文件件中注册: <receiver android:name=".ExampleA ...

随机推荐

  1. codeforces gym 100357 K (表达式 模拟)

    题目大意 将一个含有+,-,^,()的表达式按照运算顺序转换成树状的形式. 解题分析 用递归的方式来处理表达式,首先直接去掉两边的括号(如果不止一对全部去光),然后找出不在括号内且优先级最低的符号.如 ...

  2. springMVC 返回中文字符串时乱码

    转载自:https://blog.csdn.net/yaov_yy/article/details/51819567

  3. 安全简单解决MVC 提示 检测到有潜在危险的 Request.Form 值.

    一般使用富文本编辑器的时候.提交的表单中包含HTML字符,就会出现此错误提示. 使用 ValidateInput(false) 特性标签并不能解决此问题. 网上前篇一律的回答是修改Web.Config ...

  4. SpriteBuilder&amp;Cocos2D使用CCEffect特效实现天黑天亮过度效果

    大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 假设认为写的不好请多提意见,假设认为不错请多多支持点赞.谢谢! hopy ;) 在动作或RPG类游戏中我们有时须要天黑和天亮过度的效果来完毕场 ...

  5. C++学习之new与delete、malloc与free

    在C/C++的面试时,对于new/delete和malloc/free这两对的使用和区别经常被考查到,如果这种基础的问题都答不上来,估计很难过面试了.这篇文章仅仅是浅显的讲一下,仅供参考. 一.new ...

  6. 解析cocos2d-lua项目中的Hello World

    创建完cocos2d-x的lua项目后.打开项目的Resources目录,找到hello.lua.cocos2d-x的lua项目的測试样例主要就是由这个脚本文件运行的. require "A ...

  7. 【Codeforces 429D】 Tricky Function

    [题目链接] http://codeforces.com/problemset/problem/429/D [算法] 令Si = A1 + A2 + ... + Ai(A的前缀和) 则g(i,j) = ...

  8. 第三周 Leetcode 4. Median of Two Sorted Arrays (HARD)

    4. Median of Two Sorted Arrays 给定两个有序的整数序列.求中位数,要求复杂度为对数级别. 通常的思路,我们二分搜索中位数,对某个序列里的某个数 我们可以在对数时间内通过二 ...

  9. RDA 升级

    烧录BOOT升级方式: 1.连接 2.烧录BOOT 1)升级“bootrom_raw.bin” 99K,这种升级方式需要Tera Term 工具,按“F5”  U盘升级. 编译的升级文件“RR8503 ...

  10. 关于pycharm中pip版本10.0无法使用的解决办法

    背景: 近期在利用 pycharm 安装第三方库时会提示 pip 不是最新版本, 因此对 pip 进行更新,但是生成最新版本之后, pip 中由于缺少 main 函数,导致在 pycharm 中无法自 ...