package com.exam.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import com.exam.bean.User; /* * 用于登录验证的数据库 */ public class JDBCTest { //数据库查询语句 public static String findsql = "select*from tb_user"; //数据库查询方法 public static List<User> Find() { //初始化查询结果集 ResultSet rs = null; PreparedStatement pstmt = null; Connection conn = null; List<User> list = new ArrayList(); int id = 0; String username, password = null; try { conn = DBUtil.getconn(); pstmt = conn.prepareStatement(findsql); rs = pstmt.executeQuery(); while (rs.next()) { id = rs.getInt(1); username = rs.getString(2); password = rs.getString(3); User user = new User(id, username, password); list.add(user); } } catch (Exception e) { e.printStackTrace(); } finally { DBUtil.closeAll(rs, pstmt, conn); } return list; } // 测试是否能够拿到数据 public static void main(String[] args) { List<User> list = new ArrayList(); list = Find(); User user = new User(); Iterator<User> it = list.iterator(); while (it.hasNext()) { user = it.next(); System.out.println(user.getId()); System.out.println(user.getUsername()); System.out.println(user.getPassword()); } } }填写注释
时间: 2024-03-26 10:39:19 浏览: 174
mysql.rar_Mysql.r_java 连接mysql
这段代码为一个Java类,其中包含一个名为`JDBCTest`的类,通过Java JDBC API来连接数据库并执行查询语句。下面是这段代码的详细解释:
1. 导入必要的Java类库:
```java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.exam.bean.User;
```
2. 定义数据库查询语句:
```java
public static String findsql = "select * from tb_user";
```
3. 定义一个`Find()`方法,用于执行查询操作,并返回查询结果:
```java
public static List<User> Find() {
ResultSet rs = null;
PreparedStatement pstmt = null;
Connection conn = null;
List<User> list = new ArrayList();
int id = 0;
String username, password = null;
// 获取数据库连接
try {
conn = DBUtil.getconn();
pstmt = conn.prepareStatement(findsql);
rs = pstmt.executeQuery();
while (rs.next()) {
// 获取查询结果
id = rs.getInt(1);
username = rs.getString(2);
password = rs.getString(3);
User user = new User(id, username, password);
list.add(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
DBUtil.closeAll(rs, pstmt, conn);
}
// 返回查询结果
return list;
}
```
4. 定义一个`main()`方法,用于测试是否能够拿到数据:
```java
public static void main(String[] args) {
List<User> list = new ArrayList();
list = Find();
User user = new User();
Iterator<User> it = list.iterator();
while (it.hasNext()) {
user = it.next();
System.out.println(user.getId());
System.out.println(user.getUsername());
System.out.println(user.getPassword());
}
}
```
这段代码的作用是连接数据库,执行查询语句`select * from tb_user`,将结果存储在一个`List`对象中,并输出查询结果。其中`DBUtil`是一个自定义的Java类,用于连接数据库和关闭数据库连接。`User`是一个自定义的Java Bean类,用于存储查询结果。
阅读全文