winforms往SQL数据库写入数据的程序
时间: 2024-06-12 16:08:07 浏览: 11
以下是一个简单的WinForms往SQL数据库写入数据的程序:
1. 在Visual Studio中创建一个WinForms应用程序。
2. 在项目中添加一个SQL Server数据库,并创建一个名为“Person”的表,包括“ID”,“Name”和“Age”三列。
3. 在WinForms中添加一个DataGridView控件和三个TextBox控件,分别用于显示ID、Name和Age。
4. 在Form_Load事件中编写以下代码,以连接到数据库并将表中的数据加载到DataGridView中。
```csharp
private void Form1_Load(object sender, EventArgs e)
{
string connectionString = "Data Source=(local);Initial Catalog=MyDatabase;Integrated Security=True";
SqlConnection connection = new SqlConnection(connectionString);
string query = "SELECT ID, Name, Age FROM Person";
SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
DataTable table = new DataTable();
adapter.Fill(table);
dataGridView1.DataSource = table;
}
```
5. 在“Save”按钮的Click事件中编写以下代码,以将TextBox中输入的数据插入到表中。
```csharp
private void btnSave_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=(local);Initial Catalog=MyDatabase;Integrated Security=True";
SqlConnection connection = new SqlConnection(connectionString);
string query = "INSERT INTO Person (Name, Age) VALUES (@Name, @Age)";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@Name", txtName.Text);
command.Parameters.AddWithValue("@Age", txtAge.Text);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Data saved successfully!");
}
```
6. 运行程序并输入Name和Age,然后点击Save按钮,数据将被插入到数据库中,并在DataGridView中显示。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)