ResultSet
- 用来获得SQL查询结果
- 结果集包含了SQL语句的查询结果数据
- 调用语句的executeQuery方法返回结果集对象
- ResultSet常用的方法
(1)next():返回boolean类型数据,用来判断结果集中是否有数据
(2)getXXX():获取结果集
- 可以根据列名称
- 可以根据列索引
例子
创建Test3.java
package com;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class Test3 {
/**
* @param args
*/
public static void main(String[] args) {
query();
}
static void query(){
Connection connection=DBUtil.open();
String sql="select id,name,email from c";
try {
Statement statement=(Statement) connection.createStatement();
ResultSet resultSet= statement.executeQuery(sql);
while(resultSet.next()){
int id=resultSet.getInt(1);
String name=resultSet.getString(2);
String email=resultSet.getString(3);
System.out.println(id+","+name+","+email);
}
} catch (SQLException e) {
e.printStackTrace();
}
finally{
DBUtil.close(connection);
}
}
}
创建DBUtil.java,数据库链接
package com;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import com.mysql.jdbc.Connection;
public class DBUtil {
private static String driver;
private static String url;
private static String username;
private static String password;
static {
Properties p=new Properties();
Reader reader;
try {
reader = new FileReader("src//config.properties");
p.load(reader);
} catch (Exception e) {
e.printStackTrace();
}
driver=p.getProperty("driver");
url=p.getProperty("url");
username=p.getProperty("username");
password=p.getProperty("password");
}
public static Connection open() {
try {
Class.forName(driver);
return (Connection) DriverManager.getConnection(url,username,password);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void close(Connection conn) {
if(conn!=null)
{
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}