Home > Database > Mysql Tutorial > 项目小结-JDBC访问数据库的基本步骤

项目小结-JDBC访问数据库的基本步骤

WBOY
Release: 2016-06-07 16:10:36
Original
1462 people have browsed it

JDBC访问数据库的基本步骤: (1)将数据库的JDBC驱动加载到classpath中,在基于javaEE的web应用实际开发过程中, 通常把目标产品的JDBC驱动复制到WEB-INF/lib中 (2)加载JDBC驱动,将其注册到DriverManager中 //Oracle8/8i/9i(thin模式)数据库 Class.forName(or

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对象关闭,释放所占用的资源





Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template