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

猜你喜欢

转载自blog.csdn.net/qq_40433102/article/details/84984762