JDBC
Java 應(yīng)用通過(guò) JDBC 連接到數(shù)據(jù)庫(kù)執(zhí)行有五步
- Register the driver class
- Creating connection
- Creating statement
- Executing queries
- Closing connection
DriverManager class
DriverManager 類顧名思義政钟,用來(lái)管理 driver揣钦。主要有注冊(cè)接口谴仙。getConnection 的時(shí)候用 DriverManager 當(dāng)前的 classloader 嘗試順序加載注冊(cè)的 driver,加載到哪個(gè)用那個(gè)昧绣。
Connection Interface
一個(gè) connection 是一次應(yīng)用和數(shù)據(jù)庫(kù)的 session。也是 Statement, PreparedStatement, and DatabaseMetaData 的 factory爽航。
管理這這次回話的提交传藏,回滾,關(guān)閉連接屉更。
PreparedStatement interface
provides methods to execute queries with the database. The statement interface is a factory of ResultSet
PreparedStatement 比 Statement 好的原因在于
-
提升性能
執(zhí)行 sql 分四步- Parsing of sql query
- Compile this Query
- optimization of data acquisition path
- execute the query
PreparedStatement 只需要做一次前三步徙融,而 Statement 每次都要做前三步。
通過(guò)類型校驗(yàn)瑰谜,escapse 特俗字符防止 sql 注入
public class JdbcTest {
public static void main(String args[]) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager
.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oracle");
PreparedStatement stmt = con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1, 101);
stmt.setString(2, "Ratan");
int i = stmt.executeUpdate();
System.out.println(i + " records inserted");
con.close();
} catch (Exception e) {}
}
}