您的位置:首页 > 编程语言 > Java开发

教你如何使用java语言编写一个简单的SqlHelper类

2014-08-01 23:35 513 查看
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
* 数据库工具类 链接mySQL数据库
*
* @author Administrator
*
*/
public class SqlHelper {
// 链接需要的数据 (这些数据直接写到加密后的数据文件中)
private static String url = "jdbc:mysql://127.0.0.1:3306/msitdb";
private static String user = "root";
private static String password = "root";
private static String driverName = "com.mysql.jdbc.Driver";
// 声明静态链接对象
private static Connection connection = null;

// 编写静态代码块(比构造函数先加载) 用来加载驱动类
static {
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}// end
// 获得链接对象

public static Connection getConnection() {
// 创建链接对象
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}

/**
* 执行 添加 删除 修改的sql语句方法
*
* @param sql
* @return 受影响行数
*/
public static int executeNotQuery(String sql) {
int num = 0;
// 1.得到链接对象
Connection conn = getConnection();
// 2.创建命令执行对象
Statement stm = null;
try {
stm = conn.createStatement();
// 3.执行sql脚本 得到返回值
num = stm.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(null, stm, conn);
}
return num;
}

/**
* 关闭资源的方法
*
* @param rs
*            结果集
* @param stm
*            执行对象
* @param conn
*            链接对象
*/
private static void close(ResultSet rs, Statement stm, Connection conn) {
if (null != rs) {
try {
rs.close();
} catch (SQLException e) {
System.out.println("关闭结果集异常");
e.printStackTrace();
}
}
if (null != stm) {
try {
stm.close();
} catch (SQLException e) {
System.out.println("关闭执行对象异常");
e.printStackTrace();
}
}
if (null != conn) {
try {
conn.close();
} catch (SQLException e) {
System.out.println("关闭链接对象异常");
e.printStackTrace();
}
}
rs = null;
stm = null;
conn = null;
}// end

/**
* 执行查询语句的方法
*
* @param sql
* @return 返回结果集
*/
public static ResultSet executeQuery(String sql) {
ResultSet rs = null;
// 1.得到链接对象
Connection conn = getConnection();
// 2.创建命令对象
Statement stm =null;
try {
// 2.创建命令对象
stm = conn.createStatement();
// 3.执行查询方法 得到结果集
rs = stm.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 关闭资源
}
return rs;
}

/**
* 执行预编译sql的方法
* @param sql
* @param pams
* @return
*/
public static int executPreStm(String sql,String[] pams){
int num=0;
PreparedStatement pstm=null;
try {
//创建预编译对象
pstm=getConnection().prepareStatement(sql);
//添充占位符的数据
for (int i = 1; i <= pams.length; i++) {
pstm.setString(i, pams[i-1]);
}
//执行sql
num = pstm.executeUpdate();//只能执行非查询语句
//关闭资源
pstm.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return num;
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐