private void button3_Click(object sender, EventArgs e)
        {          
            for (int i = 0; i < this.dataGridView1.Rows.Count - 1; i++)
            {
                string a = dataGridView1.Rows[i].Cells[0].Value.ToString();
                string b = dataGridView1.Rows[i].Cells[1].Value.ToString();
                string c = dataGridView1.Rows[i].Cells[2].Value.ToString();
                insertdata(a,b,c);
            }
        }        public void insertdata(string s1, string s2, string s3)//插入数据库  
        {
            SqlConnection con = new SqlConnection("Data Source=10.168.1.5;Initial Catalog=data;User ID=sa;password=sa;Integrated Security=False");
            con.Open();
            SqlCommand cmd = new SqlCommand(string.Format("select Count(*) from newtable where a= '{0}'", s1), con);
            if ((int)cmd.ExecuteScalar() > 0)
            {
               listBox1.Items.Add(s1 + " 数据已经存在");
            }
            else
            {
                string sql = "insert into SC(Sno,Cno,score) values('" + s1 + "','" + s2 + "','" + s3 + "')";
                cmd.CommandText = sql;
                cmd.ExecuteNonQuery();
               listBox1.Items.Add(s1 + " 成功添加");
            }
            cmd.Dispose();
            con.Close();
        }  

解决方案 »

  1.   

    你要sql语句是insert没有问题,opeatedata这里直接就throw,这里应该调用SQL执行语句吧
      

  2.   


    那个方法是自己生成的。其他地方也用了执行sql的这个方法,但是不抛异常。这里为什么会抛啊
      

  3.   

    Quote: 引用 2 楼 wind_cloud2011 的回复:
    我需要多次用到插入的方法,每次列的数量不定。这样写太固定不好用啊
      

  4.   

    sql语句values后面没有反括号?下次再遇到这种问题,自己断点调试一下,把拼接后的SQL语句拿出来放数据库里执行一下就什么都明白了。每次SQL拼接有问题就找人来看也不是办法啊
      

  5.   


    拼接的sql在数据库里面可以正常插入,但在程序里还是抛这个异常
    我写了个类,放了这个方法
    目的是把dataGridView中的数据插入数据库,每次插入几列不一定。如果这个方法不行的话,麻烦告诉我怎么实现
    谢谢大家啦,还没法往下做。。
      

  6.   

    额,要不你把要存的数据 弄个DataSet  然后 写个存储过程,把ds 当XML参数传进去。。省得一条一条插入了。。
    比如这种
         
       public void InsertBudgetFee(DataTable dt, int index, Database db, DbTransaction transaction)
            {
                DataSet ds = new DataSet();
                ds.Tables.Add(dt);
                string proc = "";
                switch (index)
                {
                    case 1:
                        proc = "PA.InsertMainBudget";
                        break;
                    case 2:
                        proc = "PA.InsertOtherBudget";
                        break;
                }
              
                DbCommand cmd = db.GetStoredProcCommand(proc);
                db.AddInParameter(cmd, "pHeadId", DbType.String, KeyValue);
                db.AddInParameter(cmd, "pXml", DbType.Xml, ds.GetXml());
                db.AddInParameter(cmd, "pUserId", DbType.Int32, CurrentUser.UserID);
                db.ExecuteNonQuery(cmd, transaction);        }
      

  7.   

    你数据库连接串没给进去啊.
    程序怎么知道你想连哪个数据库?
    conn在new的时候将数据库连接字符串带进去