在C# WinForm中,可以使用ADO.NET或Entity Framework等技術(shù)進(jìn)行數(shù)據(jù)庫操作。這里我將介紹如何使用ADO.NET進(jìn)行數(shù)據(jù)庫操作。
首先,需要添加對System.Data和System.Data.SqlClient的引用。在項(xiàng)目中右鍵單擊“引用”,然后選擇“添加引用”,在彈出的窗口中找到并添加這兩個(gè)引用。
在代碼中,添加以下命名空間:
using System.Data;
using System.Data.SqlClient;
private SqlConnection CreateConnection()
{
string connectionString = "Server=your_server_name;Database=your_database_name;User Id=your_username;Password=your_password;";
SqlConnection connection = new SqlConnection(connectionString);
return connection;
}
請將your_server_name
、your_database_name
、your_username
和your_password
替換為實(shí)際的數(shù)據(jù)庫連接信息。
private DataTable ExecuteQuery(string query)
{
DataTable result = new DataTable();
using (SqlConnection connection = CreateConnection())
{
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
result.Load(reader);
}
}
}
return result;
}
private void btnLoadData_Click(object sender, EventArgs e)
{
string query = "SELECT * FROM your_table_name";
DataTable data = ExecuteQuery(query);
dataGridView1.DataSource = data;
}
請將your_table_name
替換為實(shí)際的表名。
private int ExecuteNonQuery(string query)
{
int rowsAffected = 0;
using (SqlConnection connection = CreateConnection())
{
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
rowsAffected = command.ExecuteNonQuery();
}
}
return rowsAffected;
}
private void btnInsert_Click(object sender, EventArgs e)
{
string query = "INSERT INTO your_table_name (column1, column2) VALUES ('value1', 'value2')";
int rowsAffected = ExecuteNonQuery(query);
MessageBox.Show("Rows affected: " + rowsAffected);
}
請根據(jù)實(shí)際情況修改表名、列名和值。
這樣,你就可以在C# WinForm應(yīng)用程序中使用ADO.NET進(jìn)行數(shù)據(jù)庫操作了。如果需要使用Entity Framework,可以參考官方文檔:https://docs.microsoft.com/en-us/ef/core/get-started/overview/first-app?tabs=netcore-cli