JDBC中的ResultSet接口表示由SQL查询生成的表格数据。它有一个光标指向当前行。最初,此光标位于第一行之前。
您可以使用移动光标的next()方法,你可以检索使用ResultSet接口(getInt()的getter方法行的列值getString(),getDate()等等)。
要从表中检索所需数据:
连接到数据库。
创建一个Statement对象。
使用executeQuery()方法执行该语句。对于此方法,以字符串格式传递选择查询。要检索所有值,我们使用以下查询:
Select * from TableName;
要检索特定的列,请指定所需的列名称,而不用*作为:
select Name, DOB from Emp
假设我们在数据库中有一个名为Emp的表,其内容如下:
+----------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+--------------+------+-----+---------+-------+ | Name | varchar(255) | YES | | NULL | | | DOB | date | YES | | NULL | | | Location | varchar(255) | YES | | NULL | | +----------+--------------+------+-----+---------+-------+
以下JDBC示例从Emp表中检索员工的Name和DOB值。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class RetrievingParticularColumn {
public static void main(String args[]) throws Exception {
//注册驱动程序
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//获得连接
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//创建一个Statement对象
Statement stmt = con.createStatement();
//检索数据
ResultSet rs = stmt.executeQuery("select Name, DOB from Emp");
System.out.println("Contents of the table");
while(rs.next()) {
System.out.print("Name of the Employee: "+rs.getString("Name")+", ");
System.out.print("Date of Birth: "+rs.getDate("DOB"));
System.out.println("");
}
}
}Connection established...... Contents of the table Name of the Employee: Amit, Date of Birth: 1970-01-08 Name of the Employee: Sumith, Date of Birth: 1970-01-08 Name of the Employee: Sudha, Date of Birth: 1970-01-05