SqlConnection con = new SqlConnection();
            con.ConnectionString = "Data Source=PHOEBE-PC;Initial Catalog=Mr_Liu_cs_design;Integrated Security=True";
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = string.Format("select COUNT(8)from  Mr_Liu_class2_type where t_type='{0}';", temp);
            cmd.Connection = con;
            con.Open();   //打开数据库连接
            int count = Convert.ToInt32(cmd.ExecuteScalar());
            if (count > 0)
            {
                MessageBox.Show("添加计量单位已存在");
            }
            else
            {
                cmd.CommandText = string.Format("insert into Mr_Liu_class2_type('{0}')", temp);
                cmd.ExecuteNonQuery();//用ExecuteNonQuery()的方法来执行查询语句
                MessageBox.Show("添加成功");
            }
            con.Close(); //关闭数据库的连接

解决方案 »

  1.   

    错误是 未将对象引用设置到对象的实例?temp 从哪里声明的,又是从哪里定义的呢?
      

  2.   


    cmd.CommandText = string.Format("select COUNT(8)from  Mr_Liu_class2_type where t_type='{0}';", temp); cmd.CommandText = string.Format("insert into Mr_Liu_class2_type('{0}')", temp);这两个temp可以共用??
      

  3.   

    请问楼主 哪里报错了?
    COUNT(8) from 聚合函数和FROM中间 加个空格试试
      

  4.   

    还有 在链接语句前边 加个 @Data Source=.;database=Mr_Liu_cs_design;Integrated Security=True";
      

  5.   

    前面有定义。   
    string temp;
                temp = this.textBox1.Text;
            用来装box的字符串的。
      

  6.   


    string c = "Data Source=PHOEBE-PC;Initial Catalog=Mr_Liu_cs_design;Integrated Security=True";
    using(SqlConnection con = new SqlConnection(c)
    )
    {
                               SqlCommand cmd = new SqlCommand();
                cmd.CommandText = string.Format("select COUNT(8)from  Mr_Liu_class2_type where t_type='{0}';", temp);
                cmd.Connection = con;
                con.Open();   //打开数据库连接
                int count = Convert.ToInt32(cmd.ExecuteScalar());
                if (count > 0)
                {
                    MessageBox.Show("添加计量单位已存在");
                }
                else
                {
                    cmd.CommandText = string.Format("insert into Mr_Liu_class2_type('{0}')", temp);
                    cmd.ExecuteNonQuery();//用ExecuteNonQuery()的方法来执行查询语句
                    MessageBox.Show("添加成功");
                }
    }楼主代码这样改下
      

  7.   

    呵呵我找到错误时我sql语句错了!!很感谢您们~~