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

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;
}
}


}


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值