JDBC概念
-
JDBC是什么?
- Java DataBase Connectivity(Java语言连接数据库)
- JAVA与数据库交互的接口
-
JDBC的本质是什么?
- JDBC是SUN公司制定的一套接口(interface)
- java.sql.*;(这个软件包下有很多接口)
-
接口都有调用者和实现者,面向接口调用、面向接口写实现类,这都属于面向接口编程。
JDBC实现
【前提】
-
JDBC驱动名:一般用String保存:“com.mysql.cj.jdbc.Driver”(MySQL 8.0 以上版本)
-
数据库URL:一般用String保存:“jdbc:mysql://域名:端口号/库名?useSSL=false&serverTimezone=UTC”
-
数据库用户名和密码:一般用两个String保存
//【前提】 String JDBC_Driver = "com.mysql.cj.jdbc.Driver"; String DB_URL = "jdbc:mysql://localhost:3306/ocs?useSSL=false&serverTimezone=UTC"; String USER = "root"; String PassWord = "admin";
【连接数据库】
-
注册驱动:Class.forName(驱动);
-
打开连接:Connection con = DriverManager.getConnection(数据库URL,用户名,密码);
//【建立连接】 Class.forName(JDBC_Driver);//1.注册驱动 System.out.println("连接数据库..."); Connection con = DriverManager.getConnection(DB_URL,USER,PassWord);//2.打开连接 if(!con.isClosed()) { System.out.println("连接数据库成功"); } else { System.out.println("连接数据库失败"); }
【发送指令】
-
创建statement:Statement
-
输入SQL语句:一般用String保存
-
创建返回内容:ResultSet
// 【发送指令】 Statement stmt = con.createStatement();//1.创建会话 String sql = "SELECT * FROM comos_cps";// 2.输入sql语句 ResultSet result = stmt.executeQuery(sql);// 3.创建返回内容
【处理返回数据】
//光标向后or向前偏移
//因为ResultSet是一个结果集,要想读出来,必须要next方法才行
result.next();
result.previous();
// 【以字符串形式,输出指定列(Addr列)】
while (result.next()) {
System.out.print(result.getString("Addr") + " ");
}
//【以数值形式,输出指定列(Distance列)】(getInt/getFloat/getDouble等,低级可以自动向高级转化)
while(result.next()) {
System.out.print(result.getDouble("Distance") + " ");
}
//以上方法都可以用列的序号作为参数(从1开始,不是从0开始!)
JDBC完整实例
public static void main(String[] args) {
// 【前提】
String JDBC_Driver = "com.mysql.cj.jdbc.Driver";
String DB_URL = "jdbc:mysql://localhost:3306/ocs?useSSL=false&serverTimezone=UTC";
String USER = "root";
String PassWord = "admin";
//此处把三个对象单独拿出来创建了
Connection con = null;
Statement stmt = null;
ResultSet result = null;
// 必须有try
try {
// 【建立连接】
Class.forName(JDBC_Driver);// 1.注册驱动
System.out.println("连接数据库...");
con = DriverManager.getConnection(DB_URL, USER, PassWord);// 2.打开连接
if (!con.isClosed()) {
System.out.println("连接数据库成功");
} else {
System.out.println("连接数据库失败");
}
// 【发送指令】
stmt = con.createStatement();// 1.创建会话
String sql = "SELECT * FROM comos_cps";// 2.输入sql语句
result = stmt.executeQuery(sql);// 3.创建返回值
// 【处理返回数据】
while (result.next()) {
System.out.println(result.getString("Addr"));
}
} catch (SQLException se) {
// 处理 JDBC 错误
se.printStackTrace();
} catch (Exception e) {
// 处理 Class.forName 错误
e.printStackTrace();
} finally {
// 关闭资源
try {
if (stmt != null)
stmt.close();
} catch (SQLException se2) {
} // 什么都不做
try {
if (con != null)
con.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}