JDBC基礎-將資料庫資料遍歷到List集合中
阿新 • • 發佈:2019-01-01
這裡用到了自己寫的JDBC工具類使用了配置檔案
配置檔案:pro.properties
配置檔案必須和你的class檔案放在一起才能連結資料庫
DriverPath=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydatabase
username=root
password=123
JDBCUtils類:
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
/**
* JDBC工具類
* Created by Aongi on 2017/5/1.
* Version 1.0
*/
public class JDBCUtils {
public JDBCUtils(){}
private static Connection CON;
static{
FileReader reader;
try {
String a=JDBCUtils.class.getResource("pro.properties").toString().substring(6);
reader = new FileReader(a);
//下面也是一種拿到檔案路徑的方式
//InputStream reader=JDBCUtils.class.getClassLoader().getResourceAsStream("pro.properties");
Properties pro = new Properties();
pro.load(reader);
reader.close();
Class.forName(pro.getProperty("DriverPath"));
CON= DriverManager.getConnection(pro.getProperty("url"),pro.getProperty("username"),pro.getProperty("password"));
} catch (Exception e) {
throw new RuntimeException("連線資料庫失敗!");
}
}
/*
*連結資料庫操作,返回Connection物件
*/
public static Connection getConnection(){
return CON;
}
}
Students 類
/**
* Created by Aongi on 2017/5/2.
* Version 1.0
*/
public class Students {
private Integer uid;
private String uname;
private String uaddress;
private Integer age;
public Students(Integer uid, String uname, String uaddress, Integer age) {
this.uid = uid;
this.uname = uname;
this.uaddress = uaddress;
this.age = age;
}
public Students(){}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getUaddress() {
return uaddress;
}
public void setUaddress(String uaddress) {
this.uaddress = uaddress;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Students{" +
"uid=" + uid +
", uname='" + uname + '\'' +
", uaddress='" + uaddress + '\'' +
", age=" + age +
'}';
}
}
JDBCdemo 類
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Aongi on 2017/5/1.
* Version 1.0
*/
public class JDBCdemo {
//main方法
public static void main(String[] args)throws Exception{
Connection con = JDBCUtils.getConnection();
String sql="SELECT * FROM users;";
PreparedStatement pst=con.prepareStatement(sql);
ResultSet rs= pst.executeQuery();
List<Students> list = new ArrayList<Students>();
while (rs.next()){
list.add(new Students(rs.getInt("uid"),rs.getString("uname"),rs.getString("uaddress"),rs.getInt("age")));
}
rs.close();
pst.close();
con.close();
for (Students s : list){
System.out.println(s);
}
}
}