這裡是使用 C# 語言撰寫的從 Customer 資料表中讀取 name 和 tel 欄位並將結果存儲在 SqlDataReader 中的程式片段。
csharp
複製程式碼
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
// 定義 SQL Server 的連接字串
string connectionString = "Server=your_server_address;Database=your_database_name;User Id=your_username;Password=your_password;";
// 建立 SQL 連接物件
SqlConnection connection = new SqlConnection(connectionString);
try
{
// 開啟資料庫連接
connection.Open();
Console.WriteLine("資料庫連接成功");
// 定義查詢字串
string query = "SELECT name, tel FROM Customer";
// 建立 SQL 命令物件
SqlCommand command = new SqlCommand(query, connection);
// 執行查詢並取得結果
SqlDataReader resultSet = command.ExecuteReader();
// 讀取並顯示結果
while (resultSet.Read())
{
string name = resultSet["name"].ToString();
string tel = resultSet["tel"].ToString();
Console.WriteLine($"Name: {name}, Tel: {tel}");
}
// 關閉資料集
resultSet.Close();
}
catch (Exception ex)
{
// 捕捉連接錯誤
Console.WriteLine("資料庫連接或查詢失敗: " + ex.Message);
}
finally
{
// 關閉資料庫連接
if (connection.State == System.Data.ConnectionState.Open)
{
connection.Close();
Console.WriteLine("資料庫連接已關閉");
}
}
}
}