溫馨提示×

怎么使用c#連接數據庫

小億
96
2024-04-18 14:06:08
欄目: 編程語言

要使用C#連接數據庫,首先需要引用適當的命名空間(例如System.Data.SqlClient)并創建一個數據庫連接對象。然后可以使用該連接對象打開數據庫連接,并執行SQL查詢或命令。

以下是一個簡單的示例代碼,演示如何使用C#連接到一個SQL Server數據庫并執行一個查詢:

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "Data Source=yourServerAddress;Initial Catalog=yourDatabase;User ID=yourUsername;Password=yourPassword";
        
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            
            string sqlQuery = "SELECT * FROM yourTable";
            SqlCommand command = new SqlCommand(sqlQuery, connection);
            
            SqlDataReader reader = command.ExecuteReader();
            
            while (reader.Read())
            {
                Console.WriteLine(reader["columnName"].ToString());
            }
            
            reader.Close();
        }
    }
}

請注意,上述示例中的數據庫連接字符串應替換為實際的數據庫連接信息。另外,還應注意錯誤處理和資源釋放,以確保連接的正確關閉和清理。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女