jdbc学习笔记(二) --引用

来源:互联网 发布:python while两个条件 编辑:程序博客网 时间:2024/04/30 01:36

一、Statement
execute(sql); 当不知道执行的SQL语句是什么类型的时候执行 ,返回值是boolean
executeQuery(sql); 执行查询语句
executeUpdate(sql); 执行更新语句

二、PreparedStatement
可以使用参数替代sql语句中的某些参数使用 "?"代替,他先将带参数的sql语句发送到数据库,进行编译,然后PreparedStatement会将参数发送给数据库。
在使用PreparedStatement时,在设置相应参数时,要指明参数的位置和类型,以及给出参数值
根据不同的参数类型使用不同的setXXX(参数的位置,参数值)来设置参数

例:
public void insert(Student s){
Connection con=ConnectionFactory.getConnection();//建立连接
String sql="insert into student(id,name) values(?,?)";
PreparedStatement ps=null;
try {
ps=con.prepareStatement(sql);//创建一个PreparedStatement
int index=1;
ps.setInt(index++,s.getStuId()); //为参数赋值
ps.setString(index++,s.getName());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(ps!=null)
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
if(con!=null)
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

CallableStatement是可以用非sql语句来访问数据库,他是通过调用存储过程(PL/SQL)来访问数据库的。可以直接使用连接来调用 prepareCall(...)方法,来执行这个存储过程,"..."是存储过程的名字。

对于系统时间要去数据库时间
TimeStamp 和 Date都可以保存时间
TimeStamp可以保存时、分、秒的数据,Date只保存日期年月的信息。

SQLException是检查异常必须处理要么throws ,要么try{}catch(){}
getErrorCode()可以获得错误码,可以对错误进行查询。

三、源数据
JDBC中有两种源数据,一种是数据库源数据,另一种是ResultSet源数据。

源数据就是描述存储用户数据的容器的数据结构。

ResultSet rs=ps.executeQuery(sql);
ResultSetMetaData m=rs.getMetaData();

getColumnCount(),获得实际列数
getColumnName(int colnum),获得指定列的列名
getColumnType(int colnum),获得指定列的数据类型
getColumnTypeName(int colnum),获得指定列的数据类型名

//打印结果集
public static void printRS(ResultSet rs)throws SQLException{
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next()){
for(int i = 1 ; i < = rsmd.getColumnCount() ; i++){
String colName = rsmd.getColumnName(i);
String colValue = rs.getString(i);
if(i>1){
System.out.print(",");
}
System.out.print(name+"="+value);
}
System.out.println();
}
}

四、数据库源数据

DatabaseMetaData
getURL(),获得连接数据库的URL
getDatabaseProductName() 获得数据库产品的名称
getDriverVersion() 获得JDBC驱动程序的String形式的版本号
getTables()获得数据库中该用户的所有表
getUserName() 获得数据库用户名。

五、异常的处理
try{}
catch(SQLException){}
try{}
catch(Exception){}

 
原创粉丝点击