老规矩,话不都说,上代码:
package com.meboth.hive.connection.hbase.utils;
import java.sql.*;
import java.util.*;
import java.io.*;
public class JdbcUtil {
public static final String DBDRIVER = "com.mysql.jdbc.Driver";
public static final String DBURL = "jdbc:mysql://localhost:3306/my_test";
public static final String DBUSER = "root";
public static final String DBPASS = "";
private Connection con = null;
private PreparedStatement ps = null;
private ResultSet rs = null;
/**
* 初始化连接
*/
public void initConnection() {
try {
Class.forName(DBDRIVER);
con = DriverManager.getConnection(DBURL, DBUSER, DBPASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 查询数据
* @param sql
* @param obj
* @return
*/
public ResultSet queryData(String sql, Object[] obj) {
String str = "";
try {
if(con==null){
initConnection();
}
ps = con.prepareStatement(sql);
for (int i = 0; i < obj.length; i++) {
ps.setObject(i + 1, obj[i]);
}
rs = ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
/**
*添加,修改和删除
* @param sql
* @param obj
* @return
*/
public int updateAndDeleteData(String sql, Object[] obj) {
int i = 0;
try {
if(con==null){
initConnection();
}
ps = con.prepareStatement(sql);
for (int j = 0; j < obj.length; j++) {
ps.setObject(j + 1, obj[j]);
}
i = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
closePs();
}
return i;
}
/**
* 关闭ps连接
*/
public void closePs(){
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 关闭rs连接
*/
public void closeRs(){
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 关闭所有连接
*/
public void closeConnction() {
try {
if (ps != null) {
ps.close();
}
if (rs != null) {
rs.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
JdbcUtil tj = new JdbcUtil();
/**
String sql = "insert into company values(?,?,?)";
Object[] obj = {3, "baidu", "liyanhong"};
int i = tj.updateAndDeleteData(sql, obj);
System.out.println(i);
**/
String sql = "select * from company ";
Object[] obj = {};
ResultSet rs = tj.queryData(sql, obj);
try {
while (rs.next()) {
int id = rs.getInt(1);
String str = rs.getString(2);
String st = rs.getString(3);
System.out.println(id+"=="+str+"=="+st);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
tj.closeConnction();
}
}
}
查询显示效果:
1==阿里巴巴==马云
2==淘宝==马云,孙正义
3==baidu==liyanhong