executeQuery() Java Guide
In Java, the executeQuery() method is used to execute a query statement and return a result set. This method is typically used for executing SELECT statements.
Here are the general steps to use the executeQuery() method:
- Create a Connection object to connect to the database.
- Create a Statement object for executing SQL statements.
- Execute a query statement using the executeQuery() method of the Statement object, and store the returned ResultSet object in a variable.
- Iterate through the ResultSet object to retrieve the query results.
The following is an example code demonstrating how to use the executeQuery() method to retrieve data from a database.
import java.sql.*;
public class Main {
public static void main(String[] args) {
try {
// 创建一个Connection对象
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
// 创建一个Statement对象
Statement stmt = conn.createStatement();
// 执行查询语句并获取结果集
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
// 遍历结果集并输出数据
while (rs.next()) {
System.out.println(rs.getString("column1") + " " + rs.getString("column2"));
}
// 关闭连接
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
In the example above, we start by creating a Connection object, followed by creating a Statement object. Next, we execute a SELECT statement using the executeQuery() method and store the results in a ResultSet object. Finally, we loop through the ResultSet object and display the query results. Lastly, we close the ResultSet, Statement, and Connection objects.