我们可以在 JDBC 中返回结果集吗?
jdbcjava 8object oriented programmingprogramming
可以,就像 Java 中的任何其他对象一样,我们可以将 ResultSet 对象作为参数传递给方法,并从方法中返回它。
让我们使用 CREATE 语句在 MySQL 数据库中创建一个名为 MyPlayers 的表,如下所示 −
CREATE TABLE MyPlayers( ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Date_Of_Birth date, Place_Of_Birth VARCHAR(255), Country VARCHAR(255), PRIMARY KEY (ID) );
现在,我们将使用 INSERT 语句在 MyPlayers 表中插入 7 条记录 −
insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India'); insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica'); insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka'); insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India'); insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India'); insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India'); insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');
在以下 JDBC 示例中,retrieveData() 方法与数据库建立连接,并将表 MyPlayers 的内容检索到 ResultSet 对象中并返回它。
main 方法调用 tries toretrieveData() 方法并打印获取的 ResultSet 的内容。
示例
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class ReturningResultSet { public static ResultSet retrieveData() throws SQLException{ //注册驱动程序 DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //获取连接 String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //创建 Statement 对象 Statement stmt = con.createStatement(); //检索数据 ResultSet rs = stmt.executeQuery("select * from MyPlayers"); return rs; } public static void main(String args[]) throws Exception { //从retrieveData() 方法获取 ResultSet 对象 ResultSet rs = retrieveData(); System.out.println("Contents of the Table MyPlayers: "); while(rs.next()) { System.out.print(rs.getInt("ID")+", "); System.out.print(rs.getString("First_Name")+", "); System.out.print(rs.getString("Last_Name")+", "); System.out.print(rs.getDate("Date_Of_Birth")+", "); System.out.print(rs.getString("Place_Of_Birth")+", "); System.out.print(rs.getString("Country")); System.out.println(); } } }
输出
Connection established...... Contents of the Table MyPlayers: 1, Shikhar, Dhawan, 1981-12-05, Delhi, India 2, Jonathan, Trott, 1981-04-22, CapeTown, SouthAfrica 3, Kumara, Sangakkara, 1977-10-27, Matale, Srilanka 4, Virat, Kohli, 1988-11-05, Mumbai, India 5, Rohit, Sharma, 1987-04-30, Nagpur, India 6, Ravindra, Jadeja, 1988-12-06, Nagpur, India 7, James, Anderson, 1982-06-30, Burnely, England 8, Ryan, McLaren, 1983-02-09, Kumberly, null