摘要:C#連線資料庫_ Connected
1.加入參考
using System.Data.SqlClient;
加密的引用using System.Web.Security;
2.
///
/// 載入所有欄位標題
///
// sql Select...
try
{
using (SqlConnection conn = new SqlConnection(Settings.Default.NWconnStr))
{
conn.Open();
using (SqlCommand command = new SqlCommand("select * from Customers", conn))
{
using (SqlDataReader dataReader = command.ExecuteReader())
{
//存進contryTableName裡面
DataTable contryTableName = dataReader.GetSchemaTable();
//測試丟到DatagridView
this.dataGridView1.DataSource = contryTableName;
for (int i = 0; i < contryTableName.Rows.Count; i++)
{
this.listView1.Columns.Add(contryTableName.Rows[i][0].ToString());
}
this.listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
}
}
}//end using sqlConnection
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
3.載入欄位的值
///
/// 載入欄位的值
///
private void loadCountrysToComboBox()
{
// sql Select...
try
{
using (SqlConnection conn = new SqlConnection(Settings.Default.NWconnStr))
{
conn.Open();
using (SqlCommand command = new SqlCommand("select distinct Country from Customers", conn))
{
using (SqlDataReader dataReader = command.ExecuteReader())
{
while (dataReader.Read())
{
this.comboBox1.Items.Add(dataReader[0]);
}
}
}
}//end using sqlConnection
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}