深圳 医院,kb944043,科技天阅网
jdbc(java data base connectivity),用于实现java语言编程与数据库连接的api。
jdbc体系结构由两层组成:
建立jdbc连接:
import java.sql.*
class.forname("com.mysql.jdbc.driver"); connection conn = null; conn = drivermanager.getconnection("jdbc:mysql://hostname:port/db_name","db_username","db_password"); conn.close();
这样,我们的jdbc连接即已建好。
交互
连接建立后,通常通过jdbc statement、callablestatement和preparestatement这3个接口进行交互。
创建statement对象:
statement stmt = null; try{ stmt = conn.createstatement(); }catch(sqlexception e){ ... }finally{ ... }
该对象常用的3种方法:
boolean execute(string sql ):检索sql运行后结果是否存在,有则返回true,没有则返回false;
int executeupdate(string sql):检索sql语句所影响的行数,常用于会影响多行改动的sql语句,如insert、update、delete;
resultset executequery(string sql):返回运行后的结果集合,常用于select;
关闭statement对象:
finally{ stmt.close(); }
创建preparedstatement对象:
preparedstatement pstmt = null; try{ string sql = "update employees set age = ? where id = ?"; pstmt = conn.preparestatement(sql); ... }catch{ ... }finally{ pstmt.close(); }
其中?即表示要输入的参数。通过stmt.setxxx(number,value);输入参数,其中xxx表示参数数值类型,number表示?在程序出现的位置,从1开始计数;value表示输入参数的值;
statement对象可用的3种方法都可以使用。
创建callablestatement对象:
callablestatement cstmt = null; try{ string strsql = "{call getempname(?,?)}"; cstmte = conn.preparecall(sql); ... }catch(sqlexception e){ ... }finally{ cstmt.close(); }
对比前面的3种方法,callcblestatement多了一种方法:registeroutparameter(),该方法将jdbc数据类型绑定到存储过程并返回预期数据类型。
getxxx()
方法从out
参数中检索该值。 此方法将检索到的sql类型的值转换为对应的java数据类型。
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
浅析我对 String、StringBuilder、StringBuffer 的理解
使用IDEA搭建SSM框架的详细教程(spring + springMVC +MyBatis)
Springboot整合freemarker 404问题解决方案
引入mybatis-plus报 Invalid bound statement错误问题的解决方法
网友评论