Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
在C#中連接SQL數據庫,使用ADO.NET庫中的類和類。本篇介紹如何連接到SQL Server數據庫并執行一個簡單的查詢。
首先,確保項目已經引入了System.Data.這個命名空間。
完整示例代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace LinkDatabase
{
internal class Program
{
static void Main(string[] args)
{

// 連接字符串,這里替換成你的數據庫信息
string connectionString = "Data Source=192.168.1.2;Initial Catalog=School;User ID=sa;Password=00000";
// 創建SqlConnection對象
using (SqlConnection connection = new SqlConnection(connectionString))
{
// 打開連接
connection.Open();
// SQL查詢語句,這里可以替換成你自己的查詢
string sql = "SELECT * FROM SchoolInfo";
// 創建SqlCommand對象
using (SqlCommand command = new SqlCommand(sql, connection))
{
// 執行查詢,并將結果存儲在SqlDataReader對象中
using (SqlDataReader reader = command.ExecuteReader())
{
// 讀取結果并打印

while (reader.Read())
{
Console.WriteLine("{0}, {1}", reader[0], reader[1]);
}
}
}
}
}
}
}
運行結果
這個例子是一個最基礎的數據庫連接和查詢的例子。在實際開發中,可能需要考慮更多其他的因素,例如錯誤處理、數據庫連接的關閉和重用、參數化查詢等等。
*請認真填寫需求信息,我們會在24小時內與您取得聯系。