一般步骤:
整个过程需要try catch
一.Load the Driver1.Class.forName("oracle.jdbc.driver.OracleDriver"); //此次使用oracle数据库,如果使用其他数据库就用其他数据库的注册名称
2.实例化时自动向DriverManager注册,不需要显式调用DriverManager.registerDriver方法
二.Connect to the DataBase
1.Connection c = DriverManager.getConnection(数据库的url)
三.Execute the SQL
1.Statement a = Connection.CreateStatement() //即c.CreateStatement()
2.a.executeQuery() //括号内写select语句,返回一个ResultSet
3.a.executeUpdate() //执行insert,delete,update语句
四.Retrieve the result data
1.循环取出结果 while(rs.next()){}
五.Show the result data
1.将数据库中的各种类型转换为java中的类型(get XXX方法)
六.Close (后开的先关)
1.close the result / close the statement /close the connection
注意事项:一个statement最好对应一个resultset, 如果一个statement对应多个resultset,那就只能得到一个resultset后的操作
1.编写sql语句,设置占位符
PreparedStatement
eg.
PreparedStatement pstmt = null;
pstmt = conn.prepareStatement("insert into dept values (?,?,?)");
pstmt.setInt(1, deptno);
pstmt.setString(2, dname);
pstmt.setString(3, loc);
pstmt.executeUpdate();
2.对 存储过程 进行调用
CallableStatement
eg. //p这个函数已经事先存在于Oracle数据库中
CallableStatement cstmt = conn.prepareCall("(call p(?,?,?,?))");
cstmt.registerOutParameter(3,Types.INTEGER);
cstmt.registerOutParameter(4,Types.INTEGER);
cstmt.setInt(1,3);
cstmt.setInt(2,4);
cstmt.setInt(4,5);
cstmt.execute();
3.批处理 Batch
Statement stmt = conn.createStatement();
stmt.addBatch(); //括号里写sql语句
可写多句,而不用多次创建stmt来调用sql语句,之后
stmt.executeBatch(); //运行
同样,prepareStatement 也可以这么用
4.运用事务处理 Transaction
conn.setAutoCommit(false); //首先不让它自动提交
...
conn.commit(); //执行一些sql语句之后手动提交
conn.setAutoCommit(true); //恢复原来的自动提交