JDBC中的ResultSet
Posted 何甜甜在吗
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JDBC中的ResultSet相关的知识,希望对你有一定的参考价值。
ResultSet:结果集。存放数据库中的数据,可以将它想象成一张数据表,通过Statement对象中的executeQuery()方法获得
import com.mysql.jdbc.Statement;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.ResultSet;
import java.util.Properties;
/**
* Created by I am master on 2016/9/29.
*/
public class finallyjdbc {
public static void main(String[] args) throws Exception{
Connection connection=null;
Statement statement=null;
Driver driver = new com.mysql.jdbc.Driver();
String url = "jdbc:mysql://localhost:3306/student";
Properties properties = new Properties();
properties.put("user", "root");
properties.put("password", "root");
connection = driver.connect(url, properties);
statement = (Statement) connection.createStatement();
/*执行查询一条语句的操作*/
String query1 = "select * from studentInfo where id=1";
ResultSet resultSet1=statement.executeQuery(query1);
if(resultSet1.next()){
int id=resultSet1.getInt(1);
String name=resultSet1.getString("name");
int age=resultSet1.getInt(3);
String major=resultSet1.getString("class");
System.out.print(id);
System.out.print(name);
System.out.print(age);
System.out.println(major);
}
/*执行查询多条语句的操作*/
String query2 = "select * from studentInfo";
ResultSet resultSet2=statement.executeQuery(query2);
while (resultSet2.next()){
String id=resultSet2.getString("id");
String name=resultSet2.getString("name");
String age=resultSet2.getString("age");
String major=resultSet2.getString("class");
System.out.print(id);
System.out.print(name);
System.out.print(age);
System.out.println(major);
}
if(resultSet2!=null)
resultSet2.close();
if(resultSet1!=null)
resultSet1.close();
if(statement!=null)
statement.close();
if(connection!=null)
connection.close();
}
}
以上是关于JDBC中的ResultSet的主要内容,如果未能解决你的问题,请参考以下文章
java.sql.SQLException:jdbc 错误中的 Exhausted Resultset [重复]
何时关闭 JDBC 中的 Connection、Statement、PreparedStatement 和 ResultSet