JDBC工具类

package com.lovo.util;

import java.io.*;
import java.sql.*;
import java.util.*;


public class DBUtil {

static {
try {
String filePath = "properties/configuration.properties";

File file = new File(filePath);
if (!file.exists()) {
file.createNewFile();
return null;
}
BufferedReader in = new BufferedReader(new FileReader(file));
String driver = in.readLine().split("=")[1].trim();

String url = in.readLine().split("=")[1].trim();

String user = in.readLine().split("=")[1].trim();

String password = in.readLine().split("=")[1].trim();

Class.forName(p.getProperty("driver"));
coon = DriverManager.getConnection(p.getProperty("url"),
p.getProperty("user"), p.getProperty("password"));
is.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}


/*持久层对数据库的操作方法,根据传入的sql语句返回ResultSet或布尔值。(需自己强转)*/
public static Object daoAll(Object ... all){
String sql = (String) all[all.length-1];
PreparedStatement ps = null;
if (sql.indexOf("select") == 0 || sql.indexOf("SELECT") == 0) {
//判断为查询语句
try {
ps = coon.prepareStatement(sql);
for (int i = 1; i < all.length; i++) {
ps.setObject(i, all[i-1]);
}
rs = ps.executeQuery();
return rs;
//返回包含查询结果集的ResultSet
} catch (SQLException e) {
e.printStackTrace();
}
}else{
//判断为其他语句
try {
ps = coon.prepareStatement(sql);
for (int i = 1; i < all.length; i++) {
ps.setObject(i, all[i-1]);
}
return ps.executeUpdate() > 0; //返回表示是否成功
的布尔值
} catch (SQLException e) {
e.printStackTrace();
} finally{
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
return null;
}
}

posted @ 2016-04-24 15:44  DAILU  阅读(121)  评论(0)    收藏  举报