Java基础102 完整的JDBC连接MySQL数据库和Oracle数据库的方法

Posted DSHORE

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java基础102 完整的JDBC连接MySQL数据库和Oracle数据库的方法相关的知识,希望对你有一定的参考价值。

本文知识点(目录):

    1、jdbc连接MySQL数据库
    2、jdbc连接Oracle数据库
    3、附录【本文jdbc连接MySQL或Oracle数据库的全部代码(合起来,做对比)】



1、JDBC连接mysql数据库  

1.1、我用到的jar包

1.2、实例演示

MySQL建表语句

1 -- MySQL建表语句
2 create table user(
3   id number(5) primary key auto_increment,
4   account varchar(20) not null,
5   password varchar(32) not null
6 );

db.properties 配置文件

1 jdbcDriver=com.mysql.jdbc.Driver
2 url=jdbc:mysql://localhost:3306/school
3 userName=root
4 password=123456

DBUtils 工具类(封装jdbc公共部分的代码)

  1 package com.shore.util;
  2 
  3 import java.io.IOException;
  4 import java.io.InputStream;
  5 import java.sql.Connection;
  6 import java.sql.DriverManager;
  7 import java.sql.PreparedStatement;
  8 import java.sql.ResultSet;
  9 import java.sql.SQLException;
 10 import java.sql.Statement;
 11 import java.util.Properties;
 12 
 13 /**
 14  * @author DSHORE/2020-1-15
 15  * 连接数据库--->工具类
 16  */
 17 public class DBUtils {
 18     
 19     private DBUtils() {
 20     }
 21 
 22     private static String jdbcDriver = "";
 23     private static String url = "";
 24     private static String userName = "";
 25     private static String password = "";
 26 
 27     static {
 28         Properties properties = new Properties();
 29         try {
 30             //读取配置文件(MySQL数据库)
 31             InputStream inputStream = DBUtils.class.getResourceAsStream("/db.properties");
 32             properties.load(inputStream); //加载配置文件
 33             inputStream.close();//关闭输入流
 34             
 35             //获取到对应参数的值
 36             jdbcDriver = properties.getProperty("jdbcDriver");
 37             url = properties.getProperty("url");
 38             userName = properties.getProperty("userName");
 39             password = properties.getProperty("password");
 40         } catch (IOException e1) {
 41             e1.printStackTrace();
 42         } finally {
 43             try {
 44                 Class.forName(jdbcDriver);
 45             } catch (ClassNotFoundException e) {
 46                 throw new ExceptionInInitializerError(e);
 47             }
 48         }
 49     }
 50 
 51     //连接数据库
 52     public static Connection getConnection() throws SQLException {
 53         Connection connection = null;
 54         try {
 55             connection = DriverManager.getConnection(url, userName, password);
 56         } catch (Exception e) {
 57             System.out.println(e.getMessage());//如果出现异常,则 把异常信息打印到控台上
 58         }
 59         return connection;
 60     }
 61 
 62     // 释放资源。   顺序:resultSet、statement、connection
 63     public static void free(ResultSet resultSet, Statement statement, Connection connection) {
 64         if (resultSet != null) {
 65             try {
 66                 resultSet.close();
 67             } catch (SQLException e) {
 68                 e.printStackTrace();
 69             } finally {
 70                 if (statement != null) {
 71                     try {
 72                         statement.close();
 73                     } catch (SQLException e) {
 74                         e.printStackTrace();
 75                     } finally {
 76                         if (connection != null) {
 77                             try {
 78                                 connection.close();
 79                             } catch (SQLException e) {
 80                                 e.printStackTrace();
 81                             }
 82                         }
 83                     }
 84                 }
 85             }
 86         }
 87     }
 88 
 89     // 释放资源。  顺序:resultSet、preparedStatement、connection
 90     public static void free(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) {
 91         if (resultSet != null) {
 92             try {
 93                 resultSet.close();
 94             } catch (SQLException e) {
 95                 e.printStackTrace();
 96             } finally {
 97                 if (preparedStatement != null) {
 98                     try {
 99                         preparedStatement.close();
100                     } catch (SQLException e) {
101                         e.printStackTrace();
102                     } finally {
103                         if (connection != null) {
104                             try {
105                                 connection.close();
106                             } catch (SQLException e) {
107                                 e.printStackTrace();
108                             }
109                         }
110                     }
111                 }
112             }
113         }
114     }
115 }

User 实体类

 1 package com.shore.entity;
 2 
 3 /**
 4  * @author DSHORE/2020-1-15
 5  * 
 6  */
 7 public class User {
 8     private Integer id;
 9     private String account;
10     private String password;
11 
12     public Integer getId() {
13         return id;
14     }
15 
16     public void setId(Integer id) {
17         this.id = id;
18     }
19 
20     public String getAccount() {
21         return account;
22     }
23 
24     public void setAccount(String account) {
25         this.account = account;
26     }
27 
28     public String getPassword() {
29         return password;
30     }
31 
32     public void setPassword(String password) {
33         this.password = password;
34     }
35 }

dao层

1 //接口
2 public interface IUserDao {
3     public int add(User user); //新增
4     public User findById(Integer id); //根据id查询
5 }
 1 package com.shore.dao.impl;
 2 
 3 import java.sql.Connection;
 4 import java.sql.PreparedStatement;
 5 import java.sql.ResultSet;
 6 import java.sql.Statement;
 7 
 8 import com.shore.dao.IUserDao;
 9 import com.shore.entity.User;
10 import com.shore.util.DBUtils;
11 
12 /**
13  * @author DSHORE/2020-1-15
14  *  接口的实现类
15  */
16 public class UserDao implements IUserDao {
17     //全局变量
18     Connection connection = null;
19     Statement statement = null;
20     PreparedStatement preparedStatement = null;
21     ResultSet resultSet = null;
22 
23     @Override //新增
24     public int add(User user) {
25         int result = 0;
26         String sql = "";
27         try {
28             connection = DBUtils.getConnection();
29             //MySQL数据库
30             sql = "insert into user(account,password) values(\'"+user.getAccount()+"\',\'"+user.getPassword()+"\')";
31             statement = connection.createStatement();
32             result = statement.executeUpdate(sql);//执行添加操作
33         } catch (Exception e) {
34             e.printStackTrace();
35         } finally{
36             DBUtils.free(null, statement, connection);
37         }
38         return result;
39     }
40 
41     @Override //根据id查询
42     public User findById(Integer id) {
43         User user = null;    
44         String sql = "";
45         try {
46             connection = DBUtils.getConnection();//连接数据库
47             //MySQL
48             sql = "select * from user where id = ?";
49             preparedStatement = connection.prepareStatement(sql);//编译/检查sql语句是否符合规范等等
50             preparedStatement.setInt(1, id);
51             resultSet = preparedStatement.executeQuery();//执行查询操作
52             if(resultSet.first()){
53                 user = new User();
54                 user.setId(id);
55                 user.setAccount(resultSet.getString("account"));
56                 user.setPassword(resultSet.getString("password"));
57             }
58         } catch (Exception e) {
59             e.fillInStackTrace();
60         } finally {
61             DBUtils.free(resultSet, preparedStatement, connection);
62         }
63         return user;
64     }
65 }

UserTest 测试类

 1 package com.shore.test;
 2 
 3 import org.junit.Test;
 4 
 5 import com.shore.dao.IUserDao;
 6 import com.shore.dao.impl.UserDao;
 7 import com.shore.entity.User;
 8 
 9 /**
10  * @author DSHORE/2020-1-15
11  *
12  */
13 public class UserTest {
14     @Test
15     public void addTest() {
16         IUserDao userDao = new UserDao();
17         User user = new User();
18         user.setAccount("lisi");
19         user.setPassword("123456");
20         userDao.add(user); //添加成功
21     }
22     
23     @Test
24     public void findByIdTest() {
25         IUserDao userDao = new UserDao();
26         User user = userDao.findById(2);
27         System.out.println(user); //返回值: com.shore.entity.User@1c5d9084   
28         System.out.println(user.getAccount()+" : "+user.getPassword()); //返回值: 张三 : 123456  
29     }
30 }

 

2、JDBC连接Oracle数据库  

2.1、我用到的jar包

2.2、实例演示

Oracle 建表语句

 1 -- Oracle建表语句
 2 create table users( -- user是Oracle关键字,不能用user
 3   id number(5) primary key,
 4   account varchar2(20) not null unique,
 5   password varchar2(32) not null
 6 );
 7 
 8 -- 创建序列
 9 create sequence users_seq  -- 序列名称:users_seq
10 minvalue 1  --最小值
11 start with 1   --从1开始计数,数值可变
12 increment by 1  --每次加1,数值可变
13 nocycle  --一直累加,不循环;cycle:达到最大值后,将从头开始累加。 (maxvalue 999 -- 最大值)
14 nocache;  --不建缓冲区。

这里我没有创建触发器,dao层插入数据时,id这项 必须要写上,比如:看红色代码处

insert into users(id,account,password) values(users_seq.nextval,\'张三\',\'123456\');

创建触发器(主要看Oracle部分,第3小点是创建触发器的步骤,第4小点体现了触发器的作用)详情https://www.cnblogs.com/dshore123/p/8267240.html

odb.properties 配置文件

1 jdbcDriver=oracle.jdbc.driver.OracleDriver
2 url=jdbc:oracle:thin:@localhost:1521:shoreid
3 userName=zhangsan
4 password=123456

注意:数据库名是shore,该数据库的SID是shoreid。

  其中,命令行窗口和Oracle的PLSQL Developer默认是以全局数据库名的形式来登录,即:sqlplus zhangsan/123456@shore
  而Java代码连接时,是以该全局数据库的SID的形式来登录,即:url=jdbc:oracle:thin:@localhost:1521:shoreid

这要看你在创建数据库时的设置,全局数据库名和SID可以设置一样。

DBUtils 工具类(封装jdbc公共部分的代码)

  1 package com.shore.util;
  2 
  3 import java.io.IOException;
  4 import java.io.InputStream;
  5 import java.sql.Connection;
  6 import java.sql.DriverManager;
  7 import java.sql.PreparedStatement;
  8 import java.sql.ResultSet;
  9 import java.sql.SQLException;
 10 import java.sql.Statement;
 11 import java.util.Properties;
 12 
 13 /**
 14  * @author DSHORE/2020-1-15
 15  * 连接数据库--->工具类
 16  */
 17 public class DBUtils {
 18     
 19     private DBUtils() {
 20     }
 21 
 22     private static String jdbcDriver = "";
 23     private static String url = "";
 24     private static String userName = "";
 25     private static String password = "";
 26 
 27     static {
 28         Properties properties = new Properties();
 29         try {
 30             //读取配置文件(Oracle数据库)
 31             InputStream inputStream = DBUtils.class.getResourceAsStream("/odb.properties");
 32             properties.load(inputStream); //加载配置文件
 33             inputStream.close();//关闭输入流
 34             
 35             //获取到对应参数的值
 36             jdbcDriver = properties.getProperty("jdbcDriver");
 37             url = properties.getProperty("url");
 38             userName = properties.getProperty("userName");
 39             password = properties.getProperty("password");
 40         } catch (IOException e1) {
 41             e1.printStackTrace();
 42         } finally {
 43             try {
 44                 Class.forName(jdbcDriver);
 45             } catch (ClassNotFoundException e) {
 46                 throw new ExceptionInInitializerError(e);
 47             }
 48         }
 49     }
 50 
 51     //连接数据库
 52     public static Connection getConnection() throws SQLException {
 53         Connection connection = null;
 54         try {
 55             connection = DriverManager.getConnection(url, userName, password);
 56         } catch (Exception e) {
 57             System.out.println(e.getMessage());//如果出现异常,则 把异常信息打印到控台上
 58         }
 59         return connection;
 60     }
 61 
 62     // 释放资源。   顺序:resultSet、statement、connection
 63     public static void free(ResultSet resultSet, Statement statement, Connection connection) {
 64         if (resultSet != null) {
 65             try {
 66                 resultSet.close();
 67             } catch (SQLException e) {
 68                 e.printStackTrace();
 69             } finally {
 70                 if (statement != null) {
 71                     try {
 72                         statement.close();
 73                     } catch (SQLException e) {
 74                         e.printStackTrace();
 75                     } finally {
 76                         if (connection != null) {
 77                             try {
 78                                 connection.close();
 79                             } catch (SQLException e) {
 80                                 e.printStackTrace();
 81                             }
 82                         }
 83                     }
 84                 }
 85             }
 86         }
 87     }
 88 
 89     // 释放资源。  顺序:resultSet、preparedStatement、connection
 90     public static void free(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) {
 91         if (resultSet != null) {
 92             try {
 93                 resultSet.close();
 94             } catch (SQLException e) {
 95                 e.printStackTrace();
 96             } finally {
 97                 if (preparedStatement != null) {
 98                     try {
 99                         preparedStatement.close();
100                     } catch完整java开发中JDBC连接数据库代码和步骤

Java JDBC连接MySQL数据库,基础语法及自定义JDBC的MySQL工具类

Java应用程序连接数据库--JDBC基础

ava基础MySQL存储过程 Java基础 JDBC连接MySQL数据库

java 通过jdbc连接MySQL数据库

Mysql--JDBC的基础