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

新手求指导
private void button1_Click(object sender, EventArgs e)
  {
  int k=1;
  string o = comboBox1.Text;
  string s = comboBox2.Text;
  string h = comboBox3.Text;
  string x = "["+o + "," + s + "," + h+"]";
  string tabName = "[STUDENT].[dbo].[Sheet1$]"; //欲插入列的表名
  string colName = x; //插入列的列名
  string sqlStr = "alter table " + tabName + " add " + colName + " char(20) null";

  //实例化sql连接
  SqlConnection c = new SqlConnection("Server=(local);Integrated Security=SSPI;database=student");
  c.Open();

  //实例化sql命令
  SqlCommand cmd = new SqlCommand(sqlStr, c);

  //执行sql命令
  cmd.ExecuteNonQuery();

  //关闭连接
  c.Close();

   
  for (int i = 0; i < dataGridView1.Rows.Count; i++)
  {
  if (Convert.ToBoolean(dataGridView1.Rows[i].Cells[0].Value) == true)
  {
  string add = "insert into " + tabName + colName+"values" + k;
  SqlConnection M = new SqlConnection("Server=(local);Integrated Security=SSPI;database=student");
  c.Open();
  SqlCommand cad = new SqlCommand(add,M);
  cmd.ExecuteNonQuery();
  c.Close();
  }
   
  }
为什么会出现这个问题
各表中的列名必须唯一。在表 'STUDENT.dbo.Sheet1$' 中多次指定了列名'2011,1,5'

------解决方案--------------------
SqlConnection M = new SqlConnection("Server=(local);Integrated Security=SSPI;database=student");
c.Open();//这里应该是M.Open();
SqlCommand cad = new SqlCommand(add,M);
cmd.ExecuteNonQuery();//这里应该是cad.ExecuteNonQuery();
c.Close();//这里是M.colse();
cad不是cmd你自己看清楚啊
在最后的地方 你调用了上面的cmd而不是你的cad