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

各位大侠给我看看啊 我是新手 真心求教!

  private void buttonX1_Click(object sender, EventArgs e)
  {
   

  textBoxX3.Enabled = true;
  textBoxX4.Enabled = true;
  textBoxX5.Enabled = true;
  textBoxX6.Enabled = true;
  textBoxX7.Enabled = true;
  textBoxX8.Enabled = true;
   
   
  dt=mymeans.getDataTable("select * from tb_student where StuId='" + textBoxX1.Text + "'");
   
  if (dt.Rows.Count == 0)
  {
  MessageBox.Show("您好!您输入的学号不正确或者不存在该学生信息!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  textBoxX1.Text = "";
  textBoxX1.Focus();
  }
  else
  {
  dt = mymeans.getDataTable("select * from tb_student where StuId='" + textBoxX1.Text + "'");

  textBoxX2.Text = dt.Rows[0].ItemArray[0].ToString();
  textBoxX3.Text = dt.Rows[0].ItemArray[1].ToString();
  textBoxX4.Text = dt.Rows[0].ItemArray[2].ToString();
  textBoxX8.Text = dt.Rows[0].ItemArray[3].ToString();
  textBoxX5.Text = dt.Rows[0].ItemArray[4].ToString();
  textBoxX6.Text = dt.Rows[0].ItemArray[5].ToString();
  textBoxX7.Text = dt.Rows[0].ItemArray[7].ToString();
  textBoxX9.Text = dt.Rows[0].ItemArray[8].ToString();
  string sql = ("select Photo from tb_student where StuId='"+textBoxX1.Text+"'");
  SqlCommand cmd = new SqlCommand(sql, MyMeans.My_conn);
   
   
  byte[] b = (byte[])cmd.ExecuteScalar();
  if (b.Length > 0)
  {
  MemoryStream stream = new MemoryStream(b,true);
  stream.Write(b,0,b.Length);
  pictureBox1.Image = new Bitmap(stream);
  stream.Close();
  }



  mymeans.conn_close();
  }
   
   
  }


问题补充:不加:cmd.Connection.Open(); 错误:ExecuteScalar 要求已打开且可用的 Connection。连接的当前状态为已关闭


加:cmd.Connection.Open(); 错误:ConnectionString 属性尚未初始化。

------解决方案--------------------
连接字符串就是一个字符串嘛,样式类似string strConn = "Data Source=127.0.0.1;Initial Catalog=Northwind;User ID=sa;Password=";
里边四个参数,你自己根据你的数据库进行设置就行了,比如把Northwind换成master。
另外,这个字符串也可以从webconfig获取。
------解决方案--------------------
一般连接数据库是使用如下步骤

1、先建立connection:
SqlConnection conn = new SqlConnection(connStr);
//这里connStr是连接字符串,根据数据库不同略有不同,一般只要网上搜索一下就能知道。
//注:SQL以外的数据库,用ODBC连接的,一般用OleDbConnection,或者有些数据库有独立的第三方.NET库,但用法都是一样的。
2、打开连接
conn.Open(); //打开数据库连接,这句执行完以后就相当于一个用户登录数据库了,用户一般在connStr里确定
3、建立Command
SqlCommand cmd = conn.CreateCommand();
或SqlCommand = new SqlCommand(CommandText,conn);
ADO.NET中SqlCommand有多种初始化方法,但最终都要和一个已经打开的数据库连接绑定才能发挥作用。
cmd.CommandText = "SELECT * FROM xxx WHERE name=@name"; //这里可以指定SQL语句,SQL的语法根据数据库不同而不同
cmd.Parameter.Add("@name",SqlDbType.NVarChar,50).