JAVA数据库编程(JDBC技术)-入门笔记(二)
e.printStackTrace();
}
//返回Connection对象
return conn;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SelectQuery getcon = new SelectQuery();
getcon.getConnection();
//查询
String sql = "SELECT * FROM [dbo].[User]";
try {
PreparedStatement Ps = getcon.conn.prepareStatement(sql);
ResultSet Rs = Ps.executeQuery();
while(Rs.next()){
String name = Rs.getString("Name");
String password = Rs.getString("Password");
System.out.println(name);
System.out.println(password);
}
Rs.close();
Ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
运行结果如下:
结果出来啦o(^ ^)o不是重点,重点是这个查询里面我们都用到了JDBC技术中的那些类和接口,或许你看了上面的代码还是茫然我说的是和我一样入门的人,那么下面的解释后,你就懂得啦!
首先是我们在getConnection中用到的 DriverManager类
DriverManager类是用来管理数据库中所有的驱动程序,是JDBC的管理层,作用用户和驱动程序之间,并在数据库的驱动之间建立连接。DriverManager类中的方法都是静态方法,所以用的时候不需要实例化,直接调用类名就可以。
DriverManager类的常用方法如下:
方法
功能
getConnection(String url,String user,String password)
指定3个参数,连接数据库的url,数据库用户名,数据库密码
setLoginTimeout()
获取驱动程序试图登录到某一个数据库时可以等待的最长时间
printIn(String Message)
将一条消息打印到当前JDBC日志流中
其次我们看到就是Connection接口
Connection接口代表与特定的数据库的连接。要对数据表中的数据经行操作,首先要获取数据库连接。
Connection接口常用的方法如下:
方法
功能
createStatement()
创建Statement对象
createStatement(int resultSetType,int resultSetConcurrency)
创建一个Statement对象,该对象将生产具有给定类型,并发性和可保存性的ResultSet对象
prepareStatement()
创建预处理对象PreparedStatement
isReadOnly()
查看当前的Connection对象的读取模式是否为之读形式
setReadOnly()
设置当前Connection对象的读写模式i,默认是非只读模式
commit()
使所有上一次提交,回滚后进行的更改成为持久更改
roolback()
取消再当前事物中经行的所有更改,并释放此Connection对象当前持有的所有数据库锁
close()
立即释放Connection对象数据库和JDBC资源
PreparedStatement接口
PreparedStatement接口继承Statemetn接口,用于执行动态的SQL语句,通过PreparedStatement实例执行SQL语句,将被预编译并保存到PreparedStatement实例中,从而可以反复的执行SQL语句。可以通过Connection类的prepareStatement()方法获取PreparedStatement对象。PreparedStatement接口常用的方法:
方法
功能描述
execute()
在此PreparedStatement对象中执行SQL语句,该语句可以是任何类型的SQL语句
executeQuery()
在此PreparedStatement对象中SQL查询语句,返回结果为查询结果集ResultSet对象
executeUpadte()
在此PreparedStatement对象中执行SQL语句,该SQL语句必须是个INSET,UPDATE,DELETE语句,或者返回没有返回值的DDl语句
setByte(int pIndex,byte bt)
将参数pIndex位置上设置为给定的byte型参数值bt
setDouble(int pIndex,double dou)
将参数pIndex位置上设置为给定的double型参数值dou
setInt(int pInde,int x)
将参数pIndex位置上设置为给定的int型参数值x
setObject(int pIndex,Object o)
将参数pIndex位置上设置为给定的Object型参数值o
setString(int pIndex,String str)
将参数pIndex位置上设置为给定的String型参数值str
ResultSet接口
ResultSet接口类似一张数据表,用来暂时存放数据库查询操作获得的结果集。ResultSet实例具有指向当前数据行的指定,指针开始的位置在查询的结果集第一条记录的前面。在获取查询结果集时,可通过next()方法将指针向下移动。如果存在下一行,还方法返回true,否则返回false.
方法
功能
getInt()
以intt形式获取ResultSet对象的当前行的指定值
getFloa