如何连接数据库——遍历查询数据表
MySql数据库 表名为User表
准备一个类 类名为User 类里放入表的字段
public class User {
private int userid;
private String username;
private String password;
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
查询方法
//登录名
private static String username="root";
//登录密码
private static String password="root";
//连接数据库地址
private static String url="jdbc:mysql://localhost:3306/test";
private static String driver="com.mysql.jdbc.Driver";
//参数
private static Connection con=null;
private static PreparedStatement ps=null;
private static ResultSet rs=null;
public static void selectAll() throws ClassNotFoundException, SQLException{
//在用list来获取
List<User>users= new ArrayList<User>();
//获取 jdbc.driver包-驱动类
Class.forName(driver);
//获取数据库表列名
java.sql.Connection con=DriverManager.getConnection(url, username, password);
Statement st=con.createStatement();
//执行查询语句
ResultSet rs=st.executeQuery("select * from user");
//实例User类
User user=null;
//遍历
while(rs.next()){
user=new User();
user.setUserid(rs.getInt("userid"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
users.add(user);
}
//遍历输出
for (User user2 : users) {
System.out.println("登录名:"+user2.getUsername()+", 登录密码:"+user2.getPassword());
}
rs.close();
st.close();
con.close();
}