在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()方法來執行查詢操作。