c#获取sql的表中的ID最大值并赋值给一个变量的问题

string Constr = "server = 192.168.1.25;database = csmedia;uid = sa;pwd = 123456ab;Connection Timeout=5";
SqlConnection conn = new SqlConnection(Constr);
conn.Open();
//读取lxname表中的id最大值
SqlCommand cmd2 = new SqlCommand("select max(ID) as sid from lxname",conn );
//string maxid="select max(ID) as sid from lxname";
//将最大值复制给变量mid
string mid = cmd2.ExecuteReader().ToString();

              string strSql = "insert into lxname(name,sfkl,lrrq) values('"+textBox1.Text +"','0',GetDate())";
              string sql1 = "insert into lxdizhi(dizhiID) values ('"+mid+"')";
            //sql1 += "insert into lxdizhi(dizhiID,dizhi)values('"+mid+"','"+lxpd2+"')";
            //sql1 += "insert into lxdizhi(dizhiID,dizhi)values('"+mid+"','"+lxpd3+"')";
            SqlCommand cmd = conn.CreateCommand ();
            cmd.CommandText = strSql;
            cmd.ExecuteNonQuery();
            cmd.CommandText = sql1;
            cmd.ExecuteNonQuery();
            conn.Close();

                        运行后老师提示错误,由于我是新手,查了好多资料也不知道为什么,求各位大神不吝赐教!

3个回答

 string mid = cmd2.ExecuteScalar().ToString();

command的 方法用的不对吧 ,我记得不是这个,有一个方法获取的是 获取第一行第一列的值



你试试下面这个,如果不行可能是需要你重新建立连接

     string Constr = "server = 192.168.1.25;database = csmedia;uid = sa;pwd = 123456ab;Connection Timeout=5";
     string maxid="select max(ID) as sid from lxname";
     string strSql = "insert into lxname(name,sfkl,lrrq) values('"+textBox1.Text +"','0',GetDate())";
    string sql1 = "insert into lxdizhi(dizhiID) values ('"+mid+"')";
    SqlConnection conn = new SqlConnection(Constr);
    SqlCommand cmd = conn.CreateCommand ();
    cmd.CommandText =maxid;
    conn.Open();
    string mid = cmd2.ExecuteReader().ToString();
     cmd2 = new SqlCommand(strSql,conn );
     cmd.ExecuteNonQuery();
      cmd2 = new SqlCommand(sql1 ,conn );
     cmd.ExecuteNonQuery();
     conn.Close();
立即提问