我有一项任务是根据用户的需要向Access数据库添加尽可能多的用户。 (输入一些人来补充)。
现在,我的代码只添加了我写的第一个。我如何更改代码以便添加下一个代码,如果我输入10个人,它会添加所有代码?
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"dbs.accdb\"";
OleDbConnection con = new
OleDbConnection(ConnectionString);
OleDbCommand addCmd = new OleDbCommand("INSERT INTO PERSON(Name, LastName) VALUES(?,?)", con);
Console.Write("A number of persons to add: ");
int number= Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < number; i++)
{
Console.Write("Name:");
string name= Console.ReadLine();
addCmd.Parameters.Add(new OleDbParameter("@Name", name));
Console.Write("Last Name:");
string lastName= Console.ReadLine();
addCmd.Parameters.Add(new OleDbParameter("@LastName", lastName));
}
con.Open();
addCmd.ExecuteNonQuery();
con.Close();
答案 0 :(得分:1)
只需在循环中移动命令及其执行,同时创建连接并在循环外打开
string cmdText = "INSERT INTO PERSON(Name, LastName) VALUES(?,?)";
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"dbs.accdb\"";
using(OleDbConnection con = new OleDbConnection(ConnectionString))
using(OleDbCommand addCmd = new OleDbCommand(cmdText, con))
{
con.Open();
addCmd.Parameters.Add("@Name", OleDbType.VarWChar);
addCmd.Parameters.Add("@LastName", OleDbType.VarWChar);
Console.Write("A number of persons to add: ");
int number= Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < number; i++)
{
{
Console.Write("Name:");
string name= Console.ReadLine();
addCmd.Parameters["@Name"].Value = name;
Console.Write("Last Name:");
string lastName= Console.ReadLine();
addCmd.Parameters["@LastName"].Value = lastName;
addCmd.ExecuteNonQuery();
}
}
}
请注意,所有一次性对象(连接和命令)都包含在using语句中,以便在完成后正确处理(对于连接,这也意味着您不需要调用Close) 同样如下面的注释中所指出的,您可以在循环外创建参数,然后在循环内更改它们的值(从而避免创建命令和每个循环的参数)
答案 1 :(得分:0)
string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"dbs.accdb\"";
OleDbConnection con = new OleDbConnection(ConnectionString);
Console.Write("A number of persons to add: ");
int number= Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < number; i++)
{
OleDbCommand addCmd = new OleDbCommand("INSERT INTO PERSONA(Name, LastName) VALUES(?,?)", con);
con.Open();
Console.Write("Name:");
string name= Console.ReadLine();
addCmd.Parameters.Add(new OleDbParameter("@Name", name));
Console.Write("Last Name:");
string lastname= Console.ReadLine();
addCmd.Parameters.Add(new OleDbParameter("@LastName", lastname));
Console.WriteLine();
addCmd.ExecuteNonQuery();
con.Close();
}
我改变它看起来像这样,现在它工作,无论如何感谢回复