更新时间:2022-08-14 15:58:36
Java 应用通过 JDBC 连接到数据库执行有五步
DriverManager 类顾名思义,用来管理 driver。主要有注册接口。getConnection 的时候用 DriverManager 当前的 classloader 尝试顺序加载注册的 driver,加载到哪个用那个。
一个 connection 是一次应用和数据库的 session。也是 Statement, PreparedStatement, and DatabaseMetaData 的 factory。
管理这这次回话的提交,回滚,关闭连接。
provides methods to execute queries with the database. The statement interface is a factory of ResultSet
PreparedStatement 比 Statement 好的原因在于
提升性能
执行 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) {}
}
}