java sql 工具类_一个Java Web实用工具类SqlHelper | 学步园

import java.io.InputStream;

import java.sql.*;

import java.util.*;

public class SqlHelper {

//定义需要的变量

private static Connection ct=null; (访问的人比较少的话可以用static,如果并发性比较强不能用static)

//大多数情况下,我们使用的是PreparedStatement来替代Statement可以防止sql注入

private static PreparedStatement ps=null;

private static ResultSet rs=null;

private static CallableStatement cs=null;

//连接数据库的参数

private static String url="";

private static String username="";

private static String driver="";

private static String password="";

//读配置文件

private static Properties pp=null;

private static InputStream fis=null;

//加载驱动,只需要一次

static{

try{

//从dbinfo.properties文件中读取配置信息

pp=new Properties();

//当我们使用java web的时候,读取文件要使用类加载器[因为类加载器去读取资源的时候,默认的主目录是src目录

fis=SqlHelper.class.getClassLoader().getResourceAsStream("dbinfo.properties");

pp.load(fis);

url=pp.getProperty("url");

username=pp.getProperty("username");

driver=pp.getProperty("driver");

password=pp.getProperty("password");

Class.forName(driver);

}catch(Exception e){

e.printStackTrace();

}finally{

try{

fis.close();

}catch(Exception e){

e.printStackTrace();

}

fis=null; //垃圾回收站上收拾

}

}

//得到连接

public static Connection getConnection(){

try{

ct=DriverManager.getConnection(url,username,password);

}catch(Exception e){

e.printStackTrace();

}

return ct;

}

//调用存储过程,又返回Result

//sql call过程(???)

public static CallableStatement callPro2(String sql,String[] inparameters,Integer[] outparameters){

try{

ct=getConnection();

cs=ct.prepareCall(sql);

if(inparameters!=null){

for(int i=0;i

cs.setObject(i+1, inparameters[i]);

}

}

//给out参数赋值

if(outparameters!=null){

for(int i=0;i

cs.registerOutParameter(inparameters.length+1+i,outparameters[i] );

}

}

cs.execute();

}catch(Exception e){

e.printStackTrace();

}finally{

}

return cs;

}

//调用存储过程

//sql象{sql过程(???)}

public static void callProl(String sql,String[] parameters){

try{

ct=getConnection();

cs=ct.prepareCall(sql);

if(parameters!=null){

for(int i=0;i

cs.setObject(i+1, parameters[i]);

}

}

cs.execute();

}catch(Exception e){

e.printStackTrace();

}finally{

close(rs,cs,ct);

}

}

//统一的select

//ResultSet->Arraylist

public static ResultSet executeQuery(String sql,String[] parameters){

try{

ct=getConnection();

ps=ct.prepareStatement(sql);

if(parameters!=null&&!parameters.equals("")){

for(int i=0;i

ps.setString(i+1, parameters[i]);

}

}

rs=ps.executeQuery();

}catch(Exception e){

e.printStackTrace();

}

finally{

//close(rs,ps,ct);

}

return rs;

}

//如果有多个update/delete/insert[需要考虑事务]

public static void executeUpdate2(String sql[],String[][] parameters){

try{

//核心

//1.获得连接

ct=getConnection();

//因为这时,用户传入的可能是多个Sql语句

ct.setAutoCommit(false);

for(int i=0;i

if(parameters[i]!=null){

ps=ct.prepareStatement(sql[i]);

for(int j=0;j

ps.setString(j+1, parameters[i][j]);

}

ps.executeUpdate();

}

}

ct.commit();

}catch(Exception e){

e.printStackTrace();

//回滚

try{

ct.rollback();

}catch(Exception e1){

e1.printStackTrace();

}

throw new RuntimeException(e.getMessage());

}

finally{

close(rs,ps,ct);

}

}

//先写一个update/delete/insert

//sql格式: update 表明 set 字段名=? where 字段=?

public static void executeUpdate(String sql,String[] parameters){

//1.创建一个ps

try{

ct=getConnection();

ps=ct.prepareStatement(sql);

//给?赋值

if(parameters!=null){

for(int i=0;i

ps.setString(i+1, parameters[i]);

}

}

//执行

ps.executeUpdate();

}catch(Exception e){

e.printStackTrace();//开发阶段

//抛出异常,抛出运行异常,可以给调用该函数的函数一个选择

//可以处理,也可以放弃处理

throw new RuntimeException(e.getMessage());

}finally{

//关闭资源

close(rs,ps,ct);

}

}

//关闭资源的函数

public static void close(ResultSet rs,Statement ps,Connection ct){

if(rs!=null){

try{

rs.close();

}catch(Exception e){

e.printStackTrace();

}

rs=null;

}

if(ps!=null){

try{

ps.close();

}catch(Exception e){

e.printStackTrace();

}

ps=null;

}

if(ct!=null){

try{

ct.close();

}catch(Exception e){

e.printStackTrace();

}

ct=null;

}

}

public static Connection getct(){

return ct;

}

public static PreparedStatement getPs(){

return ps;

}

public static ResultSet getRs(){

return rs;

}

public static CallableStatement getCs(){

return cs;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils; /** * SQLUtils utils = new SQLUtils(User.class); utils.setWhereStr("", "id", "=", 100).setWhereStr("and", "name", " ", "is null").setWhereStr("and", "date", ">=", new Date()); utils.setOrderByStr("id", "desc").setOrderByStr("name", "asc"); System.out.println(utils.buildSelectSQL()); System.out.println(utils.buildCountSQL()); */ import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class SqlUtils { private String beanName; private String beanShortName; private Map propertyMap; private List conditionList; private List relationList; private Map orderByMap; public SqlUtils(Class instance) { this.setBeanName(instance.getSimpleName()); this.setBeanShortName(Character.toLowerCase(this.getBeanName() .charAt(0)) + ""); init(); } public SqlUtils() { init(); } void init(){ propertyMap = new LinkedHashMap(); conditionList = new LinkedList(); relationList = new LinkedList(); orderByMap = new LinkedHashMap(); } /** * 添加查询条件 * * @param relation * 关联 "and","or"等 * @param property * 查询的对象属性 * @param condition * 查询的条件,关系符 * @param value * 查询的值 */ public SqlUtils setWhereStr(String relation, String property, String condition, Object value) { if(value != null){ relationList.add(relation); propertyMap.put(property, value); conditionList.add(condition); } return this; } private String buildWhereStr() { StringBuffer buffer = new StringBuffer(); if (!propertyMap.isEmpty() && propertyMap.size() > 0) { buffer.append("WHERE 1 = 1 "); int index = 0; for (String property : propertyMap.keySet()) { if (property != null && !property.equals("")) { buffer.append(r
以下是一个简单的 C# 工具类,用于连接 SQL Server 数据库: ```csharp using System; using System.Data.SqlClient; public class SqlHelper { // 连接字符串 private string connectionString; // 构造函数 public SqlHelper(string connectionString) { this.connectionString = connectionString; } // 执行 SQL 命令,返回受影响的行数 public int ExecuteNonQuery(string sql) { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (SqlCommand command = new SqlCommand(sql, connection)) { return command.ExecuteNonQuery(); } } } // 执行 SQL 查询,返回 SqlDataReader 对象 public SqlDataReader ExecuteReader(string sql) { SqlConnection connection = new SqlConnection(connectionString); connection.Open(); SqlCommand command = new SqlCommand(sql, connection); SqlDataReader reader = command.ExecuteReader(System.Data.CommandBehavior.CloseConnection); return reader; } // 执行 SQL 查询,返回单个结果 public object ExecuteScalar(string sql) { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (SqlCommand command = new SqlCommand(sql, connection)) { return command.ExecuteScalar(); } } } } ``` 使用示例: ```csharp // 连接字符串 string connectionString = "Server=(local);Database=MyDatabase;User ID=MyUsername;Password=MyPassword;"; // 创建 SqlHelper 对象 SqlHelper sqlHelper = new SqlHelper(connectionString); // 执行 SQL 命令 sqlHelper.ExecuteNonQuery("INSERT INTO MyTable (Column1, Column2) VALUES ('Value1', 'Value2')"); // 执行 SQL 查询 SqlDataReader reader = sqlHelper.ExecuteReader("SELECT * FROM MyTable"); while (reader.Read()) { // 读取数据 string column1 = reader.GetString(0); string column2 = reader.GetString(1); } // 执行 SQL 查询,返回单个结果 object result = sqlHelper.ExecuteScalar("SELECT COUNT(*) FROM MyTable"); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值