当前位置:首页 > 技术 > 正文内容

C# 中使用 SqlConnection 操作 SQL Server 数据库

访客 技术 2026年7月27日 4

连接字符串配置与解析

在 C# 中连接 SQL Server 时,需正确构造连接字符串。常见两种认证方式:

  • SQL Server 身份验证(显式用户名密码):
    string connStr = "Server=.;Database=TestDB;User Id=sa;Password=123456";
    可简写为:
    Server=.;Database=TestDB;Uid=sa;Pwd=123456;
  • Windows 身份验证(集成安全):
    string connStr = "Server=.;Database=TestDB;Integrated Security=SSPI";
    或使用等效写法:
    Trusted_Connection=True;

说明:

  • Server 等同于 Data Source
  • Database 等同于 Initial Catalog
  • UidUser IdPwdPassword 对应
  • 本地服务器可用 .localhost 表示;远程则需指定 IP 地址或主机名及端口
  • 连接字符串中的键值对不区分大小写

配置文件管理连接字符串

推荐将连接字符串存入应用配置文件中。

1. 通过 <connectionStrings> 节点存储(推荐)

<configuration>
  <connectionStrings>
    <add name="DbConnection" 
         connectionString="Server=.;Database=MyAppDB;Uid=admin;Pwd=securePass;" 
         providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

2. 通过 <appSettings> 节点存储

<appSettings>
  <add key="DbConnString" value="Server=.;Database=MyAppDB;Uid=admin;Pwd=securePass;" />
</appSettings>

读取配置信息

需引用 System.Configuration 并添加命名空间:

using System.Configuration;

读取方式如下:

// 从 connectionStrings 节点读取
string connString = ConfigurationManager.ConnectionStrings["DbConnection"].ConnectionString;

// 从 appSettings 节点读取
string connString = ConfigurationManager.AppSettings["DbConnString"];

创建数据库连接实例

// 推荐方式:直接传入连接字符串
SqlConnection dbConnection = new SqlConnection(connString);

// 或分步设置
SqlConnection dbConnection = new SqlConnection();
dbConnection.ConnectionString = connString;

资源自动释放:使用 using 语句

SqlConnection 实现了 IDisposable 接口,建议使用 using 确保连接及时关闭:

using (var connection = new SqlConnection(connString))
{
    connection.Open();
    // 执行数据库操作...
}
// 连接在此处自动释放,状态为 Closed
Console.WriteLine(connection.State); // 显示:Closed

配置文件加密保护

防止敏感信息泄露,可对配置节进行加密:

Configuration config = ConfigurationManager.OpenExeConfiguration("YourApp.exe");
ConnectionStringsSection section = config.GetSection("connectionStrings") as ConnectionStringsSection;

if (section.SectionInformation.IsProtected)
{
    section.SectionInformation.UnprotectSection(); // 解密
}
else
{
    section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider"); // 加密
}

config.Save(); // 保存更改

性能测试:使用 Stopwatch 测量执行时间

Stopwatch timer = new Stopwatch();
timer.Start();

// 待测代码段
for (int i = 0; i < 100000; i++) { /* 模拟操作 */ }

timer.Stop();
Console.WriteLine($"耗时:{timer.ElapsedMilliseconds} 毫秒");

SqlCommand 命令对象操作

用于执行 SQL 语句或存储过程。

核心属性

  • Connection:关联的数据库连接对象
  • CommandText:要执行的 T-SQL 语句或存储过程名称
  • CommandType:可选 Text(默认)或 StoredProcedure
  • Parameters:参数集合,支持动态传参
  • Transaction:绑定事务上下文

创建命令对象的推荐方式

// 推荐:直接传入 SQL 和连接
SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE Age > @age", connection);

// 或通过连接创建
SqlCommand cmd2 = connection.CreateCommand();
cmd2.CommandText = "INSERT INTO Logs VALUES (@msg)";
cmd2.Parameters.AddWithValue("@msg", "System started");

// 事务场景
string deleteSql = "DELETE FROM Employees WHERE DeptId = @dept";
SqlCommand cmd3 = new SqlCommand(deleteSql, connection, transaction);

SqlParameter 参数化处理

防止注入攻击,必须使用参数化查询。

常用属性

  • ParameterName:参数占位符,如 @username
  • Value:实际传入值
  • DbType:对应数据库字段类型(如 VarChar, Int
  • Size:最大长度(单位:字节)
  • Direction:输入/输出/返回值等方向

参数声明方式

// 1. 构造后赋值
SqlParameter param1 = new SqlParameter();
param1.ParameterName = "@name";
param1.SqlDbType = SqlDbType.VarChar;
param1.Size = 50;
param1.Value = "Alice";

// 2. 直接初始化名称和值
SqlParameter param2 = new SqlParameter("@age", 25);

// 3. 指定名称和数据类型
SqlParameter param3 = new SqlParameter("@deptId", SqlDbType.Int);
param3.Value = 3;

// 4. 包含大小和类型
SqlParameter param4 = new SqlParameter("@pwd", SqlDbType.VarChar, 32);
param4.Value = "secret123";

// 5. 带源列映射(用于 DataTable)
SqlParameter param5 = new SqlParameter("@userName", SqlDbType.VarChar, 20, "UserName");

SqlDataReader 读取数据流

提供高效、只进、只读的数据读取方式,适用于批量读取。

特点与限制

  • 只能向前读取,无法回滚
  • 轻量级,性能高,适合小到中等规模数据集
  • 持续占用数据库连接,务必及时关闭
  • 不可修改数据,仅用于读取

使用方法

using (var reader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
    while (reader.Read())
    {
        string name = reader["Name"].ToString();
        int age = reader.GetInt32("Age");
        // 处理每一行数据
    }
}
// 读取完成后,连接自动关闭

关键注意事项

  • 调用 Read() 返回 false 表示无更多数据
  • 若提前终止读取,应先调用 Cancel() 再关闭 Close()
  • 获取存储过程的输出参数前,必须先关闭 DataReader

常用属性

  • FieldCount:当前行包含的列数
  • HasRows:是否至少有一行数据
  • IsClosed:读取器是否已关闭
  • [index]:按列索引访问数据(如 reader[0]
  • [columnName]:按列名访问数据(如 reader["Email"]

相关文章

Linux crontab 详解

1) crontab 是什么cron 是 Linux 的定时任务守护进程;crontab 是用来编辑/查看“按时间周期执行命令”的表(cron table)。常见两类:用户 crontab:每个用户一份(crontab -e 编辑)系统级 crontab / cron.d:可指定执行用户(/etc/crontab、/etc/cron.d/*)2) crontab 时间...

富文本里可以允许的 HTML 属性

一、所有标签默认允许的安全属性(极少)class        (可选)id           (通常建议禁用)title️ 注意:id 容易被滥用做锚点注入,很多系统直接禁用class 允许的话最好只允许固定前缀(如 editor-*)二、a 标签允许属性<a href="" t...

Dom\HTML_NO_DEFAULT_NS 的副作用:自动加闭合标签

在使用Dom\HTMLDocument时,Dom\HTML_NO_DEFAULT_NS 将禁止在解析过程中设置元素的命名空间, 此设置是为了与DOMDocument向后兼容而存在的。当使用它时,已知的一个副作用就是:自动加闭合标签例如 </img> 为什么会这样?当你使用:Dom\HTML_NO_DEFAULT_NS文档会变成 无命名空间模式,此时内部更接近 XML...

Laravel 事件和监听器创建

在 Laravel 中,使用 Artisan 命令创建 Events(事件) 和 Listeners(监听器) 是非常高效的。你可以通过以下几种方式来实现:1. 手动创建单个 Event如果你只想创建一个事件类,可以使用 make:event 命令:Bashphp artisan make:event UserRegistered执行后,文件将生成在 app/Even...

自定义域名解析神器 dnsmasq

什么是 dnsmasq?dnsmasq 是一个轻量级、功能强大的网络服务工具,专为小型和中等规模网络设计。它是一个综合的网络基础设施解决方案[1]。dnsmasq 能做什么?功能说明应用场景DNS 转发与缓存将 DNS 查询转发到上游服务器(ISP、Google DNS 等),并在本地缓存结果加快 DNS 查询速度,减少外部 DNS 流量本地 DNS解析本地网络设备的主机名,无需编辑&n...

linux screen 用法详情 (nohup 的替代方案)

一、screen 是什么?能干嘛?screen 是一个终端复用器,可以:在一个 SSH 会话中开多个“虚拟终端”SSH 断线后,程序仍然在后台运行随时重新连接到原来的会话特别适合:nohup 的替代方案跑脚本 / 爬虫 / 训练模型运维、远程开发二、安装 screen# CentOS / Rocky / Almayum install -y screen# Debian / Ubuntuapt i...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。