在Winform应用程序中连接SQL数据库,通常可以使用以下步骤:
以下是一个示例代码,演示如何在Winform应用程序中连接SQL数据库:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WinformApp
{
public partial class Form1 : Form
{
private SqlConnection sqlConnection;
public Form1()
{
InitializeComponent();
InitializeSqlConnection();
}
private void InitializeSqlConnection()
{
string connectionString = "Data Source=YourServerAddress;Initial Catalog=YourDatabaseName;User ID=YourUsername;Password=YourPassword";
sqlConnection = new SqlConnection(connectionString);
try
{
sqlConnection.Open();
MessageBox.Show("Connection successful");
}
catch (Exception ex)
{
MessageBox.Show("Connection failed: " + ex.Message);
}
}
private void ExecuteQuery()
{
string query = "SELECT * FROM YourTableName";
SqlCommand sqlCommand = new SqlCommand(query, sqlConnection);
SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCommand);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
// Display query result in a DataGridView
dataGridView1.DataSource = dataTable;
}
private void button1_Click(object sender, EventArgs e)
{
ExecuteQuery();
}
}
}
在上面的示例代码中,我们首先创建一个SqlConnection对象并打开数据库连接。然后定义了一个执行查询的方法ExecuteQuery(),该方法中执行了一个简单的SELECT查询语句,并将结果显示在一个DataGridView中。最后,通过按钮的Click事件调用ExecuteQuery()方法来执行查询操作。