溫馨提示×

c# string怎么連接數(shù)據(jù)庫

c#
小樊
81
2024-10-18 18:29:30
欄目: 編程語言

在C#中,可以使用ADO.NET或Entity Framework等庫來連接數(shù)據(jù)庫并執(zhí)行SQL查詢以連接字符串。以下是使用ADO.NET連接數(shù)據(jù)庫并執(zhí)行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變量包含用于連接到數(shù)據(jù)庫的連接字符串,sql變量包含要執(zhí)行的SQL查詢。使用SqlConnection對象打開數(shù)據(jù)庫連接,并使用SqlCommand對象執(zhí)行SQL查詢。使用SqlDataReader對象讀取查詢結(jié)果并將其打印到控制臺上。

0