wpf怎么连接sqlserver写入表格数据

   2025-02-04 6320
核心提示:要在WPF应用程序中连接到SQL Server并写入表格数据,首先需要安装 NuGet 包 System.Data.SqlClient。然后,可以按照以下步骤进行

要在WPF应用程序中连接到SQL Server并写入表格数据,首先需要安装 NuGet 包 System.Data.SqlClient。然后,可以按照以下步骤进行操作:

在 XAML 文件中创建一个用于输入数据的表单。
<StackPanel>    <TextBox x:Name="txtName" Margin="5" Width="200" PlaceholderText="Name"/>    <TextBox x:Name="txtEmail" Margin="5" Width="200" PlaceholderText="Email"/>    <Button x:Name="btnSave" Content="Save" Click="btnSave_Click"/></StackPanel>
在代码文件中添加连接字符串和保存按钮的点击事件处理程序。
using System.Data.SqlClient;private string connectionString = "Data Source=YourServerName;Initial Catalog=YourDatabaseName;Integrated Security=True";private void btnSave_Click(object sender, RoutedEventArgs e){    string name = txtName.Text;    string email = txtEmail.Text;    using (SqlConnection connection = new SqlConnection(connectionString))    {        string query = "INSERT INTO YourTableName (Name, Email) VALUES (@Name, @Email)";        using (SqlCommand command = new SqlCommand(query, connection))        {            command.Parameters.AddWithValue("@Name", name);            command.Parameters.AddWithValue("@Email", email);            connection.Open();            command.ExecuteNonQuery();            connection.Close();        }    }}

在上述代码中,需要将 YourServerNameYourDatabaseNameYourTableName 替换为实际的 SQL Server 服务器名称、数据库名称和表格名称。

运行应用程序并填写表单数据,然后单击保存按钮即可将数据写入 SQL Server 表格。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言