public class DbHelper {
private static String connstr = "jdbc:mysql://localhost:3306/frutable ?user=root&password=root&useUnicode=true&characterEncoding=utf-8";
private static String username = "root";
private static String password = "123456";
/*
static {
try {
Properties p = new Properties();
try {
p.load(new FileInputStream("db"));
} catch (Exception e) {
e.printStackTrace();
}
connstr=p.getProperty("connstr",connstr);
username=p.getProperty("username",username);
password=p.getProperty("password",password);
String driver = p.getProperty("driver","com.mysql.jdbc.Driver");
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
*/
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private static Connection getConnection() throws Exception {
return DriverManager.getConnection(connstr, username, password);
}
private static void closeAll(Connection conn, Statement st, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static int executeUpdate(String sql, Object... vals) {
Connection conn = null;
PreparedStatement st = null;
try {
conn = getConnection();
st = conn.prepareStatement(sql);
for (int i = 1; i <= vals.length; i++) {
st.setObject(i, vals[i - 1]);
}
return st.executeUpdate();
} catch (Exception e) {
return -2;
} finally {
closeAll(conn, st, null);
}
}
public static List executeQuery(String sql, Class cls ,Object... vals) {
Connection conn = null;
PreparedStatement st = null;
List list = new Vector();
try {
conn = getConnection();
st = conn.prepareStatement(sql);
for (int i = 1; i <= vals.length; i++) {
st.setObject(i, vals[i - 1]);
}
ResultSet rs= st.executeQuery();
ResultSetMetaData m = rs.getMetaData();
while(rs.next()) {
Object o = cls.newInstance(); //创建实例
for(int i=1;i<=m.getColumnCount();i++){
String colname = m.getColumnLabel(i);
try {
Field f = cls.getDeclaredField(colname); //获取字段
f.setAccessible(true); //忽略权限
if(f.getType().equals(int.class)||f.getType().equals(Integer.class)) { //获取类型判断
f.set(o, rs.getInt(i)); //赋值
}else if(f.getType().equals(double.class)||f.getType().equals(Double.class)) {
f.set(o, rs.getDouble(i));
}else {
f.set(o,rs.getObject(i) .toString());
}
}catch(Exception e) {
}
}
list.add(o);
}
return list;
} catch (Exception e) {
e.printStackTrace();
return new Vector();
} finally {
closeAll(conn, st, null);
}
}
}