- 数据库连接
public class DBhelper{
//数据库驱动
public static final String driver_class = "org.netezza.Deiver";
//数据库位置
public static final String driver_url = "jdbc:netezza://10.16.1.56:5480/wml";
//用户名
public static final String user = "***";
//密码
public static final String password = "***";
private static Connection connection = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;//查询结果集
//构造函数
public DBhelper(){
try{
connection = DBhelper.getConnInstance();
}catch (Exception e){
e.printStackTrace();
}
}
//线程同步
private static synchronized Connection getConnInstance(){
if(connection = null){
try{
Class.forName(driver_class);
connection = DriverManager.getConnection(driver_url, user, password);
}catch (ClassNotFoundException e){
e.printStackTrace();
}catch (SQLException e){
e.printStackTrace();
}
System.out.println("连接数据库成功");
}
return connection;
}
//关闭数据库连接
public void close(){
try{
if(resultSet != null){
this.resultSet.close();
}
if(preparedStatement != null){
this.preparedStatement.close();
}
if(connection != null){
DBhelper.connection.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
//执行SQL语句查询结果
public ResultSet executeQuery(String sql){
try{
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
}catch (SQLException e){
e.printStackTrace();
}
return resultSet;
}
}
- 查询调用类
public class ZDao{
private ResultSet resultSet;
private DBhelper DBhelper;
private String sql = "select aa, bb, cc, dd from abcd";
public ZDao(){
DBhelper = new DBhelper();
resultSet = DBhelper.executeQuery(sql);
}
public void close(){
DBhelper.close();
}
public ResultSet getResultSet(){
return resultSet;
}
}
- 测试类
public class Test{
public static void main(String args[]){
//简单测试一下就用数组接收了,更好的选择是用List或者实体类接收
String[][] abcdTest = new String[1000][4];
ZDao ZDao = new ZDao();
ResultSet rs = ZDao.getResultSet();
int i = 0;
try{
while(rs.next()){
abcdTest[i][0] = rs.getString("aa");
abcdTest[i][1] = rs.getString("bb");
abcdTest[i][2] = rs.getString("cc");
abcdTest[i++][3] = rs.getString("dd");
}
}catch (SQLException e){
e.printStackTrace();
}
ZDao.close();
//随便打印几个看看成功没
System.out.println(abcdTest[4][0]+'\t'+abcdTest[4][1]+'\t'+abcdTest[4][2]+'\t'+abcdTest[4][3]);
}
}
需要导的包没写进去,eclipse自动导一下就好^_^