如何使用JDBC查询所有记录
public class JdbcDao {
private Connection conn=null; //数据库连接对象
private String strSql=null;
//JDBC连接数据库
public JdbcDao() {
String driver ="com.mysql.jdbc.Driver";
try {
Class.forName(driver);
String url ="jdbc:mysql://localhost:3306/dev?characterEncoding=utf8";
conn=DriverManager.getConnection(url,"root", "");
System.out.println("连接mysql数据库成功");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
//查询所有学生信息,查询某个表的所有数据
public void query(Student student) {
Statement stmt=null; // sql语句对象
ResultSet rs=null; //保存结果集对象
Student stu=new Student(); //实例化学生对象
try {
strSql=" select * from student "; //查询SQL语句
stmt=conn.createStatement(rs.TYPE_SCROLL_INSENSITIVE,rs.CONCUR_READ_ONLY);
//执行SQL语句
rs=stmt.executeQuery(strSql); //返回结果集
while(rs.next()) { //循环遍历结果集,取值,设置学生对象属性值。
stu.setId(rs.getInt("id"));
stu.setName(rs.getString("name"));
stu.setPhone(rs.getString("phone"));
stu.setStuNo(rs.getString("stuNo"));
stu.setBirthday(rs.getString("brithday"));
System.out.println("查询成功"+strSql);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
System.out.println("查询数据成功"+strSql);
}
}