1、加载JDBC驱动程序:
//加载MySql的驱动类
Class.forName("com.mysql.jdbc.Driver") ;
// 加载oracle数据库驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
2、提供JDBC连接的URL
•连接URL定义了连接数据库时的协议、子协议、数据源标识。
•书写形式:协议:子协议:数据源标识
3、创建数据库的连接
//连接MySql数据库,用户名和密码都是root
String url = "jdbc:mysql://localhost:3306/test" ;
String username = "root" ;
String password = "root" ;
Connection con = DriverManager.getConnection(url , username , password ) ;
//连接oraclel数据库,用户名 hr和密码都是123
String user = "hr";
String password = "123";
String url = "jdbc:oracle:thin:@localhost:1521:xe";
Connection con = DriverManager.getConnection(url , username , password ) ;
4、创建一个Statement
Statement stmt = con.createStatement() ; PreparedStatement pstmt = con.prepareStatement(sql) ;
5、执行SQL语句
Statement接口提供了三种执行SQL语句的方法:(
ResultSet)executeQuery 、(
int )executeUpdate
和execute
6、处理结果
执行更新返回的是本次操作影响到的记录数。
执行查询返回的结果是一个ResultSet对象
7、关闭JDBC对象
关闭记录集
关闭声明
关闭连接对象