Reference: https://www.bilibili.com/video/BV1Bt41137iB?p=1
1. 什么是JDBC
1.1 JDBC概念
JDBC:Java DataBase Connectivity,java用于连接数据库的接口(Interface)。
为什么要面向接口编程
- 解耦合,提高程序的扩展力;
- 多态机制就是非常典型的面向抽象编程。
如下图所示,SUN公司发布了一套JDBC接口,随后各数据库厂商实现JDBC的接口,而java程序员只用通过JDBC编程即可。
1.2 JDBC本质
- JDBC接口
// JDBC.java
public interface JDBC{
public void getConnection();
}
- 各厂家的实现(驱动)
// MySQL.java
public class MySQL implements JDBC{
public void getConnection(){
System.out.println("连接Mysql数据库成功!");
}
}
// Oracle.java
public class Oracle implements JDBC{
public void getConnection(){
System.out.println("连接Oracle数据库成功!");
}
}
// SqlServer.java
public class SqlServer implements JDBC{
public void getConnection(){
System.out.println("连接SqlServer数据库成功!");
}
}
- java程序员编写程序
// JavaProgrammer.java
public class JavaProgrammer{
public static void main(String[] args){
JDBC jdbc = new MySQL();
jdbc.getConnection();
}
}
上述代码更改驱动需要更改java代码,一般将数据库信息放在配置文件中,因此需要使用反射机制。
// JavaProgrammer.java
import java.util.*;
public class JavaProgrammer{
public static void main(String[] args) throws Exception{
// 读取jdbc.properities文件
ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
String className = bundle.getString("className");
// 通过反射机制创建对象
Class c = Class.forName(className);
JDBC jdbc = (JDBC) c.newInstance();
jdbc.getConnection();
}
}
// jdbc.properties
className=SqlServer
2. JDBC编程步骤
若是使用文本开发代码,使用javac命令编译:需要将mysql-connector-java-8.0.22.jar
配置到classpath中
2.1 注册驱动
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
Class.forName("com.mysql.cj.jdbc.Driver");
**遇到问题:**无法找到com.mysql.cj.jdbc`包,即使添加了环境变量, 只能将包放在:
/usr/java/jdk1.7.0_75/jre/lib/ext`
2.2 获取连接
conn = DriverManager.getConnection("jdbc:mysql://139.196.28.120:3300/smbms", "root", "yang");
2.3 获取数据库操作对象
stmt = conn.createStatement();
2.4 执行SQL语句
sql = "select * from smbms_address";
rs = stmt.execute(sql);
2.5 处理查询结果集
while(rs.next()){
for(int i = 0; rs.getMetaData.getColumnCount(); i++){
System.out.print(rs.getObject(i+1));
System.out.print('\t');
}
System.out.println();
}
2.6 释放资源
try{
// 上面的5步操作
} catch(SQLException e){
e.printStackTrace();
} catch(ClassNotFoundException e){
e.printStackTrace();
} finally{
if (rs != null){
try{
rs.close():
}catch(SQLException e){
e.printStackTrace();
}
}
if (stmt != null){
try{
stmt.close():
}catch(SQLException e){
e.printStackTrace();
}
}
if (conn != null){
try{
conn.close():
}catch(SQLException e){
e.printStackTrace();
}
}
}
2.7 综合代码
package com.yang;
import java.sql.*;
import java.util.ResourceBundle;
public class JDBCTest {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
String driver = bundle.getString("driver");
String url = bundle.getString("url");
String usr = bundle.getString("usr");
String pwd = bundle.getString("pwd");
// 1. 注册驱动
Class.forName(driver);
// 2. 获取连接
conn = DriverManager.getConnection(url, usr, pwd);
// 3. 获取数据库操作对象
stmt = conn.createStatement();
// 4. 执行sql语句
String sql = "select * from smbms_bill";
rs = stmt.executeQuery(sql);
// 5. 查询结果集处理
while (rs.next()) {
for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
System.out.print(rs.getObject(i + 1));
System.out.print("\t");
}
System.out.println();
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
// 6. 释放资源
try {
if (rs != null){
rs.close();
}
}catch (SQLException e){
e.printStackTrace();
}
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (stmt != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://139.196.28.120:3300/smbms
usr=root
pwd=yang
2.8 代码改进
-
使用反射注册类
Class.forName("com.mysql.cj.jdbc.Driver");
-
使用资源绑定器读取配置文件,注意使用maven创建的项目需要将配置文件放在resources文件夹下,ResourceBundle.getBundle也是从resources文件夹为根路径读取的
ResourceBundle bundle = ResourceBundle.getBundle("jdbc"); String dirver = bundle.getString("driver"); String url = bundle.getString("url"); String usr = bundle.getString("usr"); String pwd = bundle.getString("pwd");
-
防止SQL注入,使用conn.prepareStatement()先预编译SQL语句
// 3. 创建数据库操作对象 String sql = "select * from smbms_user where userName = ? and userPassword = ?"; ps = conn.prepareStatement(sql); ps.setString(1, "孙磊"); ps.setString(2, "0000000"); // 4. 执行数据库SQl语句 rs = ps.executeQuery();
-
工具类DBUtils
package com.yang.jdbc; import java.sql.*; public class DBUtils { /** * 私有构造器,防止工具类创建对象 */ private DBUtils() {} /** * 静态方法区,创建类时自动自动执行,并且仅仅执行一次 */ static { try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * 创建连接 * @param url * @param username * @param password * @return 返回建立的连接 * @throws SQLException */ public static Connection getConnection(String url, String username, String password) throws SQLException { return DriverManager.getConnection(url, username, password); } /** * 关闭连接 * @param rs * @param ps * @param conn */ public static void close(ResultSet rs, Statement ps, Connection conn){ if (rs != null){ try { rs.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (ps != null){ try { ps.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (conn != null){ try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } }
3. 示例:用户登录验证
package com.yang.loginSys;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class loginSys {
public static void main(String[] args) {
// 1. 用户登录界面
Map<String, String> loginInfo = loginUI();
// 2. 用户信息验证
boolean isPass = validateInfo(loginInfo);
System.out.println(isPass ? "登录成功": "登录失败");
}
// 用户信息验证
private static boolean validateInfo(Map<String, String> loginInfo) {
boolean loginSuccess = false;
String username = loginInfo.get("username");
String password = loginInfo.get("password");
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://139.196.28.120:3300/smbms", "root", "yang");
String sql = "select * from smbms_user where userName = ? and userPassword = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
rs = ps.executeQuery();
loginSuccess = rs.next();
} catch (Exception e){
e.printStackTrace();
} finally {
if (rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (ps != null){
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
return loginSuccess;
}
// 用户登录界面
private static Map<String,String> loginUI() {
Scanner in = new Scanner(System.in);
System.out.print("请输入用户名:");
String username = in.nextLine();
System.out.print("请输入密码:");
String password = in.nextLine();
Map<String, String> loginInfo = new HashMap<String, String>();
loginInfo.put("username", username.trim());
loginInfo.put("password", password.trim());
return loginInfo;
}
}