实现JDBC的六个步骤:
注册数据库驱动
获取数据库连接
获取传输器对象
传输sql执行获取结果集对象
遍历结果集获取信息
关闭资源
package cn.tedu.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
create database springdb;
use springdb;
create table stu(id int primary key auto_increment,name varchar(255),addr varchar(255));
insert into stu values (null,'aaa','bj'),(null,'bbb','sh'),(null,'ccc','gz'),(null,'ddd','sh'),(null,'eee','bj');
*/
public class Demo01 {
public static void main(String[] args){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
//1.注册数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取数据库连接
conn = DriverManager.getConnection("jdbc:mysql:///springdb","***","***");
//3.获取传输器
ps = conn.prepareStatement("select * from stu where id < ?");
ps.setInt(1, 4);
//4.执行sql获取结果集
rs = ps.executeQuery();
//5.遍历结果集获取结果
while(rs.next()){
String name = rs.getString("name");
System.out.println(name);
}
}catch(Exception e){
e.printStackTrace();
}finally {
//6.关闭资源
if(rs!=null){
try {
rs.close();
}catch(SQLException e){
e.printStackTrace();
}finally {
rs = null;
}
}
if(ps!=null){
try {
ps.close();
}catch(SQLException e){
e.printStackTrace();
}finally {
ps = null;
}
}
if(conn!=null){
try {
conn.close();
}catch(SQLException e){
e.printStackTrace();
}finally {
conn = null;
}
}
}
}
}