1.認(rèn)識JDBC
JDBC: Java Database Connect Java連接數(shù)據(jù)庫
需要jar包支持:
- java.sql
- javax.sql
- mysql-connector-java
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
https://repo1.maven.org/maven2/mysql/mysql-connector-java/8.0.26/mysql-connector-java-8.0.26.jar
2. 準(zhǔn)備測試數(shù)據(jù)庫
2.1 創(chuàng)建數(shù)據(jù)庫
CREATE DATABASE jdbc;
2.2 創(chuàng)建數(shù)據(jù)表
CREATE TABLE IF NOT EXISTS `user`(
`id` INT UNSIGNED AUTO_INCREMENT,
`username` VARCHAR(100) NOT NULL,
`password` VARCHAR(40) NOT NULL,
PRIMARY KEY ( `id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
2.3 插入數(shù)據(jù)
INSERT INTO user(username,password )
VALUES( "張三", "123456"),
( "李四", "123456"),
( "張三瘋", "123456");
3. 編寫JDBC
- JDBC_statement_CRUD
package com.zzqsmile;
import java.sql.*;
public class JDBC_statement_CRUD {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1. 加載驅(qū)動
Class.forName("com.mysql.cj.jdbc.Driver");
//2. 配置信息
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=false";
String username="root";
String password="root";
//3. 連接數(shù)據(jù)庫,Connection代表數(shù)據(jù)庫
Connection connection = DriverManager.getConnection(url, username, password);
//4. 向數(shù)據(jù)庫發(fā)送sql的對象Statement&&PreparedStatement,用來CRUD
Statement statement = connection.createStatement();
//編寫查詢sql --查
String sql="select * from user;";
//執(zhí)行
ResultSet resultSet = statement.executeQuery(sql);
//打印信息
while (resultSet.next()){
System.out.println("id="+resultSet.getObject("id"));
System.out.println("username="+resultSet.getObject("username"));
System.out.println("password="+resultSet.getObject("password"));
System.out.println("=======================");
System.out.println();
}
//編寫插入sql --增
String sql1="insert into user(username,password) values('劉五','111111')";
//執(zhí)行
int i = statement.executeUpdate(sql1);
if (i>0){
System.out.println("插入成功泰鸡!");
System.out.println();
}
//編寫修改sql --改
String sql2="update user set `password`='123123' where `username`='劉五'";
//執(zhí)行
int i1 = statement.executeUpdate(sql2);
if (i1>0){
System.out.println("修改成功谤辜!");
System.out.println();
}
//編寫刪除sql --刪
String sql3="delete from user where id = 1";
//執(zhí)行
int i2 = statement.executeUpdate(sql3);
if (i2>0){
System.out.println("刪除成功!");
System.out.println();
}
//5. 關(guān)閉連接
resultSet.close();
statement.close();
connection.close();
}
}
- JDBC_PreparedStatement_CRUD
預(yù)編譯CURD
package com.zzqsmile;
import java.sql.*;
public class JDBC_PreparedStatement_CRUD {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1. 加載驅(qū)動
Class.forName("com.mysql.cj.jdbc.Driver");
//2. 配置信息
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=false";
String username="root";
String password="root";
//3. 連接數(shù)據(jù)庫,Connection代表數(shù)據(jù)庫
Connection connection = DriverManager.getConnection(url, username, password);
//4. 編寫參數(shù)化SQL(帶?的SQL語句)
//編寫查詢sql --查
String sql="select * from user where username = ?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//賦值
preparedStatement.setString(1,"李四");
//執(zhí)行
ResultSet resultSet = preparedStatement.executeQuery();
//打印信息
while (resultSet.next()){
System.out.println("===========查詢結(jié)果============");
System.out.println("id="+resultSet.getObject("id"));
System.out.println("username="+resultSet.getObject("username"));
System.out.println("password="+resultSet.getObject("password"));
System.out.println();
}
//編寫插入sql --增
String sql1="insert into user(username,password) values(?,?)";
PreparedStatement preparedStatement1 = connection.prepareStatement(sql1);
//賦值
preparedStatement1.setString(1,"李四2");
preparedStatement1.setString(2,"123321");
//執(zhí)行
int i1 = preparedStatement1.executeUpdate();
if (i1>0){
System.out.println("插入成功哮奇!");
System.out.println();
}
//編寫修改sql --改
String sql2="update user set `password`=? where `username`='劉五'";
PreparedStatement preparedStatement2 = connection.prepareStatement(sql2);
//賦值
preparedStatement2.setString(1,"222222");
//執(zhí)行
int i2 = preparedStatement2.executeUpdate();
if (i2>0){
System.out.println("修改成功饭耳!");
System.out.println();
}
//編寫刪除sql --刪
String sql3="delete from user where id = ?";
PreparedStatement preparedStatement3 = connection.prepareStatement(sql3);
//賦值
preparedStatement3.setString(1,"2");
//執(zhí)行
int i3 = preparedStatement3.executeUpdate();
if (i3>0){
System.out.println("刪除成功串述!");
System.out.println();
}
//5. 關(guān)閉連接
resultSet.close();
preparedStatement.close();
preparedStatement1.close();
preparedStatement2.close();
preparedStatement3.close();
connection.close();
}
}
3. 提取工具類JDBC_utils
- src目錄下創(chuàng)建
db.properties
文件
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8&useSSL=false
username=root
password=root
JDBC_utils
:
package com.zzqsmile.lesson2.utils;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JDBC_utils {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
static {
try {
InputStream resourceAsStream = JDBC_utils.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(resourceAsStream);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
//1.驅(qū)動只用加載一次
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
// 2. 獲取連接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,username,password);
}
//3. 釋放資源,關(guān)閉鏈接`close(Connection conn,Statement stmt,ResultSet rs)`
public static void close(Connection conn, Statement stmt, ResultSet rs) {
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();
}
}
}
// 4.重載關(guān)閉方法`close(Connection conn, Statement stmt)`
public static void close(Connection conn, Statement stmt) {
close(conn, stmt, null);
}
}
- 使用JDBC_utils改進(jìn)編寫Statement的CURD:
package com.zzqsmile.lesson2;
import com.zzqsmile.lesson2.utils.JDBC_utils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Test_Statement {
public static void main(String[] args) {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
conn = JDBC_utils.getConnection(); //獲得數(shù)據(jù)庫連接
st = conn.createStatement(); //獲得SQL執(zhí)行對象
//增
String sql = "insert into user(username,password) values('admin1','333333')";
int i = st.executeUpdate(sql);
if (i>0){
System.out.println("插入成功寞肖!");
System.out.println();
}
//刪
String sql1 = "delete from user where id = '10'";
int i1 = st.executeUpdate(sql1);
if (i1>0){
System.out.println("刪除成功纲酗!");
System.out.println();
}
//改
String sql2 = "update user set password = '135790' where username = 'admin1'";
int i2 = st.executeUpdate(sql2);
if (i2>0){
System.out.println("修改成功!");
System.out.println();
}
//查
String sql3 = "select * from user where username = 'admin1'";
ResultSet resultSet = st.executeQuery(sql3);
if (resultSet.next()){
System.out.println("查詢成功新蟆!");
System.out.println("id="+resultSet.getObject("id"));
System.out.println("username="+resultSet.getObject("username"));
System.out.println("password="+resultSet.getObject("password"));
System.out.println();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JDBC_utils.close(conn,st);
}
}
}
- 使用JDBC_utils改進(jìn)編寫PreparedStatement的CURD:
package com.zzqsmile.lesson2;
import com.zzqsmile.lesson2.utils.JDBC_utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Test_PreparedStatement {
public static void main(String[] args) {
try {
//獲得數(shù)據(jù)庫連接
Connection connection = JDBC_utils.getConnection();
//編寫SQL --增加
String sql1 = "insert into user(username,password) values(?,?)";
//獲得SQL預(yù)編譯執(zhí)行對象
PreparedStatement preparedStatement1 = connection.prepareStatement(sql1);
//賦值
preparedStatement1.setString(1,"admin");
preparedStatement1.setString(2,"admin");
//執(zhí)行
int i1 = preparedStatement1.executeUpdate();
if (i1>0){
System.out.println("添加成功");
System.out.println();
}
//編寫SQL --刪除
String sql2 = "delete from user where id = ?";
//獲得SQL預(yù)編譯執(zhí)行對象
PreparedStatement preparedStatement2 = connection.prepareStatement(sql2);
//賦值
preparedStatement2.setString(1,"5");
//執(zhí)行
int i2 = preparedStatement2.executeUpdate();
if (i2>0){
System.out.println("刪除成功");
System.out.println();
}
//編寫SQL --更新
String sql3 = "update user set password = '123321' where username = ?";
//獲得SQL預(yù)編譯執(zhí)行對象
PreparedStatement preparedStatement3 = connection.prepareStatement(sql3);
//賦值
preparedStatement3.setString(1,"admin");
//執(zhí)行
int i3 = preparedStatement3.executeUpdate();
if (i3>0){
System.out.println("修改成功");
System.out.println();
}
//編寫SQL --查詢
String sql = "select * from user where username = ?";
//獲得SQL預(yù)編譯執(zhí)行對象
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//賦值
preparedStatement.setString(1,"admin");
//執(zhí)行
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
System.out.println("===========查詢結(jié)果============");
System.out.println("id="+resultSet.getObject("id"));
System.out.println("username="+resultSet.getObject("username"));
System.out.println("password="+resultSet.getObject("password"));
System.out.println();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}