Java中操作資料庫語句JDBC基礎
阿新 • • 發佈:2018-12-25
JDBC
JDBC Java Database connectivity
Java資料庫連線規範(一套介面) 由SUn公司提供的
JDBC四個核心類
DriverManager 建立連線
Connection 連線類
Statement 執行sql語句
ResultSet 結果集
JDBC連線步驟:
1.註冊驅動
2.獲取連線 Connection
3.獲取sql 語句的執行物件 Statement
4.執行sql 語句 返回結果集
5.處理結果集
6.關閉資源
JDBC 連線
// 註冊驅動
// 這種註冊方式 相當於註冊了兩遍
// Driver 類 內部的靜態程式碼塊 已經註冊了一遍
//DriverManager.registerDriver(new Driver());
// 直接把該類載入到記憶體當中 引數是 全限定類名
// 包名+類名
Class.forName("com.mysql.jdbc.Driver");
// 獲取連線物件
// url 是訪問資料庫 連結地址
// 3306是資料庫的埠號
// myjdbc是庫名
String url = "jdbc:mysql://localhost:3306/myjdbc";
// 連線方式一
// root是資料庫賬號
// 123456是資料庫密碼
// Connection connection = DriverManager.getConnection(url, "root", "123456");
/*
//獲取連線的方式2
Properties info = new Properties();
// 新增使用者名稱 密碼
// 注意鍵值別拼錯了
info.setProperty("user", "root");
info.setProperty("password", "123456");
Connection connection = DriverManager.getConnection(url, info);
*/
// 獲取連線方式3 相當於使用了一個get請求
// 攜帶引數 訪問連結
String url2 = "jdbc:mysql://localhost:3306/myjdbc?user=root&password=123456";
Connection connection = DriverManager.getConnection(url2);
// 獲取執行sql語句的物件 Statement
Statement statement = connection.createStatement();
// 執行sql語句 返回結果集
// users 是表名
String sql = "select * from users";
ResultSet resultSet = statement.executeQuery(sql);
// 處理結果集
// 迴圈遍歷結果集 輸出結果
// 有記錄 next()方法 返回true 反之 返回 false
// next方法是檢視資料庫下一條記錄有沒有值
// 有就返回true 沒有就返回false
while (resultSet.next()) {
// 列印資料
// 結果集中新增的 索引 要和 查詢語句中的 欄位對應
// 注意:查詢資料庫時 索引從1開始
// 這裡的12345 是資料庫列的索引
// 1 程式碼 id
System.out.println(resultSet.getObject(1));
System.out.println(resultSet.getObject(2));
System.out.println(resultSet.getObject(3));
System.out.println(resultSet.getObject(4));
System.out.println(resultSet.getObject(5));
System.out.println("--------------------");
}
// 關閉資源
resultSet.close();
statement.close();
connection.close();
}
測試增刪改查
// 註解 用來測試方法
// 注意: 要使用public修飾 無返回值方法
// 插入方法
@Test
public void testInsert() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/myjdbc";
Connection connection = DriverManager.getConnection(url, "root", "123456");
Statement statement = connection.createStatement();
String sql = "insert into users values(5,'f','123456','[email protected]','1997-06-01')";
int row = statement.executeUpdate(sql);
if (row > 0) {
System.out.println("插入成功");
}
statement.close();
connection.close();
}
// 修改方法
@Test
public void testUpdate() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/myjdbc";
Connection connection = DriverManager.getConnection(url, "root", "123456");
Statement statement = connection.createStatement();
String sql = "update users set name = 'g' where name='f'";
// 受影響的行數
int update = statement.executeUpdate(sql);
if (update > 0) {
System.out.println("更新成功" + update + "行");
}
statement.close();
connection.close();
}
// 刪除方法
@Test
public void testDelete() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/myjdbc";
Connection connection = DriverManager.getConnection(url, "root", "123456");
Statement statement = connection.createStatement();
String sql = "delete from users where id=5 ";
int row = statement.executeUpdate(sql);
if (row > 0) {
System.out.println("刪除成功");
}
statement.close();
connection.close();
}
// 查詢方法
//@Test寫入時需要選擇匯入 import org.junit.Test;
@Test
public void testSelect() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/myjdbc";
Connection connection = DriverManager.getConnection(url, "root", "123456");
Statement statement = connection.createStatement();
// 查詢
String sql = "select id,name,email from users";
ResultSet resultSet = statement.executeQuery(sql);
// 處理結果集
while (resultSet.next()) {
// 可以直接填欄位名稱
System.out.println(resultSet.getObject("id"));
System.out.println(resultSet.getObject("name"));
System.out.println(resultSet.getObject("email"));
}
resultSet.close();
statement.close();
connection.close();
}
連線資料庫的異常處理
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/myjdbc";
connection = DriverManager.getConnection(url, "root", "123456");
statement = connection.createStatement();
String sql = "select * from users";
resultSet = statement.executeQuery(sql);
// 處理結果集(把資料庫的記錄封裝到物件中)
// 把物件儲存到陣列當中並遍歷列印
// 建立集合
ArrayList<User> arrayList = new ArrayList<>();
while (resultSet.next()) {
// 建立User物件
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setPassword(resultSet.getString("password"));
user.setEMail(resultSet.getString("email"));
user.setBirthday(resultSet.getDate("birthday"));
// 放入集合當中
arrayList.add(user);
}
// 遍歷檢視
for (User user : arrayList) {
System.out.println(user);
}
} catch (ClassNotFoundException e) {
// 停止程式
throw new RuntimeException("驅動載入失敗");
} catch (SQLException e) {
throw new RuntimeException("獲取連線失敗");
} finally {
// 關閉資源前 要做非空判斷 防止空指標出現
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
throw new RuntimeException("關閉失敗");
}
// 加快系統回收的速度
resultSet = null;
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
throw new RuntimeException("關閉失敗");
}
// 加快系統回收的速度
statement = null;
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
throw new RuntimeException("關閉失敗");
}
// 加快系統回收的速度
connection = null;
}
}
JDBC工具類
//在src目錄下建立一個檔案
//檔名為 dbinfo.properties
//將以下程式碼寫入檔案中
//這個檔案成為配置檔案
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/myjdbc
user=root
password=123456
private static String driverClass;
private static String url;
private static String user;
private static String password;
// 使用靜態程式碼塊載入驅動 讀取配置檔案
static {
// 使用系統類來讀取配置檔案
ResourceBundle rb = ResourceBundle.getBundle("dbinfo");
// 獲取檔案中的資料
driverClass = rb.getString("driverClass");
url = rb.getString("url");
user = rb.getString("user");
password = rb.getString("password");
// 利用集合讀取檔案
// Properties properties = new Properties();
// try {
// FileInputStream fis = new FileInputStream("src/dbinfo.properties");
// properties.load(fis);
// // 讀檔案
// driverClass = properties.getProperty("driverClass");
// url = properties.getProperty("url");
// user = properties.getProperty("user");
// password = properties.getProperty("password");
// } catch (IOException e) {
//
// }
// 讓驅動類只加載一次
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 獲取資料庫的連線方法
public static Connection getConnection() throws SQLException, ClassNotFoundException {
return DriverManager.getConnection(url, user, password);
}
// 關閉資料庫的方法 如果沒有結果集需要關閉 直接傳空就好了
public static void closeALL(ResultSet resultSet, Statement statement, Connection connection) {
// 關閉資源前 要做非空判斷 防止空指標出現
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
throw new RuntimeException("關閉失敗");
}
// 加快系統回收的速度
resultSet = null;
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
throw new RuntimeException("關閉失敗");
}
// 加快系統回收的速度
statement = null;
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
throw new RuntimeException("關閉失敗");
}
// 加快系統回收的速度
connection = null;
}
}
// 建立測試類 測試 JDBC工具類
@Test
public void testSelect() {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
// 獲取連線
try {
connection = JDBCUtil.getConnection();
statement = connection.createStatement();
String sql = "select * from users";
resultSet = statement.executeQuery(sql);
// 建立集合
ArrayList<User> arrayList = new ArrayList<>();
while (resultSet.next()) {
// 建立User物件
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setPassword(resultSet.getString("password"));
user.setEMail(resultSet.getString("email"));
user.setBirthday(resultSet.getDate("birthday"));
// 放入集合當中
arrayList.add(user);
}
// 遍歷檢視
for (User user : arrayList) {
System.out.println(user);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
// 關閉資源
JDBCUtil.closeALL(resultSet, statement, connection);
}
}