package com.secondHand.db;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class DBUtil {
private String url = "jdbc:mysql://localhost:3306/db_secondhand?user=root&password=root";
private String dbUserName = "root";
private String dbUserPassword = "root";
private String driver = "com.mysql.jdbc.Driver";
private Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null;
public DBUtil() {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private Connection getConnection() {
try {
conn = DriverManager.getConnection(url, dbUserName, dbUserPassword);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
private 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();
}
}
}
public List query(String sql) {
List list = new ArrayList();
conn = this.getConnection();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
// 获取数据库表结构
ResultSetMetaData rsm = rs.getMetaData();
// 取得数据库的列数
int col = rsm.getColumnCount();
// 生成col长度的Object数组
Object[] obj = new Object[col];
// 遍历结果集,将结果存入Object数组
while (rs.next()) {
for (int i = 0; i < col; i++) {
obj[i] = rs.getObject(i + 1);
}
list.add(obj);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
this.close(rs, stmt, conn);
}
return list;
}
public void update(String sql) {
try {
conn = this.getConnection();
stmt = conn.createStatement();
stmt.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}finally{
this.close(rs, stmt, conn);
}
}
public static void main(String args[]) {
DBUtil nj = new DBUtil();
String sql = "select * from users";
List list = nj.query(sql);
// 返回list的迭代器
Iterator it = list.iterator();
// 遍历迭代器,取出结果
while (it.hasNext()) {
Object[] o = (Object[]) it.next();
int id = ((BigDecimal) o[0]).intValue();
System.out.println(id);
}
}
}