可作为以后开发的参考代码,也可以再整理下,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Configuration; using System.Windows.Forms; namespace test1
{
class DataBase
{
private static string connString;
private static SqlConnection Conn;
//获取连接数据库字符串
public static String GetConnString()
{
string connString = "chaiqianD2.Properties.Settings.testConnectionString";
String s = ConfigurationManager.ConnectionStrings[connString].ConnectionString;
return s;
} /**////<summary>
///创建connnection并打开
/// </summary>
public static void Open()
{
GetConnString();
connString = GetConnString();
Conn = new SqlConnection();
Conn.ConnectionString = connString;
try
{
Conn.Open();
}
catch (SqlException ee)
{
MessageBox.Show(ee.Message.ToString() + ee.ToString());
}
} /**////<summary>
///获取connnection
/// </summary>
public static SqlConnection getConnection()
{
Open();
return Conn;
} //执行查询,返回受影响的行数
public static int ExecuteSQL(string cmdString)
{
Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = cmdString;
cmd.Connection = Conn;
cmd.CommandType = System.Data.CommandType.Text;
//返回数据库操作影响的行数
int nAffected = -;
try
{
nAffected = cmd.ExecuteNonQuery();
}
catch (SqlException sqlEx)
{
MessageBox.Show(sqlEx.Message.ToString());
throw sqlEx;
}
finally
{
Conn.Close();
}
return nAffected;
} //返回第一行第一列的数据
public static int ExecuteScalar(string cmdString)
{
Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = cmdString;
cmd.Connection = Conn;
cmd.CommandType = System.Data.CommandType.Text;
//返回数据库操作影响的行数
int count = ;
try
{
count = Int32.Parse(cmd.ExecuteScalar().ToString().Trim());
}
catch (SqlException ee)
{
Conn.Close();
MessageBox.Show(ee.Message.ToString());
count = -; }
finally
{
Conn.Close();
}
return count;
} //关闭连接
public static void Close()
{
if (Conn.State == ConnectionState.Open)
Conn.Close();
} //根据查询语句和在数据集中表的名字,返回DataSet
public static DataSet GetDataSet(String cmdString, String strTableName)
{
Open();
SqlCommand cmd = new SqlCommand(cmdString, Conn);
SqlDataAdapter myAd = new SqlDataAdapter();
myAd.SelectCommand = new SqlCommand(cmdString, Conn); DataSet myDs = new DataSet();
//填充数据
try
{
myAd.Fill(myDs, strTableName);
return myDs;
}
catch (SqlException sqlEx)
{ MessageBox.Show(sqlEx.Message.ToString());
throw sqlEx;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
throw ex;
}
finally
{
Close();
} } //返回datareader
public static SqlDataReader GetDataReader(string CmdStr)
{
Open();
SqlCommand myCmd = new SqlCommand();
myCmd.Connection = Conn;
myCmd.CommandType = CommandType.Text;
myCmd.CommandText = CmdStr;
SqlDataReader myDr = null;
try
{
//数据读取器关闭时,连接对象自动关闭
myDr = myCmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (SqlException sqlEx)
{
Close();
if (myDr != null)
myDr.Close();
throw sqlEx;
}
return myDr;
} //执行存储过程的函数
public static int ExecuteStoredProcedure(string StoredProcedureStr, SqlParameter[] parameters)
{
Open(); using (SqlCommand cmd = new SqlCommand(StoredProcedureStr, Conn))
{
try
{
if (Conn.State != ConnectionState.Open)
{
Conn.Open();
}
foreach (SqlParameter parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
cmd.CommandType = CommandType.StoredProcedure;
int rows = cmd.ExecuteNonQuery();
Close();
return rows;
}
catch (SqlException E)
{
MessageBox.Show(E.Message.ToString());
throw E;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
return -; }
finally
{
Close();
} } } //
public static int ExecuteNonQuery(string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
PrepareCommand(cmd, cmdText, commandParameters);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
} //
private static void PrepareCommand(SqlCommand cmd, string cmdText, SqlParameter[] cmdParms)
{
Open();
cmd.Connection = Conn;
cmd.CommandText = cmdText;
cmd.CommandType = CommandType.Text; if (cmdParms != null)
{
foreach (SqlParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
} public static SqlDataReader ExecuteReader(string cmdText, params SqlParameter[] commandParameters)
{
SqlCommand cmd = new SqlCommand();
try
{
PrepareCommand(cmd, cmdText, commandParameters);
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return rdr;
}
catch (SqlException ee)
{
Close();
MessageBox.Show(ee.Message.ToString());
return null;
}
} /**//// <summary>
/// 执行存储过程,返回DataSet对象
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string StoredProcedureStr, SqlParameter[] parameters, string tableName){
Open();
DataSet ds = new DataSet();
try
{
if (Conn.State != ConnectionState.Open)
Conn.Open();
SqlDataAdapter command = new SqlDataAdapter(StoredProcedureStr, Conn);
command.SelectCommand.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter parameter in parameters)
{
command.SelectCommand.Parameters.Add(parameter);
}
command.Fill(ds, tableName);
Close(); }
catch (System.Data.SqlClient.SqlException ex)
{
MessageBox.Show(ex.Message.ToString() + ex.Number);
throw ex;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
Close();
}
return ds;
} //执行存储过程,返回多个表的结果集
public static DataSet Query(string StoredProcedureStr, SqlParameter[] parameters)
{
Open();
DataSet ds = new DataSet();
try
{
if (Conn.State != ConnectionState.Open)
Conn.Open();
SqlDataAdapter command = new SqlDataAdapter(StoredProcedureStr, Conn);
command.SelectCommand.CommandType = CommandType.StoredProcedure;
foreach (SqlParameter parameter in parameters)
{
command.SelectCommand.Parameters.Add(parameter);
}
command.Fill(ds);
Close(); }
catch (System.Data.SqlClient.SqlException ex)
{
MessageBox.Show(ex.Message.ToString() + ex.Number);
throw ex;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
Close();
}
return ds;
} //
public static void ShowSqlException(SqlException ex)
{
if (ex == null)
return;
// uses SQLServer 2000 ErrorCodes
switch (ex.Number)
{
case :
// SQL Server does not exist or access denied.
case :
// Invalid Database
case :
// Login Failed
break;
case :
MessageBox.Show("外键约束!");
// ForeignKey Violation
break;
case :
// DeadLock Victim
break;
case :
MessageBox.Show("违反约束,插入重复值!");
break;
case :
MessageBox.Show("违反唯一约束,插入重复值!");
// Unique Index/Constriant Violation
break;
default:
// throw a general DAL Exception
break;
}
}
}
}

  

操作SQL Server的帮助类的更多相关文章

  1. SQL Server学习之路(七):Python3操作SQL Server数据库

    0.目录 1.前言 2.准备工作 3.简单测试语句 4.提交与回滚 5.封装成类的写法 1.前言 前面学完了SQL Server的基本语法,接下来学习如何在程序中使用sql,毕竟不能在程序中使用的话, ...

  2. [转]C#操作SQL Server数据库

    转自:C#操作SQL Server数据库 1.概述 ado.net提供了丰富的数据库操作,这些操作可以分为三个步骤: 第一,使用SqlConnection对象连接数据库: 第二,建立SqlComman ...

  3. 数据库SQL Server2012笔记(七)——java 程序操作sql server

    1.crud(增删改查)介绍:create/retrieve/update/delete 2.JDBC介绍 1)JDBC(java database connectivity,java数据库连接) 2 ...

  4. PHP操作SQL Server 2008/2012

    PHP操作SQL Server驱动,微软官方提供2个版本,Version 2.0 和 Version 3.0 Version 2.0 版本支持的操作系统有: Windows Server 2003 S ...

  5. 使用php来访问操作sql server

    使用php来访问操作sql server 在此分成三步走: 第一部:查看配置,下载文件 首先查看自己的php和sql server版本 Php文件输入echo PHP_VERSION  运行脚本就可以 ...

  6. Nodejs 操作 Sql Server

    Nodejs 操作 Sql Server Intro 最近项目需要爬取一些数据,数据有加密,前端的js又被混淆了,ajax请求被 hook 了,有些复杂,最后打算使用 puppeteer 来爬取数据. ...

  7. Python 学习笔记:Python 操作 SQL Server 数据库

    最近要将数据写到数据库里,学习了一下如何用 Python 来操作 SQL Server 数据库. 一.连接数据库: 首先,我们要连接 SQL Server 数据库,需要安装 pymssql 这个第三方 ...

  8. ORM之Dapper操作Sql Server和MySql数据库

    1.为什么选择Dapper 1)轻量. 2)速度快.Dapper的速度接近与IDataReader,取列表的数据超过了DataTable. 3)支持多种数据库.Dapper可以在所有Ado.net P ...

  9. 基于Spring Boot,使用JPA操作Sql Server数据库完成CRUD

    完成一个RESTful服务,提供几个访问接口,用来操作较简单的联系人信息,数据保存在Sql Server数据库中. 1.使用STS创建工程. 使用STS创建RESTful工程,可以参考: <用S ...

随机推荐

  1. [datatables杂记] sAjaxSource 数据源 Search 后 fnInitComplete 不执行。

    var oTable = $('#div_list').dataTable({ "oLanguage": {//语言国际化 "sUrl": "/Adm ...

  2. Cocos2d-x学习笔记1

    版权声明:本文为博主原创文章.未经博主同意不得转载. https://blog.csdn.net/u014734779/article/details/26077453 1.创建新的cocos2d-x ...

  3. 操作系统CPU上下文切换

    关于CPU,有3个重要的概念:上下文切换(context switchs),运行队列(Run queue)和使用率(utilization). 上下文切换: 目前流行的CPU在同一时间内只能运行一个线 ...

  4. 【转】关于gcc、glibc和binutils模块之间的关系

    原文网址:http://www.mike.org.cn/articles/linux-about-gcc-glibc-and-binutils-the-relationship-between-mod ...

  5. display的flex属性使用详解

    flex的兼容性在pc端还算阔以,但是在移动端,那就呵呵了.今天我们只是学习学习,忽略一些不重要的东西. 首先flex的使用需要有一个父容器,父容器中有几个items. 父容器:container 属 ...

  6. Eclipse导入工程后,XDoclet错误:Missing library: xdoclet-1.2.1.jar. Select the home directory for XDoclet

    这几天在使用Open Health Tools的OpenXDS工程,在导入Eclipse后,出现下面的错误: 遂google之,在网上找到了答案.答案网址为http://blog.v-s-f.co.u ...

  7. linux误删数据恢复

    linux下数据恢复工具有: 1.通过分析文件系统的日志,解析文件的inode,可以恢复ex3 ex4的文件系统下的数据 extundelete:扫描inode和恢复数据同时进行,因此恢复速度很快.支 ...

  8. golang调用动态库

    测试动态库 test_so.h int test_so_func(int a,int b); test_so.c #include "test_so.h" int test_so_ ...

  9. CSS3 教程 选择器 标记一下防止 要找时404

    客 » Airen的博客 CSS3 选择器——基本选择器 作者:大漠 日期:2011-08-09 点击:6418  CSS的选择器,我想大家并不会陌生吧,因为天天在使用,但对于CSS3的选择器,要运 ...

  10. jquery json string 转换 合并

    Jquery 1.9.1 var BODY = { "recipients": { "values": [] }, "subject": ' ...