日期:2014-05-18  浏览次数:21171 次

大神求救:C#中ExecuteScalar: Connection 属性尚未初始化的问题
程序功能主要是想从数据库中查询并统计学生总数,再将这个数插入到随机数产生器中,
进行从1-zh的数字产生(其中zh是一个变量)
但是一直说我没初始化,求解啊,同志们,我是菜鸟
   
  con.Open();
  String select1 = "select count(*) from student";
  SqlCommand cmd2 = new SqlCommand();
  cmd2.CommandText = select1;
  int zh = 0;
  zh = Convert.ToInt32(cmd2.ExecuteScalar()); //强制数据转换

  int suijishu = new Random().Next(1, zh);//随机数产生器

------解决方案--------------------
C# code
string queryString ="select count(*) as stuNum from student";
string connectionString = "server='(local)';database='mytable';uid='sa';pwd='sa'"; 
  using (SqlConnection connection = new SqlConnection( connectionString))
  {
  SqlCommand command = new SqlCommand( queryString, connection); 
      connection.Open();
  SqlDataReader reader = command.ExecuteReader();
  try
  {
  while (reader.Read())
  {
     int zh = 0;
    zh = Convert.ToInt32(reader["stuNum"]); //强制数据转换
  }
  }
  finally
  {
  // Always call Close when done reading.
  reader.Close();
  }