Java数据库——ResultSet接口

使用SQL中的SELECT语句可以查询出数据库的全部结果,在JDBC的操作中数据库的所有查询记录将使用ResultSet进行接收,并使用ResultSet显示内容。

 

从user表中查询数据

import java.sql.*;

public class MySQL_demo {
	//定义MySQL的数据库驱动程序
	public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
	//定义MySQL数据库的连接地址
	public static final String DBURL = "jdbc:mysql://localhost:3306/mysql_demo";
	//MySQL数据库的连接用户名
	public static final String DBUSER = "root";
	//MySQL数据库的连接密码
	public static final String DBPASS = "123456";
	
	public static void main(String[] args) throws Exception {
		// TODO 自动生成的方法存根
		
		Connection conn = null;					//数据库连接
		Statement stmt = null;					//数据库操作
		
		ResultSet rs = null;			//保存查询结果
		String sql = "SELECT id,name,password,age,sex,birthday FROM user";
		Class.forName(DBDRIVER);			//加载驱动程序
		//连接MySQL数据库时,要写上连接的用户名和密码
		conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
		stmt = conn.createStatement();		//实例化Statement对象
		rs = stmt.executeQuery(sql);			//实例化ResultSet对象
		while(rs.next()){
//			int id = rs.getInt("id");
//			String name = rs.getString("name");
//			String pass = rs.getString("password");
//			int age = rs.getInt("age");
//			String sex = rs.getString("sex");
//			Date d = rs.getDate("birthday");
			int id = rs.getInt(1);
			String name = rs.getString(2);
			String pass = rs.getString(3);
			int age = rs.getInt(4);
			String sex = rs.getString(5);
			Date d = rs.getDate(6);
			System.out.println("编号:"+id);
			System.out.println("名字:"+name);
			System.out.println("密码:"+pass);
			System.out.println("年龄:"+age);
			System.out.println("性别:"+sex);
			System.out.println("生日:"+d);
		}
		
		rs.close(); 												//关闭结果集
		stmt.close(); 										//操作关闭
		conn.close(); 										//数据库关闭
	}
}

 

posted @ 2016-03-21 17:43  tonglin0325  阅读(583)  评论(0编辑  收藏  举报