记一次C# Sql Server数据库处理

记一次C# Sql Server数据库处理

菜企鹅 Lv2

类 MDataBase

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SqlServerTest.DataBase
{
public class MDataBase
{
protected readonly SqlConnection _connection;
public MDataBase(string connectionString)
{
_connection = new SqlConnection(connectionString);
}

public virtual async Task<List<T>> Select<T>(string query, SqlParameter[] sqlParameters) where T : new()
{
try
{
if (_connection.State != ConnectionState.Open)
await _connection.OpenAsync();

using (SqlCommand sqlCommand = new SqlCommand(query, _connection))
{
sqlCommand.Parameters.AddRange(sqlParameters);
using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sqlCommand))
{
DataSet ds = new DataSet();
await Task.Run(() => sqlDataAdapter.Fill(ds));

// 创建用于存储结果的列表
List<T> resultList = new List<T>();

// 遍历 DataSet 中的每个 DataTable
foreach (DataTable dataTable in ds.Tables)
{
// 遍历 DataTable 中的每行数据
foreach (DataRow row in dataTable.Rows)
{
// 创建一个新的泛型对象
T obj = new T();

// 使用反射将每列的值赋给对象的属性
foreach (DataColumn column in dataTable.Columns)
{
var property = typeof(T).GetProperty(column.ColumnName);
if (property != null && row[column] != DBNull.Value)
{
property.SetValue(obj, Convert.ChangeType(row[column], property.PropertyType));
}
}

// 将对象添加到结果列表中
resultList.Add(obj);
}
}

return resultList;
}
}
}
catch (Exception)
{
// 返回异常给上层
throw;
}
finally
{
// 确保连接在完成后关闭
_connection.Close();
}
}

public virtual async Task<bool> Insert<T>(List<T> items, string insertQuery) where T : new()
{
try
{
if (_connection.State != ConnectionState.Open)
await _connection.OpenAsync();

using (SqlCommand sqlCommand = new SqlCommand(insertQuery, _connection))
{
foreach (var item in items)
{
sqlCommand.Parameters.Clear();
var properties = typeof(T).GetProperties();
foreach (var property in properties)
{
sqlCommand.Parameters.AddWithValue($"@{property.Name}", property.GetValue(item) ?? DBNull.Value);
}

int rowsAffected = await sqlCommand.ExecuteNonQueryAsync();
if (rowsAffected == 0)
{
return false; // 如果没有影响任何行,则操作失败
}
}

return true; // 所有行都受影响,则操作成功
}
}
catch (Exception)
{
// 将异常传播给调用层
throw;
}
finally
{
_connection.Close();
}
}

public virtual async Task<bool> Update<T>(T item, string updateQuery) where T : new()
{
try
{
if (_connection.State != ConnectionState.Open)
await _connection.OpenAsync();

using (SqlCommand sqlCommand = new SqlCommand(updateQuery, _connection))
{
sqlCommand.Parameters.Clear();
var properties = typeof(T).GetProperties();
foreach (var property in properties)
{
sqlCommand.Parameters.AddWithValue($"@{property.Name}", property.GetValue(item) ?? DBNull.Value);
}

int rowsAffected = await sqlCommand.ExecuteNonQueryAsync();
return rowsAffected > 0; // 如果有行受影响,则操作成功
}
}
catch (Exception)
{
// 将异常传播给调用层
throw;
}
finally
{
_connection.Close();
}
}

public virtual async Task<bool> Delete<T>(T item, string deleteQuery) where T : new()
{
try
{
if (_connection.State != ConnectionState.Open)
await _connection.OpenAsync();

using (SqlCommand sqlCommand = new SqlCommand(deleteQuery, _connection))
{
sqlCommand.Parameters.Clear();
var properties = typeof(T).GetProperties();
foreach (var property in properties)
{
sqlCommand.Parameters.AddWithValue($"@{property.Name}", property.GetValue(item) ?? DBNull.Value);
}

int rowsAffected = await sqlCommand.ExecuteNonQueryAsync();
return rowsAffected > 0; // 如果有行受影响,则操作成功
}
}
catch (Exception)
{
// 将异常传播给调用层
throw;
}
finally
{
_connection.Close();
}
}


}
}

调用代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SqlServerTest.DataBase
{

public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}

internal class test_Data_base
{
public static async void test()
{
string connectionString = "YourConnectionString";

// 创建 DataBase 实例
MDataBase dataBase = new MDataBase(connectionString);

// 查询示例
string selectQuery = "SELECT Id, Name, Age FROM People";
SqlParameter[] selectParameters = new SqlParameter[] { };
var dataSet = await dataBase.Select<Person>(selectQuery, selectParameters);
// 这里可以对返回的 DataSet 进行处理

// 插入示例
var person1 = new Person { Id = 1, Name = "John", Age = 30 };
var person2 = new Person { Id = 2, Name = "Jane", Age = 25 };
string insertQuery = "INSERT INTO People (Id, Name, Age) VALUES (@Id, @Name, @Age)";
bool insertSuccess = await dataBase.Insert(new List<Person> { person1, person2 }, insertQuery);
Console.WriteLine($"Insert success: {insertSuccess}");

// 更新示例
var updatePerson = new Person { Id = 1, Name = "John Doe", Age = 32 };
string updateQuery = "UPDATE People SET Name = @Name, Age = @Age WHERE Id = @Id";
bool updateSuccess = await dataBase.Update(updatePerson, updateQuery);
Console.WriteLine($"Update success: {updateSuccess}");

// 删除示例
var deletePerson = new Person { Id = 2 }; // 删除 ID 为 2 的记录
string deleteQuery = "DELETE FROM People WHERE Id = @Id";
bool deleteSuccess = await dataBase.Delete(deletePerson, deleteQuery);
Console.WriteLine($"Delete success: {deleteSuccess}");

}
}
}

  • 标题: 记一次C# Sql Server数据库处理
  • 作者: 菜企鹅
  • 创建于 : 2024-05-11 10:53:19
  • 更新于 : 2025-01-04 22:57:26
  • 链接: https://blog.cybersafezone.top/2024/05/11/记一次Csharp处理SqlServer/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
目录
记一次C# Sql Server数据库处理