jdbc基础

一般步骤:


整个过程需要try catch

一.Load the Driver
1.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); //恢复原来的自动提交
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值