using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration; public class SqlHelper
{
public static readonly string conString = ConfigurationManager.ConnectionStrings["sqlCon"].ConnectionString;
//增删改
public static bool ExeNonQuery(string sql, CommandType type, params SqlParameter[] lists)
{
bool bFlag = false;
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = sql;
cmd.CommandType = type;
if (lists != null)
{
foreach (SqlParameter p in lists)
{
cmd.Parameters.Add(p);
}
}
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
int result = cmd.ExecuteNonQuery();
if (result > )
{
bFlag = true;
} }
catch { ;}
}
return bFlag;
} //查.读
public static SqlDataReader ExeDataReader(string sql, CommandType type, params SqlParameter[] lists)
{
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = sql;
cmd.CommandType = type; if (con.State == ConnectionState.Closed)
{
con.Open();
} if (lists != null)
{
foreach (SqlParameter p in lists)
{
cmd.Parameters.Add(p);
}
} SqlDataReader reader = cmd.ExecuteReader(); return reader;
} //返回单个值
public static object GetScalar(string sql, CommandType type, params SqlParameter[] lists)
{
object returnValue = null;
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = sql;
cmd.CommandType = type;
if (lists != null)
{
foreach (SqlParameter p in lists)
{
cmd.Parameters.Add(p);
}
}
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
returnValue = cmd.ExecuteScalar(); }
catch { ; }
}
return returnValue;
} //事务
public static bool ExeNonQueryTran(List<SqlCommand> list)
{
bool flag = true;
SqlTransaction tran = null;
using (SqlConnection con = new SqlConnection(conString))
{
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
tran = con.BeginTransaction();
foreach (SqlCommand com in list)
{
com.Connection = con;
com.Transaction = tran;
com.ExecuteNonQuery();
}
tran.Commit();
}
}
catch (Exception ex)
{
Console.Write(ex.Message);
tran.Rollback();
flag = false;
}
}
return flag;
}
//返回DataTable
public static DataTable GetTable(string sql)
{
SqlConnection conn = new SqlConnection(conString);
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataTable table = new DataTable();
da.Fill(table);
return table;
}
/// <summary>
/// 调用带参数的存储过程,返回dataTable
/// </summary>
/// <param name="proc">存储过程的名称</param>
/// <param name="rows">一页几行</param>
/// <param name="page">当前页</param>
/// <param name="tabName">表名</param>
/// <returns>dataTable</returns>
public static DataTable Proc_Table(string proc, int rows, int page, string tabName)
{
SqlConnection conn = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(proc, conn);
//指定调用存储过程
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@rows", rows);
cmd.Parameters.Add("@page", page);
cmd.Parameters.Add("@tabName", tabName);
SqlDataAdapter apt = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
apt.Fill(dt);
return dt;
} //调用带参数的存储过程返回datatable
public static DataTable GetTablebyproc(string proc, int pageRow, int pagSize, string tabName)
{
SqlConnection conn = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(proc,conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@rows", pageRow);
cmd.Parameters.Add("@pagesize", pagSize);
cmd.Parameters.Add("@tablename", tabName);
SqlDataAdapter apt = new SqlDataAdapter(cmd);
DataTable table = new DataTable();
apt.Fill(table);
return table; }
public static DataTable GetDataByPager(string tbname, string fieldkey, int pagecurrent, int pagesize, string fieldshow, string fieldorder, string wherestring, ref int pagecount)
{
SqlParameter[] parameters = {
new SqlParameter("@tbname", SqlDbType.VarChar, ),
new SqlParameter("@FieldKey", SqlDbType.VarChar, ),
new SqlParameter("@PageCurrent", SqlDbType.Int),
new SqlParameter("@PageSize", SqlDbType.Int),
new SqlParameter("@FieldShow", SqlDbType.VarChar, ),
new SqlParameter("@FieldOrder", SqlDbType.VarChar, ),
new SqlParameter("@WhereString", SqlDbType.VarChar, ),
new SqlParameter("@RecordCount", SqlDbType.Int),
};
parameters[].Value = tbname;
parameters[].Value = fieldkey;
parameters[].Value = pagecurrent;
parameters[].Value = pagesize;
parameters[].Value = fieldshow;
parameters[].Value = fieldorder;
parameters[].Value = wherestring;
parameters[].Direction = ParameterDirection.Output;
DataTable dt = ExecuteQuery("sp_get_data", parameters).Tables[];
pagecount = Convert.ToInt32(parameters[].Value);
return dt;
}
/// <summary>
/// 执行有参数的查询类存储过程
/// </summary>
/// <param name="pstrStoreProcedure">存储过程名</param>
/// <param name="pParms">存储过程的参数数组</param>
/// <returns>查询得到的结果集</returns>
public static DataSet ExecuteQuery(string pstrStoreProcedure, SqlParameter[] pParms)
{ DataSet dsResult = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter();
SqlConnection con = new SqlConnection(conString);
SqlCommand cmd;
int intCounter;
try
{
if (con.State != ConnectionState.Open)
con.Open();
cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = pstrStoreProcedure;
if (pParms != null)
{
for (intCounter = ; intCounter < pParms.GetLength(); intCounter++)
{
cmd.Parameters.Add(pParms[intCounter]);
}
}
sda.SelectCommand = cmd;
sda.Fill(dsResult); }
catch (SqlException ex)
{
throw new Exception(ex.Message);
}
finally
{
//清空关闭操作
sda.Dispose();
con.Close();
con.Dispose(); }
return dsResult;
}
/// <summary>
/// 此分页存储过程直没修改 大家可以用自己的
/// </summary>
/// <param name="tableName">表名</param>
/// <param name="getFields">需要返回的列</param>
/// <param name="orderName">排序的字段名</param>
/// <param name="pageSize">页尺寸</param>
/// <param name="pageIndex">页码</param>
/// <param name="isGetCount">返回记录总数,非 0 值则返回</param>
/// <param name="orderType">设置排序类型,0表示升序非0降序</param>
/// <param name="strWhere"></param>
/// <returns></returns>
//public static DataSet GetList(string tableName, string getFields, string orderName, int pageSize, int pageIndex, bool isGetCount, bool orderType, string strWhere)
//{
// SqlParameter[] parameters = {
// new SqlParameter("@tblName", SqlDbType.VarChar, 255),
// new SqlParameter("@strGetFields", SqlDbType.VarChar, 1000),
// new SqlParameter("@fldName", SqlDbType.VarChar, 255),
// new SqlParameter("@PageSize", SqlDbType.Int),
// new SqlParameter("@PageIndex", SqlDbType.Int),
// new SqlParameter("@doCount", SqlDbType.Bit),
// new SqlParameter("@OrderType", SqlDbType.Bit),
// new SqlParameter("@strWhere", SqlDbType.VarChar, 1500)
// };
// parameters[0].Value = tableName;
// parameters[1].Value = getFields;
// parameters[2].Value = orderName;
// parameters[3].Value = pageSize;
// parameters[4].Value = pageIndex;
// parameters[5].Value = isGetCount ? 1 : 0;
// parameters[6].Value = orderType ? 1 : 0;
// parameters[7].Value = strWhere;
// return SqlHelper.RunProcedure("pro_pageList", parameters, "ds");
//}
//public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
//{
// using (SqlConnection connection = new SqlConnection(conString))
// {
// DataSet dataSet = new DataSet();
// connection.Open();
// new SqlDataAdapter { SelectCommand = BuildQueryCommand(connection, storedProcName, parameters) }.Fill(dataSet, tableName);
// connection.Close();
// return dataSet;
// }
//}
/// <summary>
/// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
/// </summary>
/// <param name="connection">数据库连接</param>
/// <param name="storedProcName">存储过程名</param>
/// <param name="parameters">存储过程参数</param>
/// <returns>SqlCommand</returns>
private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
{
SqlCommand command = new SqlCommand(storedProcName, connection)
{
CommandType = CommandType.StoredProcedure
};
foreach (SqlParameter parameter in parameters)
{
if (parameter != null)
{
if (((parameter.Direction == ParameterDirection.InputOutput) || (parameter.Direction == ParameterDirection.Input)) && (parameter.Value == null))
{
parameter.Value = DBNull.Value;
}
command.Parameters.Add(parameter);
}
}
return command;
}
//根据表名和主键id来进行删除
public static int DelData(string tabName, string ID)
{
if (ID != string.Empty && ID != "")
{
string sql = string.Format("delete from {0} WHERE (ID IN ({1}))", tabName, ID);
int delNum = ExecuteSql(sql);
return delNum;
}
return ;
}
//增删改返回执行条数
public static int ExecuteSql(string SQLString)
{
int num2;
using (SqlConnection connection = new SqlConnection(conString))
{
SqlCommand command = new SqlCommand(SQLString, connection);
try
{
connection.Open();
num2 = command.ExecuteNonQuery();
}
catch (SqlException exception)
{
connection.Close();
throw exception;
}
finally
{
if (command != null)
{
command.Dispose();
}
}
}
return num2;
}
}

.net 连接sqlserver类库的更多相关文章

  1. php以pdo方式连接sqlserver,无法开启sqlsrv扩展

    首先,PHP连接sqlserver代码如下: $host="aaaaa"; $dbname="aaaaa"; $user="aaaaa"; ...

  2. 用Window Authentication的方式去连接SQLServer

    用Window Authentication的方式去连接SQLServer Connection String: jdbc:sqlserver://${serverName};databaseName ...

  3. Android通过webservice连接SQLServer 详细教程(数据库+服务器+客户端)

    http://blog.csdn.net/zhyl8157121/article/details/8169172 目录(?)[-] 项目说明 开发环境的部署 数据库设计 服务器端程序设计Webserv ...

  4. ORACLE连接SQLSERVER

    一.实验(实验成功) 1.实验目标:ORACLE连接SQLSERVER以及查询数据 2.搭建的环境: oracle 9i 9.0.2.0.1 地址:192.168.40.139 sql2000 的数据 ...

  5. Jfinal连接SQLSERVER相关配置说明

    driver=net.sourceforge.jtds.jdbc.Driver jdbcUrl = jdbc:sqlserver://localhost:1433;DatabaseName=test ...

  6. jsp连接sqlServer数据库教程

    一.首先讲下我用的工具版本以供参考: jar包:jtds1.3.1.jar  下载地址:点击进入 数据库:SQL Server2012 服务器:Tomcat8.0   下载地址:点击进入 开发IDE工 ...

  7. navicat 连接sqlserver提示要安装 sql server native client

    navicat 连接sqlserver提示要安装 sql server native client 解决方法:其实navicat自带sqlncli_x64.msi,就在安装目录下,安装后问题解决!

  8. 使用thinkphp连接sqlserver数据库时提示“系统不支持:sqlsrv”

    习惯了使用php跟mysql组合,现在接到项目需要调用客户线下的系统软件的数据,具了解,这个软件的数据库是用sqlserver数据库也就是常说的mssql数据库了. 那么我现在需要用PHP连接sqls ...

  9. PHP:PHP5.4连接SQLSERVER

    在PHP5.4的环境下要连接SQLSERVER(2005/2008)数据库,需要以下步骤: 1.下载PHP5.4连接SQLSERVER的驱动(两个动态连接库)http://www.microsoft. ...

随机推荐

  1. http://www.cnblogs.com/xqin/p/4862849.html

    一.前言 半年前左右折腾了一个前后端分离的架子,这几天才想起来翻出来分享给大家.关于前后端分离这个话题大家也谈了很久了,希望我这个实践能对大家有点点帮助,演示和源码都贴在后面. 二.技术架构 这两年a ...

  2. js词法作用域规则

    function foo() {console.log( a ); // 2不是3} function bar() {var a = 3;foo();} var a = 2;bar(); js中的作用 ...

  3. 【转】在Eclipse中配置tomcat

    转载地址: http://kin111.blog.51cto.com/738881/163096 为了在Eclipse中进行struts2的测试,才发现自己机器上的Eclipse没有集成Tomcat, ...

  4. android FragmentPagerAdapter getItem方法没有执行

    转自 http://blog.csdn.net/getchance/article/details/40263505 在一个 Android 应用中,我使用 FragmentPagerAdapter  ...

  5. Android处理图片OOM的若干方法小结 (推荐)

    众所周知,每个Android应用程序在运行时都有一定的内存限制,限制大小一般为16MB或24MB(视平台而定).因此在开发应用时需要特别关注自身的内存使用量,而一般最耗内存量的资源,一般是图片.音频文 ...

  6. hihoCoder 数论五·欧拉函数

    题目1 : 数论五·欧拉函数 时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 小Hi和小Ho有时候会用密码写信来互相联系,他们用了一个很大的数当做密钥.小Hi和小Ho约定 ...

  7. SDUT 2877:angry_birds_again_and_again

    angry_birds_again_and_again Time Limit: 2000ms   Memory limit: 65536K  有疑问?点这里^_^ 题目描述 The problems ...

  8. 20151224001 GridView 多按钮的各种使用方法

    <asp:GridView ID="GridView1"                 runat="server" AllowPaging=" ...

  9. Humble Numbers

    Humble Numbers Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 9988 Accepted: 4665 Descri ...

  10. Linux多线程同步机制

    http://blog.163.com/he_junwei/blog/static/19793764620141711130253/ http://blog.csdn.net/h_armony/art ...