要在WPF应用程序中连接到SQL Server并写入表格数据,首先需要安装 NuGet 包 System.Data.SqlClient
。然后,可以按照以下步骤进行操作:
<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();
}
}
}
在上述代码中,需要将 YourServerName
、YourDatabaseName
和 YourTableName
替换为实际的 SQL Server 服务器名称、数据库名称和表格名称。