C#獲取數據庫select某一列的值

首先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);
            }
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章