c# - asp插入错误

标签 c# asp.net .net sql-server

我是 Asp.net 的新手,我尝试从文件中读取数据并将其存储到数据库中 文件形式是:(阅读是测试,很好)

       0101;23/05/2014
       0602;23/05/2014
       0301;23/05/2014
       1103;23/05/2014
       0201;23/05/2014
       1704;23/05/2014
       ***************


        string[] lines = System.IO.File.ReadAllLines(@"C:\Users\user\Desktop\file.txt");
        SqlConnection connexion = new SqlConnection(@"Data Source=               (LocalDB)\v11.0;AttachDbFilename=C:\Users\user\Desktop\controle\miniprojet\miniprojet\App_Data\ariche.mdf;Integrated Security=True"); 
        SqlCommand command = connexion.CreateCommand();
        String requete = "INSERT INTO commande VALUES(@idpr,@date)";
        SqlParameter paramidprod;
        SqlParameter paramdate;
        connexion.Open(); 
        res.Text="Contents of file.txt = ";
        foreach (string line in lines)
        {
           if (line.Contains('*')) break;
           String[] l = line.Split(';');
           paramidprod=new SqlParameter("@idpr", line.Substring(0,2));
           paramdate = new SqlParameter("@date", l[1]);
           command.Parameters.Add(paramidprod);
           command.Parameters.Add(paramdate);
           command.CommandText = requete;
           command.ExecuteNonQuery();
           res.Text += "<br>" + l[1] +"   "+ line.Substring(0, 2);
        }
        connexion.Close();
        connexion.Dispose();

当我运行程序时我遇到了这个问题:

The variable name '@idpr' has already been declared. Variable names must be unique 
within a query batch or stored procedure. 

你能找出我迷路的错误吗

最佳答案

您正在循环,每次循环运行时都会添加新参数。因此,第二次和后续调用将失败。

要么在每个循环中设置新的命令参数,要么只创建一次参数,然后在每个循环中重新分配它们。

这是第二个选项 - 重用相同的参数 - 它会在循环场景中表现得更好,就像你所拥有的那样:

    var connexion = new SqlConnection(@"Data Source=..."); 
    var command = connexion.CreateCommand();
    var requete = "INSERT INTO commande VALUES(@idpr,@date)";
    // I've assumed the types - double check
    var paramidprod = new SqlParameter("@idpr", SqlDbType.VarChar);
    var paramdate = new SqlParameter("@date", SqlDbType.DateTime);
    command.Parameters.Add(paramidprod);
    command.Parameters.Add(paramdate);
    command.CommandText = requete;
    connexion.Open(); 

    foreach (string line in lines)
    {
       if (line.Contains('*')) break;
       String[] l = line.Split(';');
       paramidprod.Value = line.Substring(0,2);
       paramdate.Value = l[1];
       command.ExecuteNonQuery();
    }
    connexion.Close();
    connexion.Dispose();

如果您要插入大量记录,您还可以考虑每插入 1000 次就提交一次事务。

关于c# - asp插入错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23829308/

相关文章:

C# 远程 MySQL - 用户访问被拒绝

c# - 在我们正在实现的每个方法中使用#region 是否好

c# - 如何安排日期时间列表的特殊表格格式

c# - 获取页面注册的客户端证书

c++ - 64 位 Windows 上应用程序可用的最大内存是多少

c# - RichTextBox 控件,制作非 URL 超链接?

c# - WebAPI 上传错误。 MIME 多部分流的预期结束。 MIME 多部分消息不完整

c# - 什么配置控制 "HttpBufferlessInputStream.DisableMaxRequestLength"

C# 无法从泛型方法调用重载的非泛型方法

.net - 正则表达式的多线程使用