C#连接sql server代码

在C#中连接到SQL Server数据库,你可以使用System.Data.SqlClient命名空间中的SqlConnection类。以下是连接到SQL Server数据库的基本步骤和示例代码:

步骤 1: 引入命名空间

using System.Data.SqlClient; // 引入SQL Server连接命名空间

步骤 2: 创建连接字符串

连接字符串包含了连接到数据库所需的所有信息,如服务器地址、数据库名称、认证信息等。

string connectionString = @"Server=L5318819A251\SQLEXPRESS;Database=BooKMS;Integrated Security=True;";

这里的连接字符串包括:

  • Server:指定了SQL Server实例的地址,\SQLEXPRESS是实例名称。
  • Database:指定了要连接的数据库名称。
  • Integrated Security:设置为True表示使用Windows身份验证。

步骤 3: 创建并打开连接

使用连接字符串创建SqlConnection对象,然后打开这个连接。

SqlConnection conn = new SqlConnection(connectionString);
try
{
    conn.Open();
    if (conn.State == ConnectionState.Open)
    {
        Console.WriteLine("Connection successful!");
        // 执行数据库操作...
    }
}
catch (Exception ex)
{
    Console.WriteLine("An error occurred while connecting to the database: " + ex.Message);
}

步骤 4: 执行数据库操作

一旦连接打开,你可以执行SQL命令或查询,例如使用SqlCommand对象。

SqlCommand cmd = new SqlCommand("SELECT * FROM YourTable", conn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
    // 处理每一行数据...
    Console.WriteLine(reader["YourColumnName"].ToString());
}
reader.Close();
步骤 5: 关闭连接
完成数据库操作后,不要忘记关闭连接和释放资源。

示例代码

这是一个简单的示例,演示了如何连接到SQL Server并从表中读取数据:

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = @"Server=L5318819A281\SQLEXPRESS;Database=BooKMS;Integrated Security=True;";
        
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            try
            {
                conn.Open();
                Console.WriteLine("Connected to the database successfully!");

                string sql = "SELECT * FROM YourTable";
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            // 替换YourColumnName为你的表中的列名
                            Console.WriteLine(reader["YourColumnName"].ToString());
                        }
                    }
                }
            }
            catch (SqlException e)
            {
                Console.WriteLine("Error: " + e.Message);
            }
        }
    }
}

  • 6
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值