/*
* 编写快速 入门的jdbc 程序 :
*
* 1. 先导入 具体的驱动jar包
* 2. 编写一个类 , 写jdbc 的程序
*
* 具体的编写 java类的 代码的步骤:
*
* 第一步: 注册驱动 --- 告诉 具体的要操做的是那个 数据库
* 第二步: 创建与 数据库的连接---Connection
* 第三步: 得到能够发送 sql 语句的 statement 对象
* 第四步: 执行sql 语句, 拿到 结果集对象
* 第五步: 解析结果集中的数据
* 第六步: 释放资源
*
*/html
@Test
public void test2() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 第一步: 注册驱动
// DriverManager.registerDriver(new Driver());
//这里 原本是 加载字节码, 可是 加载字节码的 时候 又 会执行 这个Driver类的静态代码快, 而静态代码块 有完成了驱动的注册, 因此
// 这行代码 就是那么巧 ...
Class.forName("com.mysql.jdbc.Driver");
// 第二步: 创建与 数据库的连接
// http://localhost:8080/day15/1.html
//一般 能够简写 为 : jdbc:mysql:///day15_jdbc
conn = DriverManager.getConnection("jdbc:mysql:///day15_jdbc", "root", "abc");
// 第三步:得到能够发送 sql 语句的 statement 对象
stmt = conn.createStatement();
// 第四步: 执行sql 语句, 拿到 结果集对象
// rs , 就封装了这个查询的结果
rs = stmt.executeQuery("select * from users");
// 第五步: 解析结果集中的数据
while(rs.next()){
int id = rs.getInt("id");
String username = rs.getString("username");
String password = rs.getString("password");
String nickname = rs.getString("nickname");
System.out.println("id: " + id+",username : " + username+", password : " + password +", nickname : " + nickname);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
// 第六步: 释放资源 --- 因为 数据库 连接很是的稀缺, 因此 在 操做完成后,记得释放资源 , 都会放到 finally 代码块 中
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs =null;
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt=null;
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn=null;
}
}
}
java