阅读更多
package write_demo;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class JDBCUtils {
/**
* 连接数据库
* */
public static Connection getConnection() throws Exception {
//读取jdbc.properties文件,获取数据库信息
Properties info = new Properties();
info.load(new FileInputStream(new File("jdbc.properties")));
String url = info.getProperty("url");
String driverClass = info.getProperty("driverClass");
String user = info.getProperty("user");
String password = info.getProperty("password");
//加载驱动
Class.forName(driverClass);
//连接数据库
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
}
/**
* 关闭数据库连接对象
* */
public static void close(ResultSet rs,Statement st,Connection conn){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(st != null){
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 金典查询
* */
@SuppressWarnings("unchecked")
public static List select(String sql) {
Statement stat = null;
ResultSet rs = null;
ResultSetMetaData rsmd = null;
java.sql.Connection conOrcale = null;
List ll = new ArrayList();
try {
conOrcale = JDBCUtils.getConnection();
stat = conOrcale.createStatement();
// 得到结果集
rs = stat.executeQuery(sql);
// 用于获取关于 ResultSet 对象中列的类型和属性信息的对象
rsmd = rs.getMetaData();
while (rs.next()) {
try {
Map rowData = new HashMap();
for (int i = 1; i <= rsmd.getColumnCount(); i++)
rowData.put(rsmd.getColumnName(i), rs.getString(i));
ll.add(rowData);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
conOrcale.close();
stat.close();
rs.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return ll;
}
//测试jdbc是否连接成功
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
//System.out.println(getConnection());
List list = select("select * from h_hyjx_yellowpages");
for (Object obj : list) {
System.out.println(obj);
}
}
}