在C#項目中管理SQL Server連接,通常遵循以下步驟:
using System.Data;
using System.Data.SqlClient;
public static SqlConnection CreateConnection(string connectionString)
{
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
return connection;
}
using
語句確保連接正確關閉:string connectionString = "your_connection_string";
using (SqlConnection connection = CreateConnection(connectionString))
{
// 在這里執行你的數據庫操作
}
public static DataTable ExecuteQuery(SqlConnection connection, string query)
{
DataTable result = new DataTable();
using (SqlCommand command = new SqlCommand(query, connection))
{
SqlDataReader reader = command.ExecuteReader();
result.Load(reader);
}
return result;
}
string connectionString = "your_connection_string";
using (SqlConnection connection = CreateConnection(connectionString))
{
string query = "SELECT * FROM your_table";
DataTable result = ExecuteQuery(connection, query);
// 處理查詢結果
}
public static int ExecuteNonQuery(SqlConnection connection, string query, params SqlParameter[] parameters)
{
int rowsAffected;
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddRange(parameters);
rowsAffected = command.ExecuteNonQuery();
}
return rowsAffected;
}
string connectionString = "your_connection_string";
using (SqlConnection connection = CreateConnection(connectionString))
{
string query = "INSERT INTO your_table (column1, column2) VALUES (@value1, @value2)";
SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter("@value1", "your_value1"),
new SqlParameter("@value2", "your_value2")
};
int rowsAffected = ExecuteNonQuery(connection, query, parameters);
// 處理影響的行數
}
通過遵循這些步驟,你可以在C#項目中有效地管理SQL Server連接。記住始終使用參數化查詢以防止SQL注入攻擊,并確保在不再需要時正確關閉連接。