C#獲取資料庫select某一列的值
阿新 • • 發佈:2018-12-13
首先SqlConnection需要引入的名稱空間為System.Data.SqlClient
public static void OpenDateBase() { List<int> idList = new List<int>(); // 資料庫連線字串,database設定為自己的資料庫名,以Windows身份驗證 string constr = "server=IP,埠;database=資料庫;uid=sa;pwd=pwd"; // "data source=IP;initial catalog=資料庫名稱;user id=sa;pwd=pwd;pooling=false"; SqlConnection con = new SqlConnection(constr); string sql = " select ID from testTable"; SqlCommand com = new SqlCommand(sql, con); try { con.Open(); MessageBox.Show("成功連線資料庫"); SqlDataReader dr = com.ExecuteReader(); // 讀取記錄 while (dr.Read()) { idList.Add(dr.GetInt32(0));//獲取第一列所有值 //string str=dr["ServerName"].ToString();//接收一個返回值 } dr.Close(); } catch (Exception) { throw; } finally { con.Close(); MessageBox.Show("成功關閉資料庫連線", "提示資訊", MessageBoxButtons.OK); } }