int count; 
            string ConnectionString = "server = (local) ; database = Test ; uid = sa ; pwd = xiaotuni";
            SqlConnection cn = new SqlConnection(ConnectionString);
            cn.Open();
            string CreateTableString = this.txtCreateTableString.Text; 
            SqlCommand cmd = new SqlCommand(CreateTableString, cn);
            count = cmd.ExecuteNonQuery();
                                       ~~~~~ 这个不是用来返回所受影响的行数,可是它返回一个 -1 不知道为什么.
            Response.Write(count);
            cn.Close();以上是创建表的代码
但是每次返回都是一个 -1 不知道为什么
但是在数据库里查看一下吧
又创建了此表.

解决方案 »

  1.   

    对于 UPDATE、INSERT 和 DELETE 语句,cmd.ExecuteNonQuery()
    返回值为该命令所影响的行数。对于其他所有类型的语句,返回值都为 -1所以不能根据返回值判断是否成功创建了表,而应该用try-catch语句尝试捕获异常
      

  2.   

    string ConnectionString = "server = (local) ; database = Test ; uid = sa ; pwd = xiaotuni";
            SqlConnection cn = new SqlConnection(ConnectionString);
            try
            {
                cn.Open();
                string CreateTableString = this.txtCreateTableString.Text;
                SqlCommand cmd = new SqlCommand(CreateTableString, cn);
                cmd.ExecuteNonQuery();
            }
            catch (System.Exception ex)
            {
                Response.Write(ex.Message);
            }
            finally
            {
                if(cn.State == ConnectionState.Open)
                    cn.Close();
            }