c# sql server 访问增删改查公共类
时间: 2023-09-12 14:07:11 浏览: 106
以下是一个简单的 C# SQL Server 访问增删改查公共类的示例:
```csharp
using System;
using System.Data;
using System.Data.SqlClient;
public static class SqlHelper
{
private static string connectionString = "Data Source=yourServerName;Initial Catalog=yourDatabaseName;Integrated Security=True";
public static DataTable ExecuteDataTable(string sql)
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
}
}
return dt;
}
public static int ExecuteNonQuery(string sql)
{
int affectedRows = 0;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
affectedRows = cmd.ExecuteNonQuery();
}
}
return affectedRows;
}
public static object ExecuteScalar(string sql)
{
object result = null;
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
result = cmd.ExecuteScalar();
}
}
return result;
}
}
```
这个公共类包含了三个静态方法:
1. `ExecuteDataTable`:执行查询语句并返回一个 DataTable 对象。
2. `ExecuteNonQuery`:执行增删改语句并返回受影响的行数。
3. `ExecuteScalar`:执行查询语句并返回单个结果。
你可以使用这些方法来执行 SQL Server 数据库的基本操作。例如,使用 `ExecuteNonQuery` 方法来执行一个插入语句:
```csharp
string insertSql = "INSERT INTO MyTable (Name, Age) VALUES ('John', 30)";
int affectedRows = SqlHelper.ExecuteNonQuery(insertSql);
```
使用 `ExecuteDataTable` 方法来执行一个查询语句并返回一个 DataTable 对象:
```csharp
string selectSql = "SELECT * FROM MyTable";
DataTable dt = SqlHelper.ExecuteDataTable(selectSql);
foreach (DataRow row in dt.Rows)
{
Console.WriteLine("Name: {0}, Age: {1}", row["Name"], row["Age"]);
}
```
使用 `ExecuteScalar` 方法来执行一个查询语句并返回单个结果:
```csharp
string countSql = "SELECT COUNT(*) FROM MyTable";
int count = (int)SqlHelper.ExecuteScalar(countSql);
Console.WriteLine("Total rows: {0}", count);
```
阅读全文