java jdbc6_Java学习-JDBC
JDBC
1、數據庫驅動
應用程序通過驅動連接到數據庫,進而操作數據庫。
2、JDBC
簡化開發人員對數據庫的操作,提供了一個java操作數據庫的規范,俗稱JDBC
對于程序猿,只需要學習JDBC提供的接口。
java.sql
javax.sqlpublic?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
獲得返回的結果集
釋放連接URLString?url?=?"jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&useSSL=true";
//mysql?--?3306
//jdbc:mysql://主機地址:端口號/數據庫名?參數1&參數2
//oracle?--?1521
//jdbc:oracle:thin:@主機地址:端口號:sidDriverManagerConnection?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',?'z13@131.com',?'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',?'z13@133451.com',?'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"??>
com.mysql.cj.jdbc.Driver
jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&useSSL=true
root
handhand
5
10
60000
com.mysql.cj.jdbc.Driver
jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&useSSL=true
root
handhand
5
8
60000
工具類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();
}
}
}
}
總結
以上是生活随笔為你收集整理的java jdbc6_Java学习-JDBC的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WAP PUSH解析(3)——Andro
- 下一篇: Java 类在 Tomcat 中是如何加