« | September 2025 | » | 日 | 一 | 二 | 三 | 四 | 五 | 六 | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | | | | | |
| 公告 |
暂无公告... |
Blog信息 |
blog名称: 日志总数:7 评论数量:2 留言数量:-1 访问次数:46199 建立时间:2009年3月9日 |

| |
JDBC基础知识 读书笔记, 心得体会, 软件技术, 电脑与网络, 职业生涯
wendyneil 发表于 2009/7/28 10:55:58 |
//Source:
//《精通Java Web整合开发》 刘斌 编著 电子工业出版社
// MySQL 参考手册
// 《JSP2.0 技术手册》 林上杰 林康司 编著 电子工业出版社
这里谈谈刚刚学习的JDBC链接,我是第一次弄这个。
JDBC访问数据库有四个步骤:
1. 将数据库的JDBC驱动加载到classpath中;
2. 加载JDBC驱动,并将其注册到DriverManager中:
采用Class.forName("……").newInstance():
其中……代表各个数据库的Driver,如MySQL就是com.mysql.jdbc.Driver
3. 建立数据库连接,获取Connection对象:
以MySQL为例:
String url="jdbc:mysql://localhost:3306/testDB?user=root&password=123&
useUnicode=true&characterEncoding=gb2312";
Connection conn=DriverManager.getConnection(url);
这里我们要详细讲讲其中的一些methods
Class.forName("……").newInstance
这里我们为什么要在加载完驱动程序后,再调用newInstance()呢?是因为加载驱动时可能会出现“Driver not found”的错误提示信息,因为在用Class.forName()加载时,会碰到JDBC规范与某些JVM产生问题,因此我们采用示例的程序。
getConnection()
这个方法除了上面的用法外,还有一种:
String url="jdbc:mysql://localhost:3306/testDB";
String user="root";
String password="123"; //这里我们数据库root用户密码设为123
Connection conn=DriverManager.getConnection(url,user,password);
4. 建立Statement对象或PreparedStatement对象:
//建立Statement对象
Statement stmt=conn.createStatement();
//建立PreparedStatement对象
String sql="select * from users where userName=?and password=?";
PreparedStatement pstmt=conn.prepareStatement(sql);
pstmt.setString(1,"admin");
pstmt.setString(2,"liubin");
5. 执行SQL语句:
//执行静态SQL查询
String sql="select * from users";
ResultSet rs=stmt.executeQuery(sql);
//执行动态SQL查询
ResultSet rs=pstmt.executeQuery();
//执行insert、update、delete等语句,先定义sql
6. 访问结果记录集ResultSet对象:
while(rs.next())
{
out.println("你的第一个字段内容为:"+rs.getString(1));
out.println("你的第二个字段内容为:"+rs.getString(2));
}
7. 依次将ResultSet、Statement、PreparedStatement、Connection对象关闭:
rs.close();
stmt.close();
pstmt.close();
conn.close();
|
|
|