mysql, "jdbc:mysql://localhost:3306/userdb", "root", "123",查询user表的全部字段,使用java编写
时间: 2023-07-19 10:24:00 浏览: 134
好的,下面是使用Java连接MySQL数据库,查询user表的全部字段并添加到userList中的代码:
```java
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
List<User> userList = new ArrayList<>();
try {
// 加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 建立连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/userdb", "root", "123");
// 创建Statement对象
stmt = conn.createStatement();
// 执行查询语句
String sql = "SELECT * FROM user";
rs = stmt.executeQuery(sql);
// 处理结果集
while (rs.next()) {
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setAge(rs.getInt("age"));
user.setGender(rs.getString("gender"));
userList.add(user);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭资源
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// 输出结果
for (User user : userList) {
System.out.println(user);
}
}
}
class User {
private int id;
private String name;
private int age;
private String gender;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
}
```
这段代码使用了Java中提供的JDBC接口来连接MySQL数据库,查询user表的全部字段,并将结果添加到userList中。需要注意的是,这里需要手动关闭连接、语句和结果集等资源。另外,为了方便处理结果,我定义了一个User类来存储查询结果。
阅读全文