JAVA-JDBC連接和相關學習
文章目錄
- JAVA-JDBC連接和相關學習
- JDBC基本連接方式
- SQL陳述句
- Statement和preparedStatement區別
- execute與executeUpdate的區別
- 事務
- ORM
- DAO
- 資料庫連接池
JDBC基本連接方式
首先準備作業下載安裝Mysql或者其他資料庫,其次匯入 mysql-connector-java-5.0.8-bin.jar 或其他第三方包(用于驅動)
然后連接:
Connection connection = null;
PreparedStatement preparedStatement = null;
//第一步加載驅動;
Class.forName("com.mysql.jdbc.Driver");
//第二步獲取連接;
// 建立與資料庫的Connection連接
// 這里需要提供:
// 資料庫所處于的ip:127.0.0.1 (本機)本地可以寫local:
// 資料庫的埠號: 3306 (mysql專用埠號)
// 資料庫名稱 weeklyreport
// 編碼方式 UTF-8
//serverTimezone最好加一下,因為有時候會報錯;
//useSSL=false
//MySQL在高版本需要指明是否進行SSL連接
//1.true 需要連接
//2.false 不需要連接
String url = "jdbc:mysql://localhost:3306/weeklyreport?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8";
String user = "root";
String password = "password";//自己的密碼
connection = DriverManager.getConnection(url, user, password);
//創建statement或者preparedStatement,先用preparedStatement舉例;
String sql = "insert into users2(USER_NAME,USER_PASSWORD,USER_ENTRYDATE) VALUES(?,?,?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, name);
preparedStatement.setString(2, password2);
preparedStatement.setString(3,date);
preparedStatement.executeUpdate();
//這就實作了一個插入注冊資訊的操作
//最后一步要實作關閉connection和preparedStatement操作;
connection.close();
preparedStatement.close();
完整的就是
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/weeklyreport?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8";
String user = "root";
String password = "password";//自己的密碼
connection = DriverManager.getConnection(url, user, password);
String sql = "insert into users2(USER_NAME,USER_PASSWORD,USER_ENTRYDATE) VALUES(?,?,?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, name);
preparedStatement.setString(2, password2);
preparedStatement.setString(3,date);
preparedStatement.executeUpdate();
}catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e){
e.printStackTrace();
} finally {
try {
//一般preparedStatement關閉在connection關閉之后;
connection.close();
preparedStatement.close();
} catch (SQLException e){
e.printStackTrace();
}
}
}
SQL陳述句
1、sql還有很多其他的操作,例如增刪改查
//增加
String sql = "insert into users2(USER_NAME,USER_PASSWORD,USER_ENTRYDATE) VALUES(?,?,?)";
//洗掉
String sql = "delete from hero where id = 5";
//更改
String sql = "update hero set name = 'name 5' where id = 3";
具體的其他操作可以參考菜鳥教程mysql里陳述句的具體用法
2、較為特殊的是查詢操作;
public boolean finduser(String name2,String password2) {
ResultSet result = null;
Connection connection = null;
PreparedStatement preparedStatement = null;
int i =0;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/weeklyreport?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8";
String user = "root";
String password = "password";
connection = DriverManager.getConnection(url, user, password);
String sql = "select * from users2 where USER_NAME= ? and USER_PASSWORD= ?";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, name2);
preparedStatement.setString(2, password2);
//特殊的就是要設定一個結果集ResultSet,把結果存放在結果集中,
result =preparedStatement.executeQuery();
while(result.next()) {
i++;
}
//這里實作的功能就是在登陸的時候驗證賬號和密碼,如果正確,那查詢得到的結果集就有內容并i++最后回傳true;
}catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e){
e.printStackTrace();
} finally {
try {
connection.close();
preparedStatement.close();
result.close();
//關閉結果集
} catch (SQLException e){
e.printStackTrace();
}
}
if (i == 0)
return false;
else
return true;
}
具體的其他操作可以參考菜鳥教程mysql里陳述句的具體用法
Statement和preparedStatement區別
1、
? Statement 需要進行字串拼接,可讀性和維護性比較差 ;
? PreparedStatement 使用引數設定,可讀性好,不易犯錯 ;
Statement s = connection.createStatement();
PreparedStatement preparedStatement= connection.prepareStatement(sql);
// Statement需要進行字串拼接,可讀性和維修性比較差
String sql0 = "insert into USERS1(null," + "'學生1'" + "," + "'123456'"+")";
s.execute(sql0);
String sql = "insert into USERS1(null,?,?,?)";
// PreparedStatement 使用引數設定,可讀性好,不易犯錯
// "insert into USERS1(null,?,?)";
preparedStatement.setString(1, "學生1");
preparedStatement.setString(2, "123456");
preparedStatement.execute();
2、 PreparedStatement有預編譯機制,性能比Statement更快
? 資料庫對帶?的SQL進行預編譯
? 每次執行,只需要傳輸引數到資料庫端
- 網路傳輸量比Statement更小
- 資料庫不需要再進行編譯,回應更快
3、 PreparedStatement防止SQL注入式攻擊, 比如登錄時密碼加入OR 1=1就會被sql讀取并登錄;
execute與executeUpdate的區別
1、 execute與executeUpdate的相同點:都可以執行增加,洗掉,修改
preparedStatement.execute();
preparedStatement.executeUpdate();
2、不同:
execute可以執行查詢陳述句
然后通過getResultSet,把結果集取出來
executeUpdate不能執行查詢陳述句
不同2:
execute回傳boolean型別,true表示執行的是查詢陳述句,false表示執行的是insert,delete,update等等
executeUpdate回傳的是int,表示有多少條資料受到了影響
事務
connection.setAutoCommit(false);
// 更改操作
String sql1 = "update hero set hp = hp +1 where id = "xuesheng1"";
statement.execute(sql1);
//第二個更新操作
// 不小心寫錯寫成了 updata(而非update)
String sql2 = "updata users1 set score = score -1 where name = "xuesheng2"";
statement.execute(sql2);
// 手動提交
connection.commit();
所以放在
connection.setAutoCommit(false);
connection.commit();
之間的事務只要一個操作有錯誤,那么全都不會進行,這樣可以保證差錯不出現;
ORM
其實就是建立一個物件其屬性可以存盤資料庫里的一條記錄然后展開操作;
ORM=Object Relationship Database Mapping
物件和關系資料庫的映射
簡單說,一個物件,對應資料庫里的一條記錄 ;
DAO
實際上就是運用ORM的思路,把資料庫相關的操作都封裝在這個類里面,其他地方看不到JDBC的代碼
資料庫連接池
提前創建數條連接,待執行緒使用,如果全部被使用,沒能使用的執行緒就等待連接用完重新回到資料庫連接池;并且, 這些連接都不會關閉,而是不斷的被回圈使用,從而節約了啟動和關閉連接的時間,
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class ConnectionPool {
List<Connection> cs = new ArrayList<Connection>();
int size;
public ConnectionPool(int size) {
this.size = size;
init();
}
public void init() {
//這里恰恰不能使用try-with-resource的方式,因為這些連接都需要是"活"的,不要被自動關閉了
try {
Class.forName("com.mysql.jdbc.Driver");
for (int i = 0; i < size; i++) {
Connection c = DriverManager
.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8", "root", "admin");
cs.add(c);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public synchronized Connection getConnection() {
while (cs.isEmpty()) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Connection c = cs.remove(0);
return c;
}
public synchronized void returnConnection(Connection c) {
cs.add(c);
this.notifyAll();
}
}
//代碼來自how2j網站
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/200339.html
標籤:其他
上一篇:first day
