自己写的一个SqlHelper,感觉使用起来挺方便的

using System;
using System.Data;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using System.IO;
using System.Data.SqlClient;
namespace NdfDeviceNetC
{
public class SqlHelper
{
//数据库连接字符串
private readonly static string connstr = @"Data Source=127.0.0.1;Initial Catalog=DB;Persist Security Info=True;User ID=sa;Password=123456"; private static List<bool> IsBusy = new List<bool>();
private static List<SqlConnection> connList = new List<SqlConnection>();//链接列表,解决打开链接消耗时间问题
static SqlHelper()
{
//打开10个链接
for (int i = ; i < ; i++)
{
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
connList.Add(conn);
IsBusy.Add(false);
}
}
/// <summary>
/// 获得一个可用的链接
/// </summary>
/// <returns></returns>
private static SqlConnection GetConnection()
{
int index = IsBusy.IndexOf(false);
if (index == -)
{
return null;
}
IsBusy[index] = true;
SqlConnection conn = connList[index];
if (conn.State==ConnectionState.Closed)
{
//如果链接已经关闭,重新打开
conn.Open();
}
return connList[index];
} /// <summary>
/// 释放链接
/// </summary>
/// <param name="conn"></param>
private static void FreeConnect(SqlConnection conn)
{
int index = connList.IndexOf(conn);
ConnectionState state = conn.State;
IsBusy[index] = false;
}
#region 组织select命令
public static string CmdForSelectTable(string tableName, string selctColumns, string whereStr)
{
string cmdstr = string.Format("SELECT {1} FROM [{0}] WHERE {2}", tableName, selctColumns, whereStr);
return cmdstr;
}
public static string CmdForSelectTable(string tableName, string selctColumns, string whereStr, int top)
{
string cmdstr = string.Format("SELECT TOP {3} {1} FROM [{0}] WHERE {2}", tableName, selctColumns, whereStr, top);
return cmdstr;
}
public static string CmdForSelectTable(string tableName, string selctColumns, string whereStr, string orderby)
{
string cmdstr = string.Format("SELECT {1} FROM [{0}] WHERE {2} ORDER BY {3}", tableName, selctColumns, whereStr, orderby);
return cmdstr;
}
public static string CmdForSelectTable(string tableName, string selctColumns, string whereStr, int top,string orderby)
{
string topStr = "";
string orderbyStr = "";
if (top > )
{
topStr = "TOP " + top;
}
if (!string.IsNullOrEmpty(orderby))
{
orderbyStr = " ORDER BY " + orderby;
}
string cmdstr = string.Format("SELECT {3} {1} FROM [{0}] WHERE {2}{4}", tableName, selctColumns, whereStr, topStr, orderbyStr);
return cmdstr;
}
public static string CmdForSelectMulitTable(List<string> tableNameList, string selctColumns, string whereStr,int top ,string orderby)
{
string topStr = "";
string orderbyStr = "";
string tableName = "";
foreach (string name in tableNameList)
{
tableName += name+" ";
}
if (top>)
{
topStr = "TOP " + top;
}
if (!string.IsNullOrEmpty(orderby))
{
orderbyStr = " ORDER BY "+orderby;
}
string cmdstr = string.Format("SELECT {3} {1} FROM {0} WHERE {2}{4}", tableName, selctColumns, whereStr, topStr, orderbyStr);
return cmdstr;
}
#endregion
#region 组织插入和更新命令
private static string CmdForInsertTable(string tableName, List<string> valueList)
{
string columns = "";
string values = "";
foreach (string item in valueList)
{
int index = item.IndexOf('=');
columns += item.Substring(, index) + ",";
values += item.Substring(index+) + ",";
}
columns = columns.Trim(',');
values = values.Trim(',');
string sqlstr = string.Format("INSERT INTO [{0}] ({1}) VALUES ({2});select @@IDENTITY", tableName, columns, values);
return sqlstr;
}
private static string CmdForUpdateTable(string tableName, List<string> valueList, string whereStr)
{
string setStr = "";
foreach (string item in valueList)
{
setStr += item + ",";
}
setStr = setStr.Trim(',');
string sqlstr = string.Format("UPDATE [{0}] SET {1} where {2}", tableName, setStr, whereStr);
return sqlstr;
}
#endregion #region 查询 /// <summary>
/// 获得表结构
/// </summary>
/// <param name="tableName"></param>
/// <returns></returns>
public static DataTable GetTableClone(string tableName)
{
string cmdStr = "SELECT TOP 0 * FROM [" + tableName+"]";
SqlConnection conn = GetConnection();//公用
SqlCommand cmd = new SqlCommand(cmdStr, conn);
DataTable table = null;
try
{
SqlDataAdapter ad = new SqlDataAdapter(cmdStr, conn);
table = new DataTable();
ad.Fill(table);
}
catch
{
throw;
}
finally
{
FreeConnect(conn);
} return table;
}
/// <summary>
/// 根据命令,执行后返回表格
/// </summary>
/// <param name="cmdStr"></param>
/// <returns></returns>
public static DataTable GetTable(string cmdStr)
{
SqlConnection conn = GetConnection();//公用
SqlCommand cmd = new SqlCommand(cmdStr, conn);
DataTable table = null;
try
{
SqlDataAdapter ad = new SqlDataAdapter(cmdStr, conn);
table = new DataTable();
ad.Fill(table);
}
catch
{
throw;
}
finally
{
FreeConnect(conn);
}
return table; }
/// <summary>
/// 查询数据
/// </summary>
/// <param name="tableName"></param>
/// <param name="selctColumns"></param>
/// <param name="whereStr"></param>
/// <returns></returns>
public static DataTable GetTable(string tableName, string selctColumns, string whereStr)
{
string cmdStr = string.Format("SELECT {1} FROM [{0}]", tableName, selctColumns);
if (!string.IsNullOrEmpty(whereStr))
{
cmdStr += " WHERE " + whereStr;
} SqlConnection conn = GetConnection();//公用
SqlCommand cmd = new SqlCommand(cmdStr, conn);
DataTable table = null;
try
{
SqlDataAdapter ad = new SqlDataAdapter(cmdStr, conn);
table = new DataTable();
ad.Fill(table);
}
catch
{
throw;
}
finally
{
FreeConnect(conn);
}
return table;
}
/// <summary>
/// 根据命令,执行后返回一个值
/// </summary>
/// <param name="cmdStr"></param>
/// <returns></returns>
public string GetValue(string cmdStr)
{
return null;
} #endregion /// <summary>
/// 添加一行数据
/// </summary>
public static int Add(string tableName, List<string> valueList)
{
string cmdStr = CmdForInsertTable(tableName,valueList);
SqlConnection conn = GetConnection();//公用
SqlCommand cmd = new SqlCommand(cmdStr, conn);
int rowId = ;
try
{
object o = cmd.ExecuteScalar();
rowId = int.Parse(o.ToString());
}
catch
{
throw;
}
finally
{
FreeConnect(conn);
}
return rowId;
}
/// <summary>
/// 批量添加数据
/// </summary>
public static void AddTable(string tableName,DataTable table)
{ SqlConnection conn = GetConnection();//公用
SqlBulkCopy bulk = new SqlBulkCopy(conn);
bulk.DestinationTableName = tableName;
try
{
bulk.WriteToServer(table);
}
catch
{
throw;
}
finally
{
FreeConnect(conn);
}
}
/// <summary>
/// 更新数据
/// </summary>
public static bool Update(string tableName, List<string> valueList, string whereStr)
{
string cmdStr = CmdForUpdateTable(tableName, valueList, whereStr);
SqlConnection conn = GetConnection();//公用
SqlCommand cmd = new SqlCommand(cmdStr, conn);
bool ok = false;
try
{
cmd.ExecuteNonQuery();
ok = true;
}
catch
{
throw;
}
finally
{
FreeConnect(conn);
}
return ok;
}
/// <summary>
/// 删除数据
/// </summary>
public static bool Remove(string tableName, string whereStr)
{
string cmdStr = string.Format("DELETE FROM [{0}] WHERE ({1})", tableName, whereStr);
SqlConnection conn = GetConnection();//公用
SqlCommand cmd = new SqlCommand(cmdStr, conn);
bool ok = true;
try
{
cmd.ExecuteNonQuery();
ok = true;
}
catch
{
throw;
}
finally
{
FreeConnect(conn);
}
return ok;
}
/// <summary>
/// 转化表格中一行数据
/// </summary>
public static Dictionary<string, object> ConventRowToModel(DataTable dt,int rowIndex)
{
if (dt.Rows.Count==)
{
return null;
}
DataRow dr = dt.Rows[rowIndex];
Dictionary<string, object> list = new Dictionary<string, object>();
for (int i = ; i < dt.Columns.Count; i++)
{
string key = dt.Columns[i].ColumnName;
object value = dr[i];
list.Add(key, value);
}
return list;
}
}
}

查询数据

        /// <summary>
/// 获得所有公司
/// </summary>
public static DataTable GetCompanyListAll()
{
//表Company
//列 Id,Name,FullName,Adress,Lng,Lat
string whereStr = "";
string Columns = "[Id],[Name],[FullName],[Adress],[Lng],[Lat]";
DataTable dt = SqlHelper.GetTable(CompanyTable1, Columns, whereStr); return dt;
}
/// <summary>
/// 获取公司信息
/// </summary>
public static Dictionary<string, object> GetCompanyInfo(int companyId)
{
//表CompanyTable
//列Id,Name,FullName,Adress,Lng,Lat
string Columns = "[Id],[Name],[FullName],[Adress],[Lng],[Lat]";
string WhereStr = "Id=" + companyId + "";
DataTable dt = new DataTable();
dt = SqlHelper.GetTable(CompanyTable1, Columns, WhereStr);
Dictionary<string, object> DtnList = SqlHelper.ConventRowToModel(dt, ); return DtnList;
}

插入数据

        /// <summary>
/// 新增加一个公司
/// </summary>
public static int AddCompany()
{
List<string> valueList = new List<string>();
valueList.Add("Name='新添加公司'");
valueList.Add("FullName='新添加公司'");
int Id = SqlHelper.Add(CompanyTable1, valueList);
return Id;
}

更新数据

        /// <summary>
/// 更新公司信息
/// </summary>
public static void UpdateCompany(Dictionary<string, string> companyInfo)
{
//表CompanyTable
//Name='"+companyInfo["Name"]+"'
//FullName=**FullName**
//Adress=**CompanyTable**
//Lng=**Lng**
//Lat=**Lat**
//whereStr Id=**CompanyId**
List<string> valueList = new List<string>();
valueList.Add("Name='" + companyInfo["Name"] + "'");
valueList.Add("FullName='" + companyInfo["FullName"] + "'");
valueList.Add("Adress='" + companyInfo["Adress"] + "'");
valueList.Add("Lng='" + companyInfo["Lng"] + "'");
valueList.Add("Lat='" + companyInfo["Lat"] + "'");
string whereStr = "Id=" + companyInfo["CompanyId"] + "";
bool ok = SqlHelper.Update(CompanyTable1, valueList, whereStr); }

删除

       /// <summary>
/// 删除一个公司
/// </summary>
public static void RemoveCompany(int companyId)
{
//表CompanyTable
//whereStr Id=companyId
string whereStr = "Id=" + companyId + "";
bool ok = SqlHelper.Remove(CompanyTable1, whereStr);
}

多表联合查询

       /// <summary>
/// 获取设备信息
/// </summary>
public static Dictionary<string, object> GetDeviceInfo(int deviceId)
{
//表DeviceBaseInfo
//列 CompanyId,DepartmentId,ProductType,ProductModel,Name,LoadWeight
//表Company
//列 FullName
//表Department
//列 Name
//表DeviceState
//列 Lng,Lat List<string> tableNameList = new List<string>();
tableNameList.Add("DeviceBaseInfo");
tableNameList.Add("LEFT JOIN DeviceState ON DeviceBaseInfo.Id=DeviceState.DeviceId");
tableNameList.Add("LEFT JOIN Company ON DeviceBaseInfo.CompanyId=Company.Id");
tableNameList.Add("LEFT JOIN Department ON DeviceBaseInfo.DepartmentId=Department.Id");
string selctColumns = "DeviceBaseInfo.Id,DeviceBaseInfo.CompanyId,DeviceBaseInfo.DepartmentId,Company.FullName AS CompanyName,Department.Name AS DepartmentName,ProductType,ProductModel,DeviceBaseInfo.Name,LoadWeight,DeviceState.Lng,DeviceState.Lat";
string whereStr = "DeviceBaseInfo.Id=" + deviceId;
string cmdStr = SqlHelper.CmdForSelectMulitTable(tableNameList, selctColumns, whereStr, , "DeviceBaseInfo.Id"); DataTable dt = SqlHelper.GetTable(cmdStr); Dictionary<string, object> data = SqlHelper.ConventRowToModel(dt, );
return data;
}

自己写的一个SqlHelper,感觉使用起来挺方便的的更多相关文章

  1. 用Python写了一个postgresql函数,感觉很爽

    用Python写了一个postgresql函数,感觉很爽 CREATE LANGUAGE plpythonu; postgresql函数 CREATE OR REPLACE FUNCTION myfu ...

  2. 用c#写的一个局域网聊天客户端 类似小飞鸽

    用c#写的一个局域网聊天客户端 类似小飞鸽 摘自: http://www.cnblogs.com/yyl8781697/archive/2012/12/07/csharp-socket-udp.htm ...

  3. 自己写的一个关于Linq to Entity 动态查询的例子

    这两天一直想写一个动态查询的方式,先是晚上查询了一下,发现大家写的差不多都是一样的[如:http://www.cnblogs.com/ASPNET2008/archive/2012/10/28/274 ...

  4. CI(codeigniter)框架,routes.php设置正确,但是显示服务器错误,是__construct少写了一个下划线

    今天弄了一下CI框架,大概看了一下文档,感觉CI框架非常精简,但是在做的时候遇到了问题,CI文档中提供了一个新闻系统的例子,所有工作都做完了,在浏览器中打开相对应的url是,却显示“服务器错误”,一点 ...

  5. 师兄写的一个JAVA播放器的源代码(转)

    师兄写的一个JAVA播放器的源代码 MediaPlayer.java------------------------------------------------------------------ ...

  6. React自己写的一个地图小组件

    由于今天比较闲,就玩了玩react,然后就封装了一个地图的组件,当然功能比较简单,因为就是随手写的小东西,但是由于引用了百度API和bee-mobile,所以用起来可能要薛微麻烦一点点,但是我保证,只 ...

  7. 试着用c写了一个多线程的同步

    在Java中写多线程相关的程序简单很多,在多线程中需要同步的时候,使用synchronized就行了. 最近学习c的多线程与同步,感觉实现起来,要写的代码比较多一些,这也许是因为java封装的比较好吧 ...

  8. 这两天自己模仿写的一个Asp.Net的显示分页方法 附加实体转换和存储过程

    之前自己一直用Aspnetpager控件来显示项目中的分页,但是每次都要拖一个aspnetpager的控件进去,感觉很不舒服,因为现在自己写的webform都不用服务器控件了,所以自己仿照aspnet ...

  9. 用canvas和原生js写的一个笨鸟先飞的小游戏(暂时只有一个关卡)

    其中一个画布背景是一张图片,还有小鸟,两个管子的图片.暂时不知道怎么附上去就不添加了.这里只有源代码,css和js都是在html写着的,感觉比他们的容易吧,hah <!DOCTYPE html& ...

随机推荐

  1. u-boot移植 II

    下面是韦老师的uboot移植攻略: A. 开发板的相关拷贝与修改 1. 在board文件夹下面, 将原来的smdk2410复制为100ask24x0目录, 并将smdk2410.c改名为100ask2 ...

  2. Vmware10如何打开vmware11建立的虚拟机

    先说一下办法: 使用文本工具打开VMware 虚拟机配置文件(*.vmx文件),找到"virtualHW.version"一行,将值11修改为10保存即可. 修改之前: 硬件兼容性 ...

  3. 使用netty4.x客户端接收较大数据量报文时发生的读取不完整bug修复记录

    1.先说问题 背景:服务是运行在Linux上的安全网关提供的,TCP协议发送 通过二进制编码的xml字符串 报文,报文头的第一个字段是int类型的表示字节序标记,第二个字段是int类型的表示整个报文长 ...

  4. ==与equals 的使用比较

    1. == 是一个运算符. 2.Equals则是string对象的方法 我们通常是两种类型的比较 1.基本数据类型比较 2.引用对象比较 其中 1.基本数据类型比较 ==和Equals都比较两个值是否 ...

  5. ubuntu 设置 默认的JDK路径

    首先查询有多少种JDK已经被安装了 sudo update-alternatives --list java 其次 配置你想默认的JDK sudo update-alternatives --conf ...

  6. java获取两个时间的相隔时间,包括年、月、日、时、分、秒

    public static final int YEAR_RETURN = 0;                    public static final int MONTH_RETURN = 1 ...

  7. Nginx与Lua利用fpm打成rpm包

    1.下载相关软件 需要软件有:Nginx,LuaJIT,ngx_devel_kit,ngx_lua等安装文件 安装Lua或者LuaJIT都是可以的,但是出于效率的考虑,推荐安装LuaJITshell& ...

  8. python-进程,线程,协程

    1.进程和线程  进程定义:进程是正在运行的程序的实例,进程是内核分配资源的最基本的单元,而线程是内核执行的最基本单元,进程内可以包含多个线程,只要记住这三个要点,就可以很清楚的理清进程和线程的行为模 ...

  9. Excel 数据关联

    =INDEX(Sheet2!$A$2:$A$77,MATCH(A4,Sheet2!$C$2:$C$77,0))

  10. 【前端】event.target 和 event.currentTarget 的区别

    event.target 和 event.currentTarget 的区别 举例说明: <!DOCTYPE html> <html> <head> <tit ...