excel错误[教学-解决方案]
这问题是因为你没把Parameter清除,记得每次的execute command时,都需要放进新的parameter。
来看看下面的范例。
The sqlparameter is already contained by another sqlparametercollection c#
The OleDbParameter is already contained by another OleDbParameterCollection
我的Excel有Sheet 1和 Sheet 2,这两个sheet都有CarId 和 CarDesc Column
请试试看吧。- private string strConnString = "Provider=Microsoft.ACE.OLEDB.12.0" +
- ";Data Source=" + Application.StartupPath + "\\Database.xls" +
- ";Extended Properties=Excel 12.0;";
- private OleDbConnection DbConn = new OleDbConnection();
- private void createConn()
- {
- try
- {
- DbConn.ConnectionString = strConnString;
- DbConn.Open();
- }
- catch (Exception exp)
- {
- throw exp;
- }
- }
- private void Add_Records(string sSQL, ArrayList parameters)
- {
- try
- {
- if (DbConn.State == 0)
- createConn();
- using (OleDbCommand sqlCmd = new OleDbCommand("", DbConn))
- {
- sqlCmd.CommandText = sSQL;
- foreach (OleDbParameter param in parameters)
- sqlCmd.Parameters.Add(param);
- sqlCmd.ExecuteNonQuery();
- }
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- finally
- {
- DbConn.Close();
- }
- }
- private void btnSave_Click(object sender, EventArgs e)
- {
- try
- {
- string sSqlSheet1 = "INSERT INTO [Sheet1$] ([CarID], [CarDesc]) values (@CarID, @CarDesc)";
- ArrayList parameters = new ArrayList();
- parameters.Add(new OleDbParameter("@CarID", "1"));
- parameters.Add(new OleDbParameter("@CarDesc", "BMW"));
- Add_Records(sSqlSheet1, parameters);
- string sSqlSheet2 = "INSERT INTO [Sheet2$] ([CarID], [CarDesc]) values (@CarID, @CarDesc)";
- parameters = new ArrayList();//如果我不重新new一次parameter,错误肯定被弹出来
- parameters.Add(new OleDbParameter("@CarID", "1"));
- parameters.Add(new OleDbParameter("@CarDesc", "BMW"));
- Add_Records(sSqlSheet2, parameters);
- }
- catch (Exception ex)
- {
- MessageBox.Show(ex.ToString());
- }
- }
复制代码 如何使用OleDb可以浏览以下网址
微软官方网站:http://support.microsoft.com/kb/316934 |
|