標籤:
以前在公司直接用到的關於資料庫方面的都是用ibatis,現在先來學些jdbc編程,順便比較一下與ibatis架構的區別。
一,使用步驟:
1,載入驅動。
Class.forName(“com.mysql.jdbj.Driver”);
2,使用DriverManager擷取資料庫連接。url寫法:jdbc:subprotocol,other stuff。如mysql: jdbc:mysql://hostname:port/databasename
Connection conn = DriverManager.getConnection(url,user,pass);
3,使用Connection來建立一個Statement對象。
Statement stmt = conn.createStatement();
4.1,使用statement執行SQL語句。Statement有三種執行SQL語句的方法:
1)execute()可執行select任何SQL語句——返回一個boolean值。
2)executeQuery()執行select語句——返回查詢到的結果集。
3)executeUpdate()用於執行DML語句,返回一個整數代表被SQL漁具影響的記錄條數。
ResultSet rs = stmt.executeQuery(sql);
4.2使用preparedStatement執行SQL語句。
如果需要經常反覆執行一條結構相似的漁具,可以使用帶預留位置(?)參數的SQL語句來代替它。使用PreparedStatement介面。在設定的使用可以用setXxx(int index,Xxx value)的方法來傳入參數值。
例子:
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.util.Properties;
public class ConnMysql {
private String driver;
private String url;
private String user;
private String pass;
private void initParam(String paramFile) throws Exception{
Properties props = new Properties();
props.load(new FileInputStream(paramFile));
driver = props.getProperty("driver");
url = props.getProperty("url");
user = props.getProperty("user");
pass = props.getProperty("pass");
}
public static void main(String[] args) throws Exception {
ConnMysql ed = new ConnMysql();
ed.initParam("mysql.ini");
Class.forName(ed.driver);
try(
Connection conn = DriverManager.getConnection(ed.url,ed.user,ed.pass);
Statement stmt = conn.createStatement();
PreparedStatement pstmt = conn.prepareStatement("insert into s1 values(?,?)");
)
{
for(int i = 0; i < 100; i++){
pstmt.setInt(1, i+5);
pstmt.setInt(2,i);
pstmt.executeUpdate();
}
}
}
}
5,可以使用mysql.ini設定檔代替driver,url,user,pass的值。這個檔案要把它移進工程。而不是移進src目錄下面。
6,使用try(){}
從 Java 7 build 105 版本開始,Java 7 的編譯器和運行環境支援新的 try-with-resources 語句,稱為 ARM 塊(Automatic Resource Management) ,自動資源管理。
資料流會在 try 執行完畢後自動被關閉,前提是,這些可關閉的資源必須實現 java.lang.AutoCloseable 介面。
二, 比較statement和preparedStatement的。
1,PreparedStatement先行編譯SQL語句,效能更好。
2,PreparedStatement無須“拼接”SQL語句,編程更簡單。
3,PreparedStatement可以防止SQL語句注入。
java jdbc筆記整理