温馨提示×

c# string怎么连接数据库

c#
小樊
81
2024-10-18 18:29:30
栏目: 编程语言

在C#中,可以使用ADO.NET或Entity Framework等库来连接数据库并执行SQL查询以连接字符串。以下是使用ADO.NET连接数据库并执行SQL查询的示例代码:

using System;
using System.Data;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "your_connection_string_here";
        string sql = "SELECT * FROM your_table_here";

        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand(sql, conn);
                SqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    Console.WriteLine(string.Format("{0}", reader[0]));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

在上面的示例中,connectionString变量包含用于连接到数据库的连接字符串,sql变量包含要执行的SQL查询。使用SqlConnection对象打开数据库连接,并使用SqlCommand对象执行SQL查询。使用SqlDataReader对象读取查询结果并将其打印到控制台上。

0