|
assword url等信息
Properties pro = new Properties();
File path = new File("src/all.properties");
pro.load(new FileInputStream(path));
String paths = pro.getProperty("filepath");
File file = new File(paths + "mysql.properties");
getFromProperties(file);
}
public static void getFromProperties(File file) throws IOException,
FileNotFoundException, ClassNotFoundException {// 读资源文件的内容
Properties pro = new Properties();
pro.load(new FileInputStream(file));
username = pro.getProperty("username");
password = pro.getProperty("password");
url = pro.getProperty("url");
driverName = pro.getProperty("driverName");
Class.forName(driverName);
}
public static void dbClose() throws Exception {// 关闭所有
if (rs != null)
rs.close();
if (st != null)
st.close();
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
}
public static ResultSet getById(String tableName, int id) throws Exception {// 用id来查询结果
st = conn.createStatement();
rs = st.executeQuery("select * from " + tableName + " ?where id=" + id
+ " ");
return rs;
}
public static ResultSet getByAll(String sql, Object... obj)
throws Exception {// 用关键字 实现查询 关键字额可以任意
sql = sql.replaceAll(";", "");
sql = sql.trim();
stmt = conn.prepareStatement(sql);
String[] strs = sql.split("\\?");// 将sql 以? 非开
int num = strs.length;// 得到?的个数
int size = obj.length;
for (int i = 1; i <= size; i++) {
stmt.setObject(i, obj[i - 1]);// 数组下标从0开始
}
if (size < num) {
for (int k = size + 1; k <= num; k++) {
stmt.setObject(k, null);// 数组下标从0开始
}
}
rs = stmt.executeQuery();
return rs;
}
public static void doInsert(String sql) throws SQLException {// 传入 sql 语句
// 实现插入操作
st = conn.createStatement();
st.execute(sql);
}
public static void doInsert(String sql, Object... args) throws Exception {// 传入参数
// 利用
// PreparedStatement
// 实现插入
// 传入的参数是任意多个 因为有Object 。。。args
int size = args.length;// 获得 Object ...obj 传过来的参数的个数
stmt = conn.prepareStatement(sql);
for (int i = 1; i <= size; i++) {
stmt.setObject(i, args[i - 1]);// 数组下标从0开始
}
stmt.execute();
}
public static int doUpdate(String sql) throws Exception {// 传入 sql 实现更新操作
st = conn.createStatement();
int num = st.executeUpdate(sql);
return num;
}
public static void doUpdate(String sql, Object... obj) throws Exception {
// 传入参数 利用 PreparedStatement实现更新
// 传入的参数是任意多个 因为有Object 。。。args
int size = obj.length;// 获得 Object ...obj 传过来的参数的个数
stmt = conn.prepareStatement(sql);
for (int i = 1; i <= size; i++) {
stmt.setObject(i, obj[i - 1]);// 数组下标从0开始
}
stmt.executeUpdate(sql);
}
public static boolean doDeleteById(String tableName, int id)
throws SQLException {// 删除记录 by id
st = conn.createStatement();
boolean b = st.execute("delete from " + tableName + " where id=" + id
+ "");
return b;
}
public static boolean doDeleteByAll(String sql, Object... args)
throws SQLException {// 删除记录 可以按任何关键字
sql = sql.replaceAll(";", "");
sql = sql.trim();
stmt = conn.prepareStatement(sql);
String[] strs = sql.split("\\?");// 将sql 以? 非开
int num = strs.length;// 得到?的个数
int size = args.length;
|