How to connect to SQL Server with WPF?

In WPF, you can use ADO.NET to connect to SQL Server and perform operations. Here are the steps to connect to SQL Server.

  1. To add the necessary references: Right-click on the project in Visual Studio, select “Add” -> “Reference”, then choose the references for “System.Data” and “System.Data.SqlClient”.
  2. Add a button to the XAML file to trigger the connection operation. For example:
<Button Content="Connect" Click="Connect_Click" />
  1. Handle the button click event in the code. Add the following code in MainWindow.xaml.cs.
using System.Data.SqlClient;

private void Connect_Click(object sender, RoutedEventArgs e)
{
    string connectionString = "Data Source=your_server_name;Initial Catalog=your_database_name;User ID=your_username;Password=your_password";
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        try
        {
            connection.Open();
            MessageBox.Show("Connection successful!");
            // 连接成功后可以进行其他操作,例如执行SQL查询
        }
        catch (Exception ex)
        {
            MessageBox.Show("Connection failed: " + ex.Message);
        }
    }
}

In the connectionString, replace “your_server_name” with the name of your SQL Server instance, “your_database_name” with the name of the database you want to connect to, and “your_username” and “your_password” with your SQL Server username and password.

  1. Run the application and click the button to attempt to connect to SQL Server. If the connection is successful, a message box will pop up displaying “Connection successful!” Otherwise, a message indicating connection failure will be displayed.

The above are the basic steps for connecting to SQL Server. Once connected successfully, you can perform SQL queries, updates, and other operations as needed.

bannerAds