package cn.sasa.demo4;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class TestJDBCUtil {
public static void main(String[] args) throws SQLException {
Connection conn = JDBCUtil.getConn();
String sql = "SELECT * FROM product;";
PreparedStatement pstate = conn.prepareStatement(sql);
ResultSet rs = pstate.executeQuery();
ArrayList<Product> plist = new ArrayList<Product>();
while(rs.next()) {
Product p = new Product(rs.getInt("pid"),
rs.getString("pname"),
rs.getDouble("price"),
rs.getString("ptype"),
rs.getString("create_tm")
);
plist.add(p);
}
JDBCUtil.close(conn, pstate, rs);
for(var p : plist) {
System.out.println(p.getPname() +"\t"+ p.getPrice());
}
}
}
package cn.sasa.demo4;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/***
* JDBC 工具类
* @author THTF
*
*/
public class JDBCUtil {
private JDBCUtil() {}
private static Connection conn;
static {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://192.168.0.207:3306/mydb";
String user = "root";
String pwd = "XXXXXXXXXXXXXX1";
conn = DriverManager.getConnection(url, user, pwd);
}catch(Exception ex){
throw new RuntimeException(ex + "数据库连接失败");
}
}
/**
* 获得连接
*/
public static Connection getConn() {
return conn;
}
/**
* 关闭资源
*/
public static void close(Connection con, Statement state, ResultSet rs) {
if(con != null) {
try {
con.close();
}catch(SQLException ex){
}
}
if(state != null) {
try {
state.close();
}catch(SQLException ex){
}
}
if(rs != null) {
try {
rs.close();
}catch(SQLException ex){
}
}
}
public static void close(Connection con, Statement state) {
if(con != null) {
try {
con.close();
}catch(SQLException ex){
}
}
if(state != null) {
try {
state.close();
}catch(SQLException ex){
}
}
}
}
package cn.sasa.demo4;
public class Product {
private int pid;
private String pname;
private double price;
private String ptype;
private String create_tm;
public Product() {}
public Product(int pid, String pname,double price,
String ptype, String create_tm) {
this.pid = pid;
this.pname = pname;
this.price = price;
this.ptype = ptype;
this.create_tm = create_tm;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getPtype() {
return ptype;
}
public void setPtype(String ptype) {
this.ptype = ptype;
}
public String getCreate_tm() {
return create_tm;
}
public void setCreate_tm(String create_tm) {
this.create_tm = create_tm;
}
}