├── test ├── App.config ├── Properties │ └── AssemblyInfo.cs ├── test.csproj └── Program.cs ├── Xus.SQLServerHelper ├── Properties │ └── AssemblyInfo.cs ├── Xus.SQLServerHelper.csproj └── SQLServerHelper.cs ├── Xus.SQLServerHelper.sln ├── README.md ├── .gitignore └── LICENSE /test/App.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /test/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // 有关程序集的常规信息通过以下 5 | // 特性集控制。更改这些特性值可修改 6 | // 与程序集关联的信息。 7 | [assembly: AssemblyTitle("test")] 8 | [assembly: AssemblyDescription("")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("")] 11 | [assembly: AssemblyProduct("test")] 12 | [assembly: AssemblyCopyright("Copyright © 2016")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // 将 ComVisible 设置为 false 使此程序集中的类型 17 | // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, 18 | // 则将该类型上的 ComVisible 特性设置为 true。 19 | [assembly: ComVisible(false)] 20 | 21 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 22 | [assembly: Guid("8c786cfb-a41e-4ec1-9d7a-9b446f722136")] 23 | 24 | // 程序集的版本信息由下面四个值组成: 25 | // 26 | // 主版本 27 | // 次版本 28 | // 生成号 29 | // 修订号 30 | // 31 | // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, 32 | // 方法是按如下所示使用“*”: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.0.0")] 35 | [assembly: AssemblyFileVersion("1.0.0.0")] 36 | -------------------------------------------------------------------------------- /Xus.SQLServerHelper/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // 有关程序集的常规信息通过以下 5 | // 特性集控制。更改这些特性值可修改 6 | // 与程序集关联的信息。 7 | [assembly: AssemblyTitle("Xus.SQLServerHelper")] 8 | [assembly: AssemblyDescription("SQL Server Helper")] 9 | [assembly: AssemblyConfiguration("")] 10 | [assembly: AssemblyCompany("XiaoSheng")] 11 | [assembly: AssemblyProduct("Xus.SQLServerHelper")] 12 | [assembly: AssemblyCopyright("Copyright © XiaoSheng 2016")] 13 | [assembly: AssemblyTrademark("")] 14 | [assembly: AssemblyCulture("")] 15 | 16 | // 将 ComVisible 设置为 false 使此程序集中的类型 17 | // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, 18 | // 则将该类型上的 ComVisible 特性设置为 true。 19 | [assembly: ComVisible(false)] 20 | 21 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 22 | [assembly: Guid("1bad3b3b-ce4c-4861-9c86-8a93d2762bf4")] 23 | 24 | // 程序集的版本信息由下面四个值组成: 25 | // 26 | // 主版本 27 | // 次版本 28 | // 生成号 29 | // 修订号 30 | // 31 | // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, 32 | // 方法是按如下所示使用“*”: 33 | // [assembly: AssemblyVersion("1.0.*")] 34 | [assembly: AssemblyVersion("1.0.1.0")] 35 | [assembly: AssemblyFileVersion("1.0.1.0")] 36 | -------------------------------------------------------------------------------- /Xus.SQLServerHelper.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2013 4 | VisualStudioVersion = 12.0.31101.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Xus.SQLServerHelper", "Xus.SQLServerHelper\Xus.SQLServerHelper.csproj", "{6CD055DE-34BE-4FD7-912F-0EA0AF0DF887}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "test", "test\test.csproj", "{8FB9F738-5CCF-47CA-B0DA-1E75C7A204CD}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {6CD055DE-34BE-4FD7-912F-0EA0AF0DF887}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {6CD055DE-34BE-4FD7-912F-0EA0AF0DF887}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {6CD055DE-34BE-4FD7-912F-0EA0AF0DF887}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {6CD055DE-34BE-4FD7-912F-0EA0AF0DF887}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {8FB9F738-5CCF-47CA-B0DA-1E75C7A204CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {8FB9F738-5CCF-47CA-B0DA-1E75C7A204CD}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {8FB9F738-5CCF-47CA-B0DA-1E75C7A204CD}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {8FB9F738-5CCF-47CA-B0DA-1E75C7A204CD}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /Xus.SQLServerHelper/Xus.SQLServerHelper.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {6CD055DE-34BE-4FD7-912F-0EA0AF0DF887} 8 | Library 9 | Properties 10 | Xus.SQLServerHelper 11 | Xus.SQLServerHelper 12 | v4.5 13 | 512 14 | 1.0.1 15 | false 16 | 17 | 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | bin\Debug\Xus.SQLServerHelper.XML 26 | 27 | 28 | 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | bin\Release\Xus.SQLServerHelper.xml 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 57 | -------------------------------------------------------------------------------- /test/test.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {8FB9F738-5CCF-47CA-B0DA-1E75C7A204CD} 8 | Exe 9 | Properties 10 | test 11 | test 12 | v4.5 13 | 512 14 | 15 | 16 | AnyCPU 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | AnyCPU 27 | pdbonly 28 | true 29 | bin\Release\ 30 | TRACE 31 | prompt 32 | 4 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | {6cd055de-34be-4fd7-912f-0ea0af0df887} 53 | Xus.SQLServerHelper 54 | 55 | 56 | 57 | 64 | -------------------------------------------------------------------------------- /test/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Data; 3 | using System.Data.SqlClient; 4 | using Xus.SQLServerHelper; 5 | 6 | namespace test 7 | { 8 | class Program 9 | { 10 | static void Main(string[] args) 11 | { 12 | //建立SqlHelper对象(包含用户名、密码) 13 | //SqlHelper sqlHelper = new SqlHelper("127.0.0.1", "TestDB", "sa", "12345678"); 14 | //建立SqlHelper对象(不包含用户名、密码) 15 | SqlHelper sqlHelper = new SqlHelper("127.0.0.1", "TestDB"); 16 | 17 | //通过表名获取数据表 18 | DataTable stuTable = sqlHelper.GetTable("student", 50); 19 | PrintTable(stuTable); 20 | //通过sql语句获取数据表 21 | DataTable stuTable2 = sqlHelper.GetTable("select * from student where sex=N'男'"); 22 | PrintTable(stuTable2); 23 | 24 | //按流的方式单向读取数据(使用SqlDataReader) 25 | SqlDataReader sqlDataReader = sqlHelper.GetDataStream("select * from student where sex=N'男'"); 26 | while (sqlDataReader.Read()) 27 | { 28 | //获取指定字段的值 29 | string id = sqlDataReader["sid"].ToString(); 30 | string name = sqlDataReader["name"].ToString(); 31 | string sex = sqlDataReader["sex"].ToString(); 32 | string score = sqlDataReader["score"].ToString(); 33 | Console.WriteLine(id + "\t" + name + "\t" + sex + "\t" + score); 34 | } 35 | sqlHelper.CloseConnection(); 36 | 37 | //执行一条SQL语句 38 | sqlHelper.ExecuteSqlCommand("insert into student(sid,name,sex,score) values(102,'hong',N'女',78.5)"); 39 | DataTable stuTable3 = sqlHelper.GetTable("student", 50); 40 | PrintTable(stuTable3); 41 | 42 | //添加数据到指定DataSet中(添加到一张表) 43 | DataSet dataSet = new DataSet(); 44 | sqlHelper.AddDataToDataSet(dataSet, "select * from student", "student"); 45 | PrintTable(dataSet.Tables["student"]); 46 | //添加数据到指定DataSet中(添加到多张表) 47 | //DataSet dataSet = new DataSet(); 48 | //sqlHelper.AddDataToDataSet(dataSet, new List { "select * from student", "select * from teacher" }, new List { "student", "teacher" }); 49 | //PrintTable(dataSet.Tables["student"]); 50 | //PrintTable(dataSet.Tables["teacher"]); 51 | 52 | //修改student表的分数,批量提交对数据表进行的修改 53 | DataTable tempTable = sqlHelper.GetTable("select * from student"); 54 | foreach (DataRow row in tempTable.Rows) 55 | row["score"] = double.Parse(row["score"].ToString()) - 1; 56 | sqlHelper.UpdateTable(tempTable, "select * from student"); 57 | 58 | //修改student表的分数,批量提交对数据表进行的修改 59 | //DataSet dataSet = new DataSet(); 60 | //sqlHelper.AddDataToDataSet(dataSet, "select * from student", "student"); 61 | //foreach (DataRow row in dataSet.Tables["student"].Rows) 62 | // row["score"] = int.Parse(row["score"].ToString()) + 1; 63 | //sqlHelper.UpdateTable(dataSet, "student", "select * from student"); 64 | } 65 | 66 | /// 67 | /// 打印数据表 68 | /// 69 | /// 要打印的DataTable表 70 | public static void PrintTable(DataTable table) 71 | { 72 | foreach (DataRow row in table.Rows) 73 | { 74 | foreach (DataColumn column in table.Columns) 75 | { 76 | Console.Write(row[column] + "\t"); 77 | } 78 | Console.WriteLine(); 79 | } 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SQLServerHelper 2 | 3 | 适用于 C# 的 SQL Server 连接辅助类,提供了对数据库的常用操作,包括执行 SQL 语句、按流的方式读取数据、填充本地 DataSet、批量提交对数据表的修改等。 4 | 5 | ### 下载 6 | 7 | [Xus.SQLServerHelper](https://github.com/jsksxs360/Xus.SQLServerHelper/releases/) 8 | 9 | ## 构造函数 10 | 11 | SQLServerHelper 对象有三种构造方式:使用用户名密码验证的构造函数、使用 Windows 身份验证的构造函数、使用连接字符串的构造函数。 12 | 13 | ```csharp 14 | //使用用户名、密码验证 15 | SqlHelper(string dataSource, string dataBase, string user, string pwd, int timeout = 5) 16 | 17 | //或者使用Windows身份验证 18 | SqlHelper(string dataSource, string dataBase, int timeout = 5) 19 | 20 | //传入连接字符串 21 | SqlHelper(string connectionString) 22 | ``` 23 | 24 | - **dataSource:** 数据源 25 | - **dataBase:** 数据库 26 | - **user:** 用户名 27 | - **pwd:** 密码 28 | - **timeout:** 连接超时(秒),默认5秒 29 | 30 | 通常情况下,我们使用带有用户名和密码的验证方式连接数据库。只有当数据库开启了 Windows 身份验证,并且以该用户身份登录主机时,我们才能使用直接验证身份的连接方式。 31 | 32 | ## 执行一条SQL语句 33 | 34 | 执行 SQL 语句,是最基本的操作,SQLServerHelper 提供了 **ExecuteSqlCommand()** 函数来实现: 35 | 36 | ```csharp 37 | int ExecuteSqlCommand(string sqlCommand, bool closeConnection = true) 38 | ``` 39 | 40 | - **sqlCommand:** 要执行的 SQL 语句 41 | - **closeConnection:** 是否关闭连接,默认关闭 42 | - **returns:** 执行 SQL 语句受影响的行数 43 | 44 | **ExecuteSqlCommand()** 函数实际是对 `SqlCommand.ExecuteNonQuery()` 函数的包装。当需要批量地执行 SQL 语句时,可以将 **closeConnection** 参数设置为 false 不关闭连接,待所有语句执行完毕后再通过 **CloseConnection()** 函数关闭连接,避免了每次打开、关闭连接的时间消耗。 45 | 46 | ## 获取数据表 47 | 48 | 从数据库中获取某张数据表也是常用的操作,SQLServerHelper 提供了 **GetTable()** 函数来实现: 49 | 50 | ```csharp 51 | //通过sql语句获取数据表 52 | DataTable GetTable(string selectSqlCommand) 53 | ``` 54 | - **selectSqlCommand:** 获取表的select语句 55 | 56 | ```csharp 57 | //通过表名获取数据表 58 | DataTable GetTable(string tableName, int rows) 59 | ``` 60 | 61 | 62 | - **tableName:** 获取数据表的名称 63 | - **rows:** 查询的数据行数 64 | 65 | 可以直接通过 Select 语句来获取数据表,也可以直接通过表名和指定返回条数的方式获取数据表。函数实际上是对 `SqlDataAdapter.Fill()` 函数的包装。 66 | 67 | ## 按流的方式单向读取数据 68 | 69 | 当需要从数据库中读取大量数据时,直接返回整张表的方式就不合适了,这时就应该使用数据流的方式来读取了,SQLServerHelper 提供了 **GetDataStream()** 函数来实现: 70 | 71 | ```csharp 72 | SqlDataReader GetDataStream(string selectSqlCommand) 73 | ``` 74 | - **selectSqlCommand:** 获取数据的select语句 75 | - **returns:** SqlDataReader对象 76 | 77 | 获取到 SqlDataReader 对象后,就可以通过循环的方式来一条一条的读取数据了: 78 | 79 | ```csharp 80 | SqlDataReader sqlDataReader = sqlHelper.GetDataStream("select * from student where sex=N'男'"); 81 | while (sqlDataReader.Read()) 82 | { 83 | //获取指定字段的值 84 | string id = sqlDataReader["sid"].ToString(); 85 | string name = sqlDataReader["name"].ToString(); 86 | string sex = sqlDataReader["sex"].ToString(); 87 | string score = sqlDataReader["score"].ToString(); 88 | Console.WriteLine(id + "\t" + name + "\t" + sex + "\t" + score); 89 | } 90 | sqlHelper.CloseConnection(); 91 | ``` 92 | 93 | 注意:在读取完所有数据后,需要使用 **CloseConnection()** 函数手动关闭连接。 94 | 95 | ## 添加数据到指定 DataSet 中 96 | 97 | DataSet 相当于是本地的一个临时数据库,当需要频繁从同一张数据表读取数据,或者需要批量修改表中的数据时,就可以使用 **AddDataToDataSet()** 函数在内存中建立临时的本地数据库,提高数据的读取速度。 98 | 99 | ```csharp 100 | //添加数据到指定DataSet中(添加到一张表) 101 | void AddDataToDataSet(DataSet dataSet, string selectSqlCommands, string insertTableName) 102 | ``` 103 | - **dataSet:** 被填充的 DataSet 104 | - **selectSqlCommands:** 获取数据的select语句 105 | - **insertTableName:** 插入数据表的表名 106 | 107 | ```csharp 108 | //添加数据到指定DataSet中(添加到多张表) 109 | void AddDataToDataSet(DataSet dataSet, List selectSqlCommands, List insertTableNames) 110 | ``` 111 | - **dataSet:** 被填充的DataSet 112 | - **selectSqlCommands:** 获取数据的select语句列表 113 | - **insertTableNames:** 对应sql语句列表的插入表名列表 114 | 115 | **AddDataToDataSet()** 函数不仅支持在本地添加一张表,也支持同时建立多张表。 116 | 117 | ## 提交对数据表进行的修改 118 | 119 | 当我们需要对一张表做大量的修改时,通过反复执行 Update 函数就不是一个好的选择了。更好的做法是,现在本地建立一张表的备份,然后直接在内存中对表中的数据进行修改,最后再向数据库批量提交修改,SQLServerHelper 提供了 **UpdateTable()** 函数来实现: 120 | 121 | ```csharp 122 | //提交对数据表进行的修改 123 | void UpdateTable(DataTable dataTable, string createTableSqlCommand) 124 | ``` 125 | - **dataTable:** 修改的数据表 126 | - **createTableSqlCommand:** 创建数据表的sql语句 127 | 128 | ```csharp 129 | //提交对数据表进行的修改(在DataSet中的数据表) 130 | void UpdateTable(DataSet dataset, string TableName, string createTableSqlCommand) 131 | ``` 132 | - **dataset:** 修改的数据表所在的DataSet 133 | - **TableName:** 创建被修改的数据表名 134 | - **createTableSqlCommand:** 创建数据表的sql语句 135 | 136 | **UpdateTable()** 函数支持提交直接对数据表的修改,也支持提交对 DataSet 中的数据表的修改。 137 | 138 | 注意:**createTableSqlCommand** 参数是为了让函数知晓数据表的字段结构,因而必须包含完整的建表 SQL 语句,最好直接使用建表时的 SQL 语句以避免不必要的错误。 139 | 140 | ## 注意 141 | 142 | ### 与数据库连接的管理问题 143 | 144 | 绝大多函数都会自动管理与数据库连接的打开和关闭,不需要用户的干预。只有按流的方式单向读取数据的 **GetDataStream()** 函数,需要用户在读取完所有数据后调用 **CloseConnection()** 函数手动关闭连接。如果执行 SQL 语句 **ExecuteSqlCommand()** 函数以不关闭连接的方式调用,也需要用户手动关闭连接。 145 | 146 | ### 同时读写 147 | 148 | 由于每一个 SQLServerHelper 对象只维护一个与数据库的连接,所以当读取操作与写入操作同时发生时会发生错误(例如,在按流的方式 **GetDataStream()** 单向读取数据的过程中,又调用 **ExecuteSqlCommand()** 函数向数据库中写入数据),这时候必须建立多个 SQLServerHelper 对象。 149 | 150 | ### 调用示例 151 | 152 | 具体的调用方式可以参考 [测试代码](https://github.com/jsksxs360/Xus.SQLServerHelper/blob/master/test/Program.cs) 153 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | *.vcxproj.filters 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | bld/ 24 | [Bb]in/ 25 | [Oo]bj/ 26 | [Ll]og/ 27 | 28 | # Visual Studio 2015 cache/options directory 29 | .vs/ 30 | # Uncomment if you have tasks that create the project's static files in wwwroot 31 | #wwwroot/ 32 | 33 | # MSTest test Results 34 | [Tt]est[Rr]esult*/ 35 | [Bb]uild[Ll]og.* 36 | 37 | # NUNIT 38 | *.VisualState.xml 39 | TestResult.xml 40 | 41 | # Build Results of an ATL Project 42 | [Dd]ebugPS/ 43 | [Rr]eleasePS/ 44 | dlldata.c 45 | 46 | # DNX 47 | project.lock.json 48 | project.fragment.lock.json 49 | artifacts/ 50 | Properties/launchSettings.json 51 | 52 | *_i.c 53 | *_p.c 54 | *_i.h 55 | *.ilk 56 | *.meta 57 | *.obj 58 | *.pch 59 | *.pdb 60 | *.pgc 61 | *.pgd 62 | *.rsp 63 | *.sbr 64 | *.tlb 65 | *.tli 66 | *.tlh 67 | *.tmp 68 | *.tmp_proj 69 | *.log 70 | *.vspscc 71 | *.vssscc 72 | .builds 73 | *.pidb 74 | *.svclog 75 | *.scc 76 | 77 | # Chutzpah Test files 78 | _Chutzpah* 79 | 80 | # Visual C++ cache files 81 | ipch/ 82 | *.aps 83 | *.ncb 84 | *.opendb 85 | *.opensdf 86 | *.sdf 87 | *.cachefile 88 | *.VC.db 89 | *.VC.VC.opendb 90 | 91 | # Visual Studio profiler 92 | *.psess 93 | *.vsp 94 | *.vspx 95 | *.sap 96 | 97 | # TFS 2012 Local Workspace 98 | $tf/ 99 | 100 | # Guidance Automation Toolkit 101 | *.gpState 102 | 103 | # ReSharper is a .NET coding add-in 104 | _ReSharper*/ 105 | *.[Rr]e[Ss]harper 106 | *.DotSettings.user 107 | 108 | # JustCode is a .NET coding add-in 109 | .JustCode 110 | 111 | # TeamCity is a build add-in 112 | _TeamCity* 113 | 114 | # DotCover is a Code Coverage Tool 115 | *.dotCover 116 | 117 | # Visual Studio code coverage results 118 | *.coverage 119 | *.coveragexml 120 | 121 | # NCrunch 122 | _NCrunch_* 123 | .*crunch*.local.xml 124 | nCrunchTemp_* 125 | 126 | # MightyMoose 127 | *.mm.* 128 | AutoTest.Net/ 129 | 130 | # Web workbench (sass) 131 | .sass-cache/ 132 | 133 | # Installshield output folder 134 | [Ee]xpress/ 135 | 136 | # DocProject is a documentation generator add-in 137 | DocProject/buildhelp/ 138 | DocProject/Help/*.HxT 139 | DocProject/Help/*.HxC 140 | DocProject/Help/*.hhc 141 | DocProject/Help/*.hhk 142 | DocProject/Help/*.hhp 143 | DocProject/Help/Html2 144 | DocProject/Help/html 145 | 146 | # Click-Once directory 147 | publish/ 148 | 149 | # Publish Web Output 150 | *.[Pp]ublish.xml 151 | *.azurePubxml 152 | # TODO: Comment the next line if you want to checkin your web deploy settings 153 | # but database connection strings (with potential passwords) will be unencrypted 154 | *.pubxml 155 | *.publishproj 156 | 157 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 158 | # checkin your Azure Web App publish settings, but sensitive information contained 159 | # in these scripts will be unencrypted 160 | PublishScripts/ 161 | 162 | # NuGet Packages 163 | *.nupkg 164 | # The packages folder can be ignored because of Package Restore 165 | **/packages/* 166 | # except build/, which is used as an MSBuild target. 167 | !**/packages/build/ 168 | # Uncomment if necessary however generally it will be regenerated when needed 169 | #!**/packages/repositories.config 170 | # NuGet v3's project.json files produces more ignoreable files 171 | *.nuget.props 172 | *.nuget.targets 173 | 174 | # Microsoft Azure Build Output 175 | csx/ 176 | *.build.csdef 177 | 178 | # Microsoft Azure Emulator 179 | ecf/ 180 | rcf/ 181 | 182 | # Windows Store app package directories and files 183 | AppPackages/ 184 | BundleArtifacts/ 185 | Package.StoreAssociation.xml 186 | _pkginfo.txt 187 | 188 | # Visual Studio cache files 189 | # files ending in .cache can be ignored 190 | *.[Cc]ache 191 | # but keep track of directories ending in .cache 192 | !*.[Cc]ache/ 193 | 194 | # Others 195 | ClientBin/ 196 | ~$* 197 | *~ 198 | *.dbmdl 199 | *.dbproj.schemaview 200 | *.jfm 201 | *.pfx 202 | *.publishsettings 203 | node_modules/ 204 | orleans.codegen.cs 205 | 206 | # Since there are multiple workflows, uncomment next line to ignore bower_components 207 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 208 | #bower_components/ 209 | 210 | # RIA/Silverlight projects 211 | Generated_Code/ 212 | 213 | # Backup & report files from converting an old project file 214 | # to a newer Visual Studio version. Backup files are not needed, 215 | # because we have git ;-) 216 | _UpgradeReport_Files/ 217 | Backup*/ 218 | UpgradeLog*.XML 219 | UpgradeLog*.htm 220 | 221 | # SQL Server files 222 | *.mdf 223 | *.ldf 224 | 225 | # Business Intelligence projects 226 | *.rdl.data 227 | *.bim.layout 228 | *.bim_*.settings 229 | 230 | # Microsoft Fakes 231 | FakesAssemblies/ 232 | 233 | # GhostDoc plugin setting file 234 | *.GhostDoc.xml 235 | 236 | # Node.js Tools for Visual Studio 237 | .ntvs_analysis.dat 238 | 239 | # Visual Studio 6 build log 240 | *.plg 241 | 242 | # Visual Studio 6 workspace options file 243 | *.opt 244 | 245 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 246 | *.vbw 247 | 248 | # Visual Studio LightSwitch build output 249 | **/*.HTMLClient/GeneratedArtifacts 250 | **/*.DesktopClient/GeneratedArtifacts 251 | **/*.DesktopClient/ModelManifest.xml 252 | **/*.Server/GeneratedArtifacts 253 | **/*.Server/ModelManifest.xml 254 | _Pvt_Extensions 255 | 256 | # Paket dependency manager 257 | .paket/paket.exe 258 | paket-files/ 259 | 260 | # FAKE - F# Make 261 | .fake/ 262 | 263 | # JetBrains Rider 264 | .idea/ 265 | *.sln.iml 266 | 267 | # CodeRush 268 | .cr/ 269 | 270 | # Python Tools for Visual Studio (PTVS) 271 | __pycache__/ 272 | *.pyc 273 | 274 | # Cake - Uncomment if you are using it 275 | # tools/ 276 | 277 | # MacOs 278 | .DS_Store 279 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, and 10 | distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright 13 | owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities 16 | that control, are controlled by, or are under common control with that entity. 17 | For the purposes of this definition, "control" means (i) the power, direct or 18 | indirect, to cause the direction or management of such entity, whether by 19 | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the 20 | outstanding shares, or (iii) beneficial ownership of such entity. 21 | 22 | "You" (or "Your") shall mean an individual or Legal Entity exercising 23 | permissions granted by this License. 24 | 25 | "Source" form shall mean the preferred form for making modifications, including 26 | but not limited to software source code, documentation source, and configuration 27 | files. 28 | 29 | "Object" form shall mean any form resulting from mechanical transformation or 30 | translation of a Source form, including but not limited to compiled object code, 31 | generated documentation, and conversions to other media types. 32 | 33 | "Work" shall mean the work of authorship, whether in Source or Object form, made 34 | available under the License, as indicated by a copyright notice that is included 35 | in or attached to the work (an example is provided in the Appendix below). 36 | 37 | "Derivative Works" shall mean any work, whether in Source or Object form, that 38 | is based on (or derived from) the Work and for which the editorial revisions, 39 | annotations, elaborations, or other modifications represent, as a whole, an 40 | original work of authorship. For the purposes of this License, Derivative Works 41 | shall not include works that remain separable from, or merely link (or bind by 42 | name) to the interfaces of, the Work and Derivative Works thereof. 43 | 44 | "Contribution" shall mean any work of authorship, including the original version 45 | of the Work and any modifications or additions to that Work or Derivative Works 46 | thereof, that is intentionally submitted to Licensor for inclusion in the Work 47 | by the copyright owner or by an individual or Legal Entity authorized to submit 48 | on behalf of the copyright owner. For the purposes of this definition, 49 | "submitted" means any form of electronic, verbal, or written communication sent 50 | to the Licensor or its representatives, including but not limited to 51 | communication on electronic mailing lists, source code control systems, and 52 | issue tracking systems that are managed by, or on behalf of, the Licensor for 53 | the purpose of discussing and improving the Work, but excluding communication 54 | that is conspicuously marked or otherwise designated in writing by the copyright 55 | owner as "Not a Contribution." 56 | 57 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf 58 | of whom a Contribution has been received by Licensor and subsequently 59 | incorporated within the Work. 60 | 61 | 2. Grant of Copyright License. 62 | 63 | Subject to the terms and conditions of this License, each Contributor hereby 64 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 65 | irrevocable copyright license to reproduce, prepare Derivative Works of, 66 | publicly display, publicly perform, sublicense, and distribute the Work and such 67 | Derivative Works in Source or Object form. 68 | 69 | 3. Grant of Patent License. 70 | 71 | Subject to the terms and conditions of this License, each Contributor hereby 72 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 73 | irrevocable (except as stated in this section) patent license to make, have 74 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where 75 | such license applies only to those patent claims licensable by such Contributor 76 | that are necessarily infringed by their Contribution(s) alone or by combination 77 | of their Contribution(s) with the Work to which such Contribution(s) was 78 | submitted. If You institute patent litigation against any entity (including a 79 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a 80 | Contribution incorporated within the Work constitutes direct or contributory 81 | patent infringement, then any patent licenses granted to You under this License 82 | for that Work shall terminate as of the date such litigation is filed. 83 | 84 | 4. Redistribution. 85 | 86 | You may reproduce and distribute copies of the Work or Derivative Works thereof 87 | in any medium, with or without modifications, and in Source or Object form, 88 | provided that You meet the following conditions: 89 | 90 | You must give any other recipients of the Work or Derivative Works a copy of 91 | this License; and 92 | You must cause any modified files to carry prominent notices stating that You 93 | changed the files; and 94 | You must retain, in the Source form of any Derivative Works that You distribute, 95 | all copyright, patent, trademark, and attribution notices from the Source form 96 | of the Work, excluding those notices that do not pertain to any part of the 97 | Derivative Works; and 98 | If the Work includes a "NOTICE" text file as part of its distribution, then any 99 | Derivative Works that You distribute must include a readable copy of the 100 | attribution notices contained within such NOTICE file, excluding those notices 101 | that do not pertain to any part of the Derivative Works, in at least one of the 102 | following places: within a NOTICE text file distributed as part of the 103 | Derivative Works; within the Source form or documentation, if provided along 104 | with the Derivative Works; or, within a display generated by the Derivative 105 | Works, if and wherever such third-party notices normally appear. The contents of 106 | the NOTICE file are for informational purposes only and do not modify the 107 | License. You may add Your own attribution notices within Derivative Works that 108 | You distribute, alongside or as an addendum to the NOTICE text from the Work, 109 | provided that such additional attribution notices cannot be construed as 110 | modifying the License. 111 | You may add Your own copyright statement to Your modifications and may provide 112 | additional or different license terms and conditions for use, reproduction, or 113 | distribution of Your modifications, or for any such Derivative Works as a whole, 114 | provided Your use, reproduction, and distribution of the Work otherwise complies 115 | with the conditions stated in this License. 116 | 117 | 5. Submission of Contributions. 118 | 119 | Unless You explicitly state otherwise, any Contribution intentionally submitted 120 | for inclusion in the Work by You to the Licensor shall be under the terms and 121 | conditions of this License, without any additional terms or conditions. 122 | Notwithstanding the above, nothing herein shall supersede or modify the terms of 123 | any separate license agreement you may have executed with Licensor regarding 124 | such Contributions. 125 | 126 | 6. Trademarks. 127 | 128 | This License does not grant permission to use the trade names, trademarks, 129 | service marks, or product names of the Licensor, except as required for 130 | reasonable and customary use in describing the origin of the Work and 131 | reproducing the content of the NOTICE file. 132 | 133 | 7. Disclaimer of Warranty. 134 | 135 | Unless required by applicable law or agreed to in writing, Licensor provides the 136 | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, 137 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, 138 | including, without limitation, any warranties or conditions of TITLE, 139 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are 140 | solely responsible for determining the appropriateness of using or 141 | redistributing the Work and assume any risks associated with Your exercise of 142 | permissions under this License. 143 | 144 | 8. Limitation of Liability. 145 | 146 | In no event and under no legal theory, whether in tort (including negligence), 147 | contract, or otherwise, unless required by applicable law (such as deliberate 148 | and grossly negligent acts) or agreed to in writing, shall any Contributor be 149 | liable to You for damages, including any direct, indirect, special, incidental, 150 | or consequential damages of any character arising as a result of this License or 151 | out of the use or inability to use the Work (including but not limited to 152 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or 153 | any and all other commercial damages or losses), even if such Contributor has 154 | been advised of the possibility of such damages. 155 | 156 | 9. Accepting Warranty or Additional Liability. 157 | 158 | While redistributing the Work or Derivative Works thereof, You may choose to 159 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or 160 | other liability obligations and/or rights consistent with this License. However, 161 | in accepting such obligations, You may act only on Your own behalf and on Your 162 | sole responsibility, not on behalf of any other Contributor, and only if You 163 | agree to indemnify, defend, and hold each Contributor harmless for any liability 164 | incurred by, or claims asserted against, such Contributor by reason of your 165 | accepting any such warranty or additional liability. 166 | 167 | END OF TERMS AND CONDITIONS 168 | 169 | APPENDIX: How to apply the Apache License to your work 170 | 171 | To apply the Apache License to your work, attach the following boilerplate 172 | notice, with the fields enclosed by brackets "{}" replaced with your own 173 | identifying information. (Don't include the brackets!) The text should be 174 | enclosed in the appropriate comment syntax for the file format. We also 175 | recommend that a file or class name and description of purpose be included on 176 | the same "printed page" as the copyright notice for easier identification within 177 | third-party archives. 178 | 179 | Copyright 2016 jsksxs360 180 | 181 | Licensed under the Apache License, Version 2.0 (the "License"); 182 | you may not use this file except in compliance with the License. 183 | You may obtain a copy of the License at 184 | 185 | http://www.apache.org/licenses/LICENSE-2.0 186 | 187 | Unless required by applicable law or agreed to in writing, software 188 | distributed under the License is distributed on an "AS IS" BASIS, 189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 190 | See the License for the specific language governing permissions and 191 | limitations under the License. 192 | -------------------------------------------------------------------------------- /Xus.SQLServerHelper/SQLServerHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Data; 5 | using System.Data.SqlClient; 6 | 7 | namespace Xus.SQLServerHelper 8 | { 9 | /// 10 | /// SQL 连接助手类 11 | /// 12 | public class SqlHelper 13 | { 14 | /// 15 | /// Sql连接对象 16 | /// 17 | /// Sql连接对象 18 | private SqlConnection SqlCnt { get; set; } //Sql连接对象 19 | 20 | /// 21 | /// 构造函数 22 | /// (使用用户名、密码验证) 23 | /// 24 | /// 数据源 25 | /// 数据库 26 | /// 用户名 27 | /// 密码 28 | /// 连接超时(秒),默认5秒 29 | public SqlHelper(string dataSource, string dataBase, string user, string pwd, int timeout = 5) 30 | { 31 | string connectionString = "Data Source=" + dataSource + ";Initial Catalog=" + dataBase + ";User ID=" + user + ";Password=" + pwd + ";Connection Timeout=" + timeout + ";"; 32 | SqlCnt = new SqlConnection(connectionString); 33 | } 34 | 35 | /// 36 | /// 构造函数 37 | /// (使用Windows身份验证) 38 | /// 39 | /// 数据源 40 | /// 数据库 41 | /// 连接超时(秒),默认5秒 42 | public SqlHelper(string dataSource, string dataBase, int timeout = 5) 43 | { 44 | string connectionString = "Data Source=" + dataSource + ";Initial Catalog=" + dataBase + ";Integrated Security=True;Connection Timeout=" + timeout + ";"; 45 | SqlCnt = new SqlConnection(connectionString); 46 | } 47 | 48 | /// 49 | /// 构造函数 50 | /// (传入连接字符串) 51 | /// 52 | /// 53 | public SqlHelper(string connectionString) 54 | { 55 | SqlCnt = new SqlConnection(connectionString); 56 | } 57 | 58 | /// 59 | /// 打开连接 60 | /// 61 | private void OpenConnection() 62 | { 63 | if (SqlCnt.State == ConnectionState.Closed) //连接关闭 64 | { 65 | try 66 | { 67 | SqlCnt.Open(); 68 | } 69 | catch (Exception e) 70 | { 71 | throw new Exception("服务器连接失败:" + e); 72 | } 73 | } 74 | else if (SqlCnt.State == ConnectionState.Broken) //连接中断 75 | { 76 | try 77 | { 78 | CloseConnection(); 79 | SqlCnt.Open(); 80 | } 81 | catch (Exception e) 82 | { 83 | throw new Exception("服务器连接失败:" + e); 84 | } 85 | } 86 | } 87 | 88 | /// 89 | /// 关闭连接 90 | /// 91 | public void CloseConnection() 92 | { 93 | try 94 | { 95 | SqlCnt.Close(); 96 | } 97 | catch (Exception e) 98 | { 99 | throw new Exception("关闭数据库连接失败:" + e); 100 | } 101 | } 102 | 103 | /// 104 | /// 执行一条SQL语句 105 | /// 106 | /// 要执行的SQL语句 107 | /// 是否关闭连接,默认关闭 108 | /// 执行SQL语句受影响的行数 109 | public int ExecuteSqlCommand(string sqlCommand, bool closeConnection = true) 110 | { 111 | if (string.IsNullOrEmpty(sqlCommand)) 112 | throw new Exception("要执行的SQL语句不能为空"); 113 | OpenConnection(); 114 | SqlCommand sqlCmd = new SqlCommand(sqlCommand, SqlCnt); 115 | try 116 | { 117 | int changeRows = sqlCmd.ExecuteNonQuery(); //执行SQL语句 118 | if (closeConnection) //关闭连接 119 | CloseConnection(); 120 | return changeRows; 121 | } 122 | catch (Exception e) 123 | { 124 | throw new Exception("SQL语句存在错误:" + e); 125 | } 126 | } 127 | 128 | /// 129 | /// 通过sql语句获取数据表 130 | /// 131 | /// 获取表的select语句 132 | /// 获取到的数据表 133 | public DataTable GetTable(string selectSqlCommand) 134 | { 135 | if (string.IsNullOrEmpty(selectSqlCommand)) 136 | throw new Exception("要执行的select语句不能为空"); 137 | OpenConnection(); 138 | SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(selectSqlCommand, SqlCnt); 139 | DataTable dataTable = new DataTable(); 140 | try 141 | { 142 | sqlDataAdapter.Fill(dataTable); //通过SqlDataAdapter填充DataTable对象 143 | } 144 | catch (Exception e) 145 | { 146 | throw new Exception("select语句有错或者数据表不存在:" + e); 147 | } 148 | finally 149 | { 150 | CloseConnection(); 151 | } 152 | return dataTable; 153 | } 154 | 155 | /// 156 | /// 通过表名获取数据表 157 | /// 158 | /// 获取数据表的名称 159 | /// 查询的数据行数 160 | /// 获取到的数据表 161 | public DataTable GetTable(string tableName, int rows) 162 | { 163 | if (string.IsNullOrEmpty(tableName)) 164 | throw new Exception("要获取的数据表名称不能为空"); 165 | OpenConnection(); 166 | SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("select top " + rows + " * from " + tableName, SqlCnt); 167 | DataTable dataTable = new DataTable(); 168 | try 169 | { 170 | sqlDataAdapter.Fill(dataTable); //通过SqlDataAdapter填充DataTable对象 171 | CloseConnection(); 172 | return dataTable; 173 | } 174 | catch (Exception e) 175 | { 176 | throw new Exception("数据表不存在:" + e); 177 | } 178 | } 179 | 180 | /// 181 | /// 按流的方式单向读取数据 182 | /// (使用SqlDataReader) 183 | /// 184 | /// 获取数据的select语句 185 | /// SqlDataReader对象 186 | public SqlDataReader GetDataStream(string selectSqlCommand) 187 | { 188 | if (string.IsNullOrEmpty(selectSqlCommand)) 189 | throw new Exception("要执行的select语句不能为空"); 190 | OpenConnection(); 191 | SqlCommand sqlCmd = new SqlCommand(selectSqlCommand, SqlCnt); 192 | try 193 | { 194 | SqlDataReader reader = sqlCmd.ExecuteReader(); //建立SqlDataReader对象 195 | return reader; 196 | } 197 | catch (Exception e) 198 | { 199 | throw new Exception("select语句存在错误或者数据表不存在:" + e); 200 | } 201 | } 202 | 203 | /// 204 | /// 添加数据到指定DataSet中 205 | /// (添加到一张表) 206 | /// 207 | /// 被填充的DataSet 208 | /// 获取数据的select语句 209 | /// 插入数据表的表名 210 | public void AddDataToDataSet(DataSet dataSet, string selectSqlCommands, string insertTableName) 211 | { 212 | if (dataSet == null) 213 | throw new Exception("要填充数据的DataSet不能为null"); 214 | if (string.IsNullOrEmpty(selectSqlCommands)) 215 | throw new Exception("获取数据的select语句不能为空"); 216 | if (string.IsNullOrEmpty(insertTableName)) 217 | throw new Exception("插入的表名不能为空"); 218 | SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(selectSqlCommands, SqlCnt); 219 | try 220 | { 221 | sqlDataAdapter.Fill(dataSet, insertTableName); //通过SqlDataAdapter向DataSet中填充数据 222 | } 223 | catch (Exception e) 224 | { 225 | throw new Exception("select语句存在错误:" + e); 226 | } 227 | finally 228 | { 229 | CloseConnection(); 230 | } 231 | } 232 | 233 | /// 234 | /// 添加数据到指定DataSet中 235 | /// (添加到多张表) 236 | /// 237 | /// 被填充的DataSet 238 | /// 获取数据的select语句列表 239 | /// 对应sql语句列表的插入表名列表 240 | public void AddDataToDataSet(DataSet dataSet, List selectSqlCommands, List insertTableNames) 241 | { 242 | if (dataSet == null) 243 | throw new Exception("要填充数据的DataSet不能为null"); 244 | if (selectSqlCommands == null || selectSqlCommands.Count == 0) 245 | throw new Exception("获取数据的select语句列表不能为空"); 246 | if (insertTableNames == null || insertTableNames.Count == 0) 247 | throw new Exception("插入表名列表不能为空"); 248 | if (selectSqlCommands.Count != insertTableNames.Count) 249 | throw new Exception("select语句列表与插入表名列表长度不一致"); 250 | //拼接select语句列表,获取最终执行的select语句 251 | string selectCommand = string.Empty; 252 | foreach (string cmd in selectSqlCommands) 253 | if (cmd.Last() == ';') 254 | selectCommand += cmd; 255 | else 256 | selectCommand += (cmd + ";"); 257 | SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(selectCommand, SqlCnt); 258 | //通过插入表名列表,指定数据插入的数据表名称 259 | sqlDataAdapter.TableMappings.Add("Table", insertTableNames.ElementAt(0)); 260 | for (int i = 1; i < insertTableNames.Count; i++) 261 | sqlDataAdapter.TableMappings.Add("Table" + i, insertTableNames.ElementAt(i)); 262 | try 263 | { 264 | sqlDataAdapter.Fill(dataSet); //通过SqlDataAdapter向DataSet中填充数据 265 | } 266 | catch (Exception e) 267 | { 268 | throw new Exception("select语句列表中存在错误的sql语句:" + e); 269 | } 270 | finally 271 | { 272 | CloseConnection(); 273 | } 274 | } 275 | 276 | /// 277 | /// 提交对数据表进行的修改 278 | /// 279 | /// 修改的数据表 280 | /// 创建数据表的sql语句 281 | public void UpdateTable(DataTable dataTable, string createTableSqlCommand) 282 | { 283 | if (dataTable == null) 284 | throw new Exception("修改的数据表不能为空"); 285 | if (string.IsNullOrEmpty(createTableSqlCommand)) 286 | throw new Exception("创建数据表的sql语句不能为空"); 287 | SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(createTableSqlCommand, SqlCnt); 288 | //为SqlDataAdapter赋予SqlCommandBuilder功能 289 | SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter); 290 | try 291 | { 292 | sqlDataAdapter.Update(dataTable); //批量提交表中的所有修改 293 | } 294 | catch (Exception e) 295 | { 296 | throw new Exception("向数据库批量提交修改失败:" + e); 297 | } 298 | } 299 | 300 | /// 301 | /// 提交对数据表进行的修改 302 | /// (在DataSet中的数据表) 303 | /// 304 | /// 修改的数据表所在的DataSet 305 | /// 被修改的数据表名 306 | /// 创建数据表的sql语句 307 | public void UpdateTable(DataSet dataset, string TableName, string createTableSqlCommand) 308 | { 309 | if (dataset == null) 310 | throw new Exception("修改过的DataSet不能为null"); 311 | if (TableName == null || TableName == string.Empty) 312 | throw new Exception("数据表名不能为空"); 313 | if (string.IsNullOrEmpty(createTableSqlCommand)) 314 | throw new Exception("创建数据表的select语句不能为空"); 315 | SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(createTableSqlCommand, SqlCnt); 316 | //为SqlDataAdapter赋予SqlCommandBuilder功能 317 | SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(sqlDataAdapter); 318 | try 319 | { 320 | sqlDataAdapter.Update(dataset, TableName); //批量提交表中的所有修改 321 | } 322 | catch (Exception e) 323 | { 324 | throw new Exception("向数据库批量提交修改失败:" + e); 325 | } 326 | } 327 | } 328 | } --------------------------------------------------------------------------------