package cn.itcast.jdbc;
import java.sql.*;
public class JdbcDemo04 {
public static void main(String[] args) {
Connection conn = null; //定义为全局变量
Statement stat = null;
ResultSet rs = null;
try {
//1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2.获取数据库连接对象
conn = DriverManager.getConnection("jdbc:mysql:///db1", "root", "123456");
//3.定义sql
String sql = "select * from stu";
//3.获取执行sql对象
stat = conn.createStatement();
//4.执行sql
rs = stat.executeQuery(sql);
//5.处理数据,让游标向下移动一行
while(rs.next()){
//6.获取数据
int id = rs.getInt(1);
String name = rs.getString("name");
String age = rs.getString("age");
System.out.println(id+"----"+name+"-----"+age);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stat!=null){
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
标签:JDCB,rs,查询,printStackTrace,sql,catch,null,数据,conn
From: https://www.cnblogs.com/lcc-lv/p/16488784.html