JDBC
1、資料庫驅動
應用程式通過驅動連接到資料庫,進而操作資料庫,
2、JDBC
簡化開發人員對資料庫的操作,提供了一個java操作資料庫的規范,俗稱JDBC
對于程式猿,只需要學習JDBC提供的介面,
java.sql
javax.sql
匯入資料庫驅動的包: mysql-connector-java-8.0.23.jar
public class DemoJdbc01 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.加載驅動
Class.forName("com.mysql.cj.jdbc.Driver");
//2.連接 用戶資訊和url
String url = "jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&useSSL=true";
String username = "root";
String password = "handhand";
//3.連接成功,資料庫物件 Connection代表資料庫
Connection connection = DriverManager.getConnection(url, username, password);
//4.執行SQL的物件 Statement
Statement statement = connection.createStatement();
//5.執行SQL的物件 去 執行SQL,可能存在結果,
String sql = "select * from users";
//回傳的結果集
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
System.out.println("id" + resultSet.getObject("id"));
System.out.println("name" + resultSet.getObject("name"));
System.out.println("password" + resultSet.getObject("password"));
System.out.println("email" + resultSet.getObject("email"));
System.out.println("dirthday" + resultSet.getObject("dirthday"));
}
//6.釋放連接
resultSet.close();
statement.close();
connection.close();
}
}
- 加載驅動
- 連接資料庫 DriverManager
- 獲得執行sql的物件 Statement
- 獲得回傳的結果集
- 釋放連接
URL
String url = "jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&useSSL=true";
//mysql -- 3306
//jdbc:mysql://主機地址:埠號/資料庫名?引數1&引數2
//oracle -- 1521
//jdbc:oracle:thin:@主機地址:埠號:sid
DriverManager
Connection connection = DriverManager.getConnection(url, username, password);
//connection 代表資料庫,可以做資料庫的操作
//資料庫設定自動提交
connection.getAutoCommit();
//事務提交
connection.commit();
//事務回滾
connection.rollback();
Statement PrepareStatement 執行SQL的物件
statement.executeQuery();//查詢操作 回傳ResultSet
statement.executeUpdate(); //執行任何sql
statement.execute();//更新、插入、洗掉,回傳受影響的行數
ResultSet 查詢的結果集:封裝了所有的查詢結果
//在不知道列型別的情況下使用getObject,否則使用指定的型別
resultSet.getObject();
resultSet.getString();
resultSet.getInt();
resultSet.getFloat();
resultSet.getDate();
...
遍歷
//移動到最前面
resultSet.beforeFirst();
//移動到最后面
resultSet.afterLast();
//移動到下一個
resultSet.next();
//移動到前一行
resultSet.previous();
//移動到指定行
resultSet.absolute(row);
釋放資源
resultSet.close();
statement.close();
connection.close();
3、Statement物件
執行SQL的物件 Statement
Statement statement = connection.createStatement();
CRUD操作-create
使用executeUpdate(String sql)方法完成資料添加操作:
String sqlCreate = "INSERT INTO users VALUES ( 4, 'test', '134513', '[email protected]', '1995-01-01')";
int num = statement.executeUpdate(sqlCreate);
if (num > 0) {
System.out.println("插入資料成功");
}
CRUD操作-update
使用executeUpdate(String sql)方法完成資料更新操作:
String sqlUpdate = "UPDATE users u \n" +
"SET s.NAME = 'test02' \n" +
"WHERE\n" +
"\ts.id = 4";
int num = statement.executeUpdate(sqlUpdate);
if (num > 0) {
System.out.println("更新資料成功");
}
CRUD操作-delete
使用executeUpdate(String sql)方法完成資料洗掉操作:
String sqlDelete="DELETE \n" +
"FROM\n" +
"\tusers u \n" +
"WHERE\n" +
"\tu.id = 4";
int num = statement.executeUpdate(sqlDelete);
if (num > 0) {
System.out.println("插入洗掉成功");
}
CRUD操作-read
使用executeQuery(String sql)方法完成資料查詢操作:
String sql = "select * from users";
//回傳的結果集
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
}
創建utils工具類
public class JdbcUtils {
private static String driver = null;
private static String url = null;
private static String name = null;
private static String password = null;
static {
try {
InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(in);
//讀取properties檔案定義的引數值
driver = properties.getProperty("driver");
url = properties.getProperty("url");
name = properties.getProperty("username");
password = properties.getProperty("password");
//驅動加載,只需要一次
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
//獲取連接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, name, password);
}
public static void release(Connection connection, Statement statement, ResultSet resultSet) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
呼叫 utils工具類
public class DemoInsert {
public static void main(String[] args) throws SQLException {
Connection connection = JdbcUtils.getConnection();
Statement statement = connection.createStatement();
String sql = "INSERT INTO users\n" +
"VALUES\n" +
"\t( 4, 'darj453o', '14534513', '[email protected]', '1995-01-01' )";
int i = statement.executeUpdate(sql);
if (i>0){
System.out.println("插入成功");
}
JdbcUtils.release(connection,statement,null);
}
}
4、PreparedStatement物件
PreparedStatement 使用?占位符
防止SQL注入的本質,傳遞進來的引數當做字符
public class DemoUpdate {
public static void main(String[] args) throws SQLException {
Connection connection = JdbcUtils.getConnection();
//區別Statement
//使用?占位符
String sql = "UPDATE users s \n" +
"SET s.NAME = ?,\n" +
"s.dirthday = ? \n" +
"WHERE\n" +
"\ts.id = ?";
//預編譯sql
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//手動賦值
preparedStatement.setString(1, "test02");
//sql.Date 資料庫 java.sql.Date()
//util.Date Java new Date().getTime()
preparedStatement.setDate(2, new java.sql.Date(System.currentTimeMillis()));
preparedStatement.setInt(3, 4);
//執行
int i = preparedStatement.executeUpdate();
if (i > 0) {
System.out.println("更新成功");
}
JdbcUtils.release(connection, preparedStatement, null);
}
}
5、事務
ACID原則
原子性:要哦全部完成,要么都不完成
一致性:總數不變
隔離性:多個行程互不干擾,存在以下問題
- 臟讀:一個事務讀取了另一個沒有提交的事務
- 不可重復讀:在同一個事務內,重復讀取表中的資料,表資料發生了改變
- 虛讀:在一個事務內,讀取到了別人插入的資料,導致前后讀出來的結果不一致
持久性:一旦提交不可逆,持久化到資料庫
6、資料庫連接池
資料庫執行步驟:資料庫連接 --- 執行完畢 --- 釋放
池化技術:準備一些預先的資源,過來就連接準備好的
連接池常用的引數
-
最小連接數:10
-
最大連接數: 100 業務最高承載上限
-
等待超時:100ms
撰寫連接池,需要實作一個介面 DateSource
開源資料源實作
DBCP
C3P0
Druid
使用這些連接池之后,可以節省連接資料庫的代碼Connection connection = JdbcUtils.getConnection();
DBCP
需要用到的jar包:commons-dbcp-1.4.jar、commons-pool-1.6.jar
-
組態檔
#連接設定 driverClassName=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&useSSL=true username=root password=handhand #初始化連接 initialSize=10 #最大連接數 maxActive=50 #最大空閑連接 maxIdle=20 #最小空閑連接 minIdle=5 #超時等待 以毫秒為單位 maxWait=60000 #JBDC驅動建立連接是負載的連接屬性的格式必須為:[屬性名=property;] #注意:“” 兩個屬性會被明確的傳遞,因此這里不需要包含他們 connectionProperties=userUnicode=true;characterEncoding=utf8 #指定有連接池鎖創建的連接的自動提交狀態(auto-commit)狀態 defaultAutoCommit=true #driver default 指定由連接池所創建的連接的只讀(read-only)狀態 defaultReadOnly = false #driver default 指定指定由連接池所創建的連接的事物級別(TransactionIsolation) defaultTransactionIsolation=READ_UNCOMMITTED -
工具類
public class JdbcUtilsDbcp { private static DataSource dataSource = null; static { try { InputStream in = JdbcUtilsDbcp.class.getClassLoader().getResourceAsStream("dbcpconfig.properties"); Properties properties = new Properties(); properties.load(in); //創建資料源 工廠模式 dataSource = BasicDataSourceFactory.createDataSource(properties); } catch (Exception e) { e.printStackTrace(); } } //獲取連接 public static Connection getConnection() throws SQLException { return dataSource.getConnection(); } public static void release(Connection connection, Statement statement, ResultSet resultSet) { if (resultSet != null) { try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if (statement != null) { try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection != null) { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
C3P0
需要用到的jar包:mchange-commons-java-0.2.20.jar、c3p0-0.9.5.5.jar
- 組態檔 c3p0-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
<!--使用默認的配置讀取資料庫連接池物件
如果在代碼中"ComboPooledDataSource ds = new ComboPooledDataSource()"
這樣就會使用C3P0的預設-->
<default-config>
<!-- 連接引數 -->
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&useSSL=true</property>
<property name="user">root</property>
<property name="password">handhand</property>
<!-- 連接池引數 -->
<!--初始化申請的連接數量-->
<property name="initialPoolSize">5</property>
<!--最大的連接數量-->
<property name="maxPoolSize">10</property>
<!--超時時間-->
<property name="checkoutTimeout">60000</property>
</default-config>
<!--代碼中"ComboPooledDataSource ds = new ComboPooledDataSource("Darker")" -->
<named-config name="Darker">
<!--連接引數-->
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&useSSL=true</property>
<property name="user">root</property>
<property name="password">handhand</property>
<!--連接池引數 -->
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">8</property>
<property name="checkoutTimeout">60000</property>
</named-config>
</c3p0-config>
- 工具類
public class JdbcUtilsC3P0 {
private static ComboPooledDataSource dataSource = null;
static {
try {
//創建資料源
dataSource = new ComboPooledDataSource("Darker");
} catch (Exception e) {
e.printStackTrace();
}
}
//獲取連接
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
public static void release(Connection connection, Statement statement, ResultSet resultSet) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/252442.html
標籤:Java
