数据库和java(eclipse)连接查询users表中的所有记录

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38224607/article/details/80263475
package cn.itcast.ch10.demo;


import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
 * 查询users表中的所有记录
 */
public class Example01 {


public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//1.加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
//数据库的url
String url = "jdbc:mysql://localhost:3306/ch10";
//数据库用户名
String user = "root";
//数据库密码
String password = "111";
//2.获取到数据库的连接对象
conn = DriverManager.getConnection(url, user, password);
//3.获取语句对象
stmt = conn.createStatement();
//定义一个sql语句
String sql = "select * from users";
//4.语句对象将sql语句发送到数据库上,执行后得到结果集
rs = stmt.executeQuery(sql);
//5.遍历结果集,通过向下移动光标,光标指向哪一行就可以获取当前记录行的各个字段的值
while(rs.next()){
//获取当前记录行的各个字段的值,根据字段名获取字段值
int id = rs.getInt("id");
String name = rs.getString("name");
String pwd = rs.getString("password");
Date birthday = rs.getDate("birthday");
//打印当前行各个字段值
System.out.println(id+","+name+","+pwd+","+birthday);
}


} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//6.释放资源
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rs = null;
}

if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stmt = null;
}

if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn = null;
}
}


}


}

猜你喜欢

转载自blog.csdn.net/qq_38224607/article/details/80263475