要在WPF應(yīng)用程序中連接到SQL Server并寫入表格數(shù)據(jù),首先需要安裝 NuGet 包 System.Data.SqlClient
。然后,可以按照以下步驟進(jìn)行操作:
<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
替換為實(shí)際的 SQL Server 服務(wù)器名稱、數(shù)據(jù)庫名稱和表格名稱。