package cn.hu3.com;
import cn.hu1.com.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class DemoStudent {
public static void main(String[] args) throws SQLException {
// 创建对象
Connection conn = JdbcUtils.getConnection();
PreparedStatement ps = conn.prepareStatement("select * FROM emppme");
// 设置参数
ResultSet rs = ps.executeQuery();
ArrayList<emppme> al = new ArrayList<emppme>();
while(rs.next()){
// 把记录封装成对象
emppme em = new emppme();
em.setId(rs.getInt("id"));
em.setUname(rs.getString("uname"));
em.setGender(rs.getBoolean("gender"));
// 把对象添加到集合中
al.add(em);
}
JdbcUtils.close(rs,ps,conn);
//遍历集合
for(emppme ep:al){
System.out.println(ep);
}
}
}
package cn.hu3.com;
public class emppme {
private int id;
private String uname;
private boolean gender;
@Override
public String toString() {
return "emppme{" +
"id=" + id +
", uname='" + uname + '\'' +
", gender=" + gender +
'}';
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getUname() {
return uname;
}

public void setUname(String uname) {
this.uname = uname;
}

public boolean isGender() {
return gender;
}

public void setGender(boolean gender) {
this.gender = gender;
}
}
package cn.hu1.com;

import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

/**
* JDBC工具类
* */
public class JdbcUtils {
private static String url;
private static String user;
private static String password;
private static String driver;
// 文件的读取 读取一次拿到所有值 使用静态代码块
static{
try {
// 读取资源文件 获取值 创建Properties 集合类
Properties pro = new Properties();
// 获取src的路径----》ClassLoader() 类加载器
ClassLoader classLoader = JdbcUtils.class.getClassLoader();
URL res = classLoader.getResource("jdbc.properties");
String path = res.getPath();
pro.load(new FileReader(path));
url=pro.getProperty("url");
user=pro.getProperty("user");
password=pro.getProperty("password");
driver=pro.getProperty("driver");

} catch (IOException e) {
e.printStackTrace();
}
}
//获取链接对象
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
//释放资源
public static void close(Statement stmt,Connection conn){
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//释放资源
public static void close(ResultSet rs,Statement stmt, Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
url=jdbc:mysql:///qy97
user=root
password=root
driver=com.mysql.jdbc.Driver
 

 

 
posted on 2019-04-02 21:16  惯她心  阅读(438)  评论(0编辑  收藏  举报