我是 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/