jdbc增删改查——jdbc查询数据
时间: 2023-07-08 10:54:46 浏览: 90
好的,JDBC是Java Database Connectivity的缩写,它是Java语言中用于操作数据库的标准API。在Java程序中使用JDBC查询数据的步骤如下:
1. 加载JDBC驱动程序
在使用JDBC操作数据库之前,需要先加载JDBC驱动程序。可以通过Class.forName()方法来加载驱动程序,例如:
```
Class.forName("com.mysql.jdbc.Driver");
```
2. 建立数据库连接
使用DriverManager.getConnection()方法建立与数据库的连接,需要指定数据库的URL、用户名和密码,例如:
```
String url = "jdbc:mysql://localhost:3306/test";
String username = "root";
String password = "123456";
Connection conn = DriverManager.getConnection(url, username, password);
```
3. 创建Statement对象
使用Connection对象的createStatement()方法创建Statement对象,用于执行SQL语句,例如:
```
Statement stmt = conn.createStatement();
```
4. 执行SQL语句
使用Statement对象的executeQuery()方法执行查询语句,例如:
```
String sql = "select * from student where age > 18";
ResultSet rs = stmt.executeQuery(sql);
```
5. 处理查询结果
使用ResultSet对象处理查询结果,例如:
```
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("id=" + id + ", name=" + name + ", age=" + age);
}
```
6. 关闭资源
使用完ResultSet、Statement和Connection等资源后需要关闭,例如:
```
rs.close();
stmt.close();
conn.close();
```
以上就是使用JDBC查询数据的步骤,希望能对你有所帮助。