在WinForm應用程序中,進行數據庫的增刪改查操作通常需要使用ADO.NET(ActiveX Data Objects.NET)來實現。ADO.NET提供了一系列的類和方法,可以方便地與數據庫進行交互。
常用的數據庫操作方法如下:
string connectionString = "Data Source=YourServer;Initial Catalog=YourDatabase;Integrated Security=True";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
string query = "SELECT * FROM YourTable";
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// 處理查詢結果
}
reader.Close();
string insertQuery = "INSERT INTO YourTable (Column1, Column2) VALUES (@Value1, @Value2)";
SqlCommand insertCommand = new SqlCommand(insertQuery, connection);
insertCommand.Parameters.AddWithValue("@Value1", value1);
insertCommand.Parameters.AddWithValue("@Value2", value2);
insertCommand.ExecuteNonQuery();
string updateQuery = "UPDATE YourTable SET Column1 = @NewValue WHERE Column2 = @Condition";
SqlCommand updateCommand = new SqlCommand(updateQuery, connection);
updateCommand.Parameters.AddWithValue("@NewValue", newValue);
updateCommand.Parameters.AddWithValue("@Condition", condition);
updateCommand.ExecuteNonQuery();
string deleteQuery = "DELETE FROM YourTable WHERE Column1 = @Value";
SqlCommand deleteCommand = new SqlCommand(deleteQuery, connection);
deleteCommand.Parameters.AddWithValue("@Value", value);
deleteCommand.ExecuteNonQuery();
在實際應用中,需要根據具體情況來調用這些方法,以實現數據庫的增刪改查操作。同時,為了保證數據庫操作的安全性和效率,建議使用參數化查詢,避免SQL注入攻擊,并且及時關閉數據庫連接以釋放資源。