在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!