话不多说,直接开撸代码。

1.首先自己的环境使用的是maven项目+idea工具+mysql8.0.18 (使用maven项目的好处就是方便,不用手动导入相关的驱动包,在pom.xml配置即可)

2.第一步:在pom中导入mysql的驱动包(这里注意跟mysql的版本,导入驱动包的版本也不一样,我是用的是8.0.18版本,需要导入5.1.48版本)

 <!--jdbc驱动包-->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>

3.第二步:建立一个TestDriver.java来写测试用例(结论写在代码里面)

  3.1 通过Diriver实现类对象获取连接

   /**
* 注意:我这里是maven项目。通过Diriver实现类对象获取连接。
* 1.首先引入jdbc的驱动jar包,我本地用的是mysql8版本。导入mysql-connector-java,版本为5.1.48+
* 2.然后创建一个Diriver实现类的对象
* 3.准备连接数据基本信息
* 4.调用Driver接口的connect方法,连接数据库
*
* @throws SQLException
*/
@Test
public void testDriver1() throws SQLException {
//1.创建一个Diriver实现类的对象
Driver driver = new Driver(); //2.准备连接数据基本信息
String url = "jdbc:mysql://localhost:3306/test";
Properties properties = new Properties();
properties.put("user", "root");
properties.put("password", "root"); //3.调用Driver接口的connect连接数据库
Connection connect = driver.connect(url, properties);
System.out.println(connect);
}

    3.2 在前面的基础上,将数据库基本信息写成jdbc.properties配置文件,进行读取(配置文件需要放在根目录下进行读取

/**
*
* 1.首先引入jdbc的驱动jar包,我本地用的是mysql8版本。导入mysql-connector-java为5.1.48
* 2.创建一个jdbc.properties文件
* 3.定义一个方法读取jdbc.properties文件,并在该方法创建连接
* 4.调用方法,返回Driver接口的connect连接数据库
*
* @throws Exception
*/
@Test
public void testDriver2() throws Exception {
Connection connection = getConnection();
System.out.println(connection);
} /**
* 1.把配置连接放入到一个jdbc.properties文件中,然后统一读取。解耦合
* 2.读取properties文件中的连接信息
* 3.创建连接
*
* @return
*/
public Connection getConnection() throws Exception, ClassNotFoundException, IllegalAccessException, InstantiationException {
//1.首先定义本地变量
String driverClass = null;
String jdbcUrl1 = null;
String user = null;
String password = null; //2.读取类路径下的jdbc.properties,此配置文件需要放置到resources文件夹下。
InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(resourceAsStream); //3.分别获取配置对象的值
driverClass = properties.getProperty("driver");
jdbcUrl1 = properties.getProperty("jdbcUrl");
user = properties.getProperty("user");
password = properties.getProperty("password"); //4.通过反射拿到Driver连接对象
Driver driver = (Driver) Class.forName(driverClass).newInstance(); Properties info = new Properties();
info.put("user", user);
info.put("password", password); //获取连接
Connection connect = driver.connect(jdbcUrl1, info);
return connect;
}

  3.3  通过DriverManager驱动的管理类来获取Connection对象,从而实现连接数据库

 /**
* DriverManager是驱动的而管理类
* 好处:
* 1.通过 DriverManager,可以重载getConnection()方法获取数据库连接,较为方便
* 2.可以同时管理多个驱动程序:若注册了多个数据库连接,则调用getConnection()方法时,传入的参数不同,即返回的连接不同。
* <p>
* 可以通过单独封装成一个方法,从jdbc.properties中进行读取
*/
@Test
public void testDriverManager3() throws Exception { //1.准备连接数据库的4个连接信息(mysql配置信息)
String driverClass = "com.mysql.jdbc.Driver";
String jdbcUrl1 = "jdbc:mysql://localhost:3306";
String user = "root";
String password = "root"; //1.准备连接数据库的4个连接信息(假设是oracle的配置信息,模拟用,其实还是mysql的。)
String driverClass2 = "com.mysql.jdbc.Driver";
String jdbcUrl2 = "jdbc:mysql://localhost:3306";
String user2 = "root";
String password2 = "root"; //加载数据库驱动
//这里使用Class.forName方法直接注册驱动,因为对应的Driver中有注册驱动的静态代码快
//DriverManager.registerDriver((java.sql.Driver) Class.forName(driverClass).newInstance());
//注册mysql的驱动
Class.forName(driverClass);
//注册oracle的驱动
Class.forName(driverClass2); //得到mysql的连接
Connection connection = DriverManager.getConnection(jdbcUrl1, user, password); //得到oracle的连接
Connection connection2 = DriverManager.getConnection(jdbcUrl2, user2, password2); System.out.println(connection);
System.out.println(connection2);
}

  3.4 在上面创建了连接后,下面就是,通过jdbc想指定数据表中插入一条记录:

 /**
* 在上面创建了连接后,下面就是:
* 通过jdbc想指定数据表中插入一条记录
* 1.Connection和Statement都是应用程序和数据库服务器的连接资源,使用后需要关闭
* 2.需要注意在出现异常的情况下,来进行try catch来进行关闭
* 3.executeUpdate中可以为insert,update,delete。但是不能为select
* 4.关闭的顺序是,先获取的后关闭,先关闭Statement,后关闭Connection
*/
@Test
public void testStatement4() throws Exception {
//1.获取数据库连接
Connection connection = null; Statement statement = null; connection = getConnection(); try {
//2.准备插入的sql预计
//插入插座
//String sql = " insert into customers (name,email,brith) values (11,222,'2019-10-23')";
//删除操作
//String sql = " delete from customers where id =3";
//更新操作
String sql = " update customers set name ='罗杰', email='117@qq/com' ,brith='1995-05-21' where id=6"; //3.执行插入,添加,删除
//3.1获取操作sql语句的Statement对象,调用Connection的createStatement()方法来获取
statement = connection.createStatement();
//3.2调用Statement对象的executeUpdate(sql)执行sql语句进行插入
int i = statement.executeUpdate(sql);
System.out.println("执行结果返回值:"+i);
} catch (SQLException e) {
e.printStackTrace();
} finally {
//4.关闭Statement对象
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//5.关闭连接
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

3.5 在上一个基础上,封装了一个JdbcTools方法,通过工具类来进行获取链接和关闭来链接

 /**
* 在上一个基础上,封装了一个JdbcTools方法,通过工具类来进行获取链接和关闭来链接
* @throws Exception
*/
@Test
public void testStatementUseTools5() throws Exception{
//1.通过工具类获取jdbc连接
Connection connection = JdbcTools.getConnection();
//2.创建Statement对象
Statement statement = connection.createStatement();
try {
//2.准备插入的sql预计
//插入插座
//String sql = " insert into customers (name,email,brith) values (11,222,'2019-10-23')";
//删除操作
//String sql = " delete from customers where id =3";
//更新操作
String sql = " update customers set name ='小黑', email='117@qq/com' ,brith='1995-05-21' where id=6"; //3.执行插入,添加,删除
//3.1获取操作sql语句的Statement对象,调用Connection的createStatement()方法来获取
//3.2调用Statement对象的executeUpdate(sql)执行sql语句进行插入
int i = statement.executeUpdate(sql);
System.out.println(i);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcTools.release(connection,statement);
} }

工具类代码如下:

 package testhutool.jdbc;

 import com.mysql.jdbc.Driver;

 import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties; /**
* jdbc的工具方法
*/
public class JdbcTools {
/**
* 1.获取连接的公共方法
* 通过读取配置文件,获取连接
*
* @return
* @throws Exception
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static Connection getConnection() throws Exception, ClassNotFoundException, IllegalAccessException, InstantiationException {
//首先定义本地变量
String driverClass = null;
String jdbcUrl1 = null;
String user = null;
String password = null; //读取类路径下的jdbc.properties,此配置文件需要放置到resources文件夹下。
InputStream resourceAsStream = Class.forName("testhutool.jdbc.JdbcTools").getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(resourceAsStream); //分别获取配置对象的值
driverClass = properties.getProperty("driver");
jdbcUrl1 = 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); //获取连接
Connection connect = driver.connect(jdbcUrl1, info); return connect; } /**
* 关闭连接资源
* @param connection
* @param statement
*/
public static void release(Connection connection, Statement statement) {
release(null,connection,statement);
} /**
* 关闭连接资源
* @param resultSet 结果集
* @param connection 数据库连接对象
* @param statement
*/
public static void release(ResultSet resultSet,Connection connection, Statement statement) { //3.关闭resultSet对象
if (resultSet != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
} //4.关闭Statement对象
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//5.关闭连接
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
} }
}

3.6 最后就是通过RecordSet获取结果集,分别遍历获取结果:

 /**
* ResultSet来获取结果集,封装了使用jdnc进行查询的结果
* 1.调用了Statement对象的executeQuery(sql),可以得到结果集
* 2.ResultSet返回的实际上是一张数据表,有一个指针指向数据表的第一行的前面
* 可以调用next()方法。来检测下一行是否有效,如果该方法有效,且指针下移,相当于Iterator对象的hasNext和next的结合体
* 3.当指针到下一行的时候,可以通过gteXxx(index)或者getXxx(columnName)获取每一列的值。
* 4.ResultSet当然也需要进行关闭
*/
@Test
public void testResultSet6() throws Exception{ //获取id=6的customers的数据表数据,并打印
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null; //1.获取连接Connection
connection = JdbcTools.getConnection();
//2.获取Statement
statement = connection.createStatement();
//3.准备SQL
String sql = "select * from customers";
//4.执行查询。得到ResultSet结果集
resultSet = statement.executeQuery(sql);
//5.处理ResultSet
while(resultSet.next()){ int id = resultSet.getInt(1);
String name = resultSet.getString("name");
String email = resultSet.getString("email");
Date brith = resultSet.getDate("brith");
String brith1 = resultSet.getString("brith");
System.out.println("id:"+id+",name:"+name+",email:"+email+",brith:"+brith+",brith1:"+brith1); } //6.关闭数据库资源
JdbcTools.release(resultSet,connection,statement);
}

总结:通过上面的基础的获取Connection连接,获取Statement对象,ResultSet对象。简单封装了工具类方法,完成的java到数据库的增删改查。

最新文章

  1. UpdatePanel无法导出下载文件
  2. UVA11149_Power of Matrix
  3. Tomcat6.0的Thisisverylikelytocreateamemoryleak异常
  4. 【Shell脚本学习5】第一个Shell脚本
  5. Dreamweaver中清除php代码中多余空行的方法
  6. Android 自定义回调
  7. win7_32位安装MySQL_5.6以及密码修改方法
  8. Zepto
  9. 关于css起名
  10. iOS获取设备型号和App版本号等信息(OC+Swift)
  11. JAVA提高十三:Hashtable&amp;Properties深入分析
  12. Linq学习系列-----1.2 一个简单方法的改进思考及不同的执行形式
  13. MSIL实用指南-装箱拆箱
  14. TimesTen数据库的备份和恢复
  15. JavaScript模块载入框架sea.js 学习一
  16. jquery获取select多选框选中的值
  17. 洛谷 P3956 棋盘(BFS)
  18. 盐水的故事(hdu1408)
  19. LOJ1070(SummerTrainingDay05-B 矩阵快速幂)
  20. ps叠加模式笔记

热门文章

  1. java读取Excel —— XSSFWorkbook 找不到该类
  2. 解决ie6上碰到的css兼容问题
  3. STM32的RTC中断标志只能手动清除
  4. 弄懂Java为何只有值传递
  5. day 12 特殊权限
  6. 如何使用WordPress搭建个人博客
  7. 运用 CSS in JS 实现模块化
  8. 夯实Java基础系列3:一文搞懂String常见面试题,从基础到实战,更有原理分析和源码解析!
  9. 通过python代码对域名ssl证书进行监控
  10. Nginx安装教程,ubuntu18.04