JDBC
JDBC(Java Database connectivity)是一種執行SQL語句的Java API
可以爲多種關係數據庫提供統一訪問
Java數據庫連接規範(即一套接口)
JDBC四個核心類:
DriverManager 創建連接
Connection 連接類
Statement 用來執行sql語句
ResultSet 結果集
JDBC連接步驟:
1.註冊驅動
2.獲取連接 Connection
3.獲取sql語句的執行對象 Statement
4.執行sql語句 返回結果集 ResultSet
5.處理結果集
6.關閉資源
JDBC的連接
// 1.註冊驅動
/* 這種註冊方式 相當於註冊了兩遍
Driver類內部的靜態代碼塊已經註冊了一遍
DriverManager.registerDriver(new Driver());
*/
// 直接把該類加載到內存當中 參數是全限定類名 (包名+類名)
Class.forName("com.mysql.jdbc.Driver");
// 2.獲取連接對象
// url是訪問數據庫連接地址
String url = "jdbc:mysql://localhost:3306/myjdbc";
// 獲取連接的方式一
Connection connection = DriverManager.getConnection(url, "root", "123456");
// 獲取連接的方式二
Properties info = new Properties();
// 添加用戶名 密碼
info.setProperty("user", "root");
info.setProperty("password", "123456");
Connection connection = DriverManager.getConnection(url, info);
// 獲取連接的方式三 相當於使用了一個get請求
// 攜帶參數 訪問連接
String url2 = "jdbc:mysql://localhost:3306/myjdbc?user=root&password=123456";
Connection connection = DriverManager.getConnection(url2);
// 3.獲取執行sql語句的對象 Statement
Statement statement = connection.createStatement();
// 4.執行sql語句 返回結果集
String sql = "select * from users";
ResultSet resultSet = statement.executeQuery(sql);
// 5.處理結果集
// 循環遍歷結果集輸出結果
// 有記錄next()方法返回true 反之false
while (resultSet.next()) {
// 打印數據
// 注意:查詢數據庫時 索引從1開始
// 結果集中添加的索引要和查詢語句中的字段對應
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));
}
// 6.關閉資源
resultSet.close();
statement.close();
connection.close();
JDBC增刪改查
@Test註解用來測試方法
注意:要使用public修飾的、無返回值的方法
// 插入方法
@Test
public void testInsert() throws ClassNotFoundException, SQLException {
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,'ab','123','[email protected]','1997-06-23')";
// executeUpdate 增刪改
// row 表示受影響的行數
int row = statement.executeUpdate(sql);
if (row>0) {
System.out.println("成功插入"+ row +"行");
}
connection.close();
statement.close();
}
// 更新方法
@Test
public void testUpdate() throws ClassNotFoundException, SQLException {
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='ac' where name='ab'";
int row = statement.executeUpdate(sql);
if (row>0) {
System.out.println("成功更新"+ row +"行");
}
connection.close();
statement.close();
}
// 刪除方法
@Test
public void testDelete() throws ClassNotFoundException, SQLException {
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("成功刪除"+ row +"行");
}
connection.close();
statement.close();
}
// 查詢方法
@Test
public void testSelect() throws ClassNotFoundException, SQLException {
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();
connection.close();
statement.close();
}
JDBC連接數據庫的異常處理
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myjdbc", "root", "123456");
statement = connection.createStatement();
String sql = "select * from users";
resultSet = statement.executeQuery(sql);
// 處理結果集(把數據庫的記錄封裝到對象中)
// 把對象保存到集合當中
ArrayList<User> list = 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"));
// 放入集合中
list.add(user);
}
// 遍歷打印
for (User user : list) {
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工具類
JDBCUtil工具類
public class JDBCUtil {
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");
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
/*
// 利用集合 讀取文件
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 (Exception e) {
}
*/
}
// 獲取數據庫連接的方法
public static Connection getConnection() throws ClassNotFoundException, SQLException {
return DriverManager.getConnection(url, user, password);
}
// 關閉數據庫的方法 如果沒有結果集需要關閉 直接傳null
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;
}
}
}
TestJDBCUtil測試類
public class TestJDBCUtil {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
@Test
public void testSelect() {
try {
// 獲取連接
connection = JDBCUtil.getConnection();
statement = connection.createStatement();
String sql = "select * from users";
resultSet = statement.executeQuery(sql);
ArrayList<User> list = new ArrayList<>();
while (resultSet.next()) {
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"));
list.add(user);
}
for (User user : list) {
System.out.println(user);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 關閉資源
JDBCUtil.closeAll(resultSet, statement, connection);
}
}
}
JDBC實現用戶登錄
用戶登錄
public class Login {
public static void main(String[] args) {
// 接收用戶輸入的賬號和密碼
System.out.println("請輸入賬號:");
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
System.out.println("請輸入密碼:");
String password = scanner.nextLine();
// 調用查詢方法
DoLogin dl = new DoLogin();
User user = dl.findUser(name, password);
if (user != null) {
System.out.println(user.getName()+"登錄成功");
} else {
System.out.println("登錄失敗");
}
}
}
處理登錄的查詢操作
public class DoLogin {
public User findUser(String name,String password) {
User user = null;
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
String sql = "select * from users where name='"+name+"' and password='"+password+"'";
// 查詢數據庫
try {
connection = JDBCUtil.getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(sql);
if (resultSet.next()) {
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"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtil.closeAll(resultSet, statement, connection);
}
return user;
}
}
sql語句注入問題(添加了一個恆成立的條件)
解決方法
public class DoLogin {
public User findUser(String name,String password) {
User user = null;
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
// 佔位符
String sql = "select * from users where name=? and password=?";
// 查詢數據庫
try {
connection = JDBCUtil.getConnection();
// 對sql語句進行預編譯
statement = connection.prepareStatement(sql);
// 給sql語句的佔位符 進行賦值
// 參數1 填索引 sql語句中問號索引
statement.setString(1, name);
statement.setString(2, password);
resultSet = statement.executeQuery();
if (resultSet.next()) {
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"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtil.closeAll(resultSet, statement, connection);
}
return user;
}