題組內容
第二題:
請利用 Java 程式或.NET 程式(可自行選擇 VB 或 C#語言,並在作答處標示清楚您選擇的語言)回答下 列問題:
請利用 Java 程式或.NET 程式(可自行選擇 VB 或 C#語言,並在作答處標示清楚您選擇的語言)回答下 列問題:
(二)承第(一)小題,如果此一資料庫中的資料表名稱為 Customer,我們要從這個資料表中讀取客 戶的名稱(欄位名稱為 name)及電話(欄位名稱為 tel),並把結果存在一個 resultSet 的物件中, 請撰寫此一程式片段。【6 分】
詳解 (共 1 筆)
詳解
這裡是使用 C# 語言撰寫的從 Customer 資料表中讀取 name 和 tel 欄位並將結果存儲在 SqlDataReader 中的程式片段。
csharp
複製程式碼
using System;
using System.Data.SqlClient;
複製程式碼
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;";
{
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);
SqlConnection connection = new SqlConnection(connectionString);
try
{
// 開啟資料庫連接
connection.Open();
Console.WriteLine("資料庫連接成功");
{
// 開啟資料庫連接
connection.Open();
Console.WriteLine("資料庫連接成功");
// 定義查詢字串
string query = "SELECT name, tel FROM Customer";
string query = "SELECT name, tel FROM Customer";
// 建立 SQL 命令物件
SqlCommand command = new SqlCommand(query, connection);
SqlCommand command = new SqlCommand(query, connection);
// 執行查詢並取得結果
SqlDataReader resultSet = command.ExecuteReader();
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("資料庫連接已關閉");
}
}
}
}
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("資料庫連接已關閉");
}
}
}
}