JDBC概念: 使用JAVA代碼操作數(shù)據(jù)庫
-----------------------------
DEMO:
package com.company.jdbc;
import java.sql.*;
public class Main {
// 數(shù)據(jù)庫地址
? ? static Stringurl ="jdbc:mysql://localhost:3306/mysql";
? ? static Stringusername ="root";
? ? static Stringpassword ="12345678";
? ? public static void main(String[] args)? {
// 1.加載驅(qū)動(開發(fā)推薦的方式)
? ? ? ? System.out.println("Hello,Java~~~");
? ? ? ? Connection connection =null;
? ? ? ? ResultSet resultSet =null;
? ? ? ? PreparedStatement preparedStatement =null;
? ? ? ? try {
// 2.獲取Connection對象 Collection是數(shù)據(jù)庫編程中最重要的一個對象,客戶端與數(shù)據(jù)庫所有交互都是通過connection對象完成的
? ? ? ? ? ? connection = DriverManager.getConnection(url,username,password);
? ? ? ? ? ? // SQL語句
? ? ? ? ? ? String sql ="select * from student where name = '張三'";
? ? ? ? ? ? // 數(shù)據(jù)庫查詢方法,執(zhí)行SQL語句
? ? ? ? ? ? preparedStatement = connection.prepareStatement(sql);
? ? ? ? ? ? // 將查詢到的結(jié)果賦值到ResultSet對象
? ? ? ? ? ? resultSet = preparedStatement.executeQuery(sql);
? ? ? ? ? ? // 遍歷結(jié)果
? ? ? ? ? ? while (resultSet.next()) {
String name = resultSet.getString("name");
? ? ? ? ? ? ? ? System.out.println("name:" + name);
? ? ? ? ? ? }
}catch (SQLException throwables) {
throwables.printStackTrace();
? ? ? ? }finally {
// 釋放資源
? ? ? ? ? ? if (resultSet !=null) {
try {
resultSet.close();
? ? ? ? ? ? ? ? }catch (SQLException throwables) {
throwables.printStackTrace();
? ? ? ? ? ? ? ? }
}
if (preparedStatement !=null) {
try {
preparedStatement.close();
? ? ? ? ? ? ? ? }catch (SQLException throwables) {
throwables.printStackTrace();
? ? ? ? ? ? ? ? }
}
}
}
}