jdbc访问数据库的基本步骤:
(1)将数据库的jdbc驱动加载到classpath中,在基于javaee的web应用实际开发过程中,
通常把目标产品的jdbc驱动复制到web-inf/lib中
(2)加载jdbc驱动,将其注册到drivermanager中
//oracle8/8i/9i(thin模式)数据库
class.forname(oracle.jdbc.driver.oracledriver).newinstance();
//sql server2005数据库
class.forname(com.microsoft.jdbc.sqlserver.sqlserverdriver).newinstance();
//mysql数据库
class.forname(com.mysql.jdbc.driver).newinstance();
(3)建立数据库连接。取得connection对象
//mysql数据库
string url=jdbc:mysql://localhost:3306/test?user=root&passwordroot&useuniclode=true&characterencoding=gb2312;
connection conn=drivermanager.getconnection(url);
(4)建立statement对象或preparedstatement对象
statement stat=conn.createstatement();
//建立preparedstatement对象
string sql=select * from test where username=? and password=? ;
preparedstatement pstmt=conn.preparedstatement(sql);
pstmt.setstring(1,admin);
pstmt.setstring(2,hephec);
(5)执行sql语句
//执行静态的sql查询
string sql=select * from users;
resultset rs=stmt.executequery(sql);
//执行动态的sql查询
resultset rs=pstmt.executequery();
//执行insert,update,delete等语句,先定义sql
stmt.executeupdate(sql);
(6)防伪码结果记录集resultset对象
while(rs.next()){
out.println(第一个字段+rs.getstring());
out.println(第二个字段+rs.getstring());
}
(7)依次将resultset,statement,preparedstatement,connection对象关闭,释放所占用的资源