package com.searchcontrol.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class DBHelper {
private static Connection conn ;
private static PreparedStatement pstm ;
private static ResultSet rs;
public static Connection getConnection(){
try {
String driverClass = "com.sybase.jdbc3.jdbc.SybDriver";
InputStream is = new FileInputStream(new File("D:/wbs/jdbc.properties"));
Properties prop = new Properties();
prop.load(is);
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
Class.forName(driverClass);
conn = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
System.out.println("can not find the driver");
}catch (FileNotFoundException e) {
System.out.println("can not find file jdbc.properties in resource");
}catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void close(){
try {
if(rs!=null)
rs.close();
if(pstm!=null)
pstm.close();
if(conn!=null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
*
* @param sql
* @return
*/
public static int executeNonQuery(String sql){
int result = 0;
try {
if(conn == null){
getConnection();
}
pstm = conn.prepareStatement(sql);
result = pstm.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
close();
}
return result;
}
public static int executeNonQuery(String sql,Object...objects){
int result = 0;
try {
if(conn == null){
getConnection();
}
pstm = conn.prepareStatement(sql);
for (int i = 0; i < objects.length; i++) {
pstm.setObject(i+1, objects[i]);
}
result = pstm.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
close();
}
return result;
}
public static ResultSet executeQuery(String sql){
try {
if(conn == null){
getConnection();
}
pstm = conn.prepareStatement(sql);
rs = pstm.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
close();
}
return rs;
}
public static ResultSet executeQuery(String sql,Object...objects){
try {
if(conn == null){
getConnection();
}
pstm = conn.prepareStatement(sql);
if(objects != null){
for (int i = 0; i < objects.length; i++) {
pstm.setObject(i+1, objects[i]);
}
}
rs = pstm.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
close();
}
return rs;
}
public static boolean isExist(String sql,Object...objects){
try {
rs = executeQuery(sql, objects);
if(rs.next()){
return true;
}
return false;
} catch (SQLException e) {
e.printStackTrace();
close();
}
return false;
}
public static void main(String[] args)throws Exception{
ResultSet rs = executeQuery("select * from UT_FYCX_ZHXX");
while (rs.next()) {
System.out.println(rs.getString(2));
}
close();
}
}
------解决方案--------------------