在C#中操作LocalDB時,以下是一些有用的技巧:
string connectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Integrated Security=True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// 執行數據庫操作
}
string sql = "INSERT INTO MyTable (Name, Age) VALUES (@Name, @Age)";
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@Name", "John Doe");
command.Parameters.AddWithValue("@Age", 30);
command.ExecuteNonQuery();
}
string sql = "SELECT * FROM MyTable";
using (SqlCommand command = new SqlCommand(sql, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
string name = reader["Name"].ToString();
int age = reader["Age"].ToInt32();
Console.WriteLine($"Name: {name}, Age: {age}");
}
}
}
希望這些技巧能幫助你更好地在C#中操作LocalDB!