我试图将id,名字和姓氏输入表格,然后根据组合框输入我创建另一条记录,然后保存学生的ID和所选择的团队的ID在组合框中。这是我的代码。一切运行良好唯一的问题是,之后没有添加TeamPlayers表中的记录。请有人吗?!?
try
{
string team = null;
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=;Persist Security Info=False;"))
{
OleDbCommand comm = new OleDbCommand("INSERT INTO Students(BaruchID, FirstName, LastName) VALUES(@id, @first, @last)", conn);
conn.Open();
comm.Parameters.AddWithValue("@id", tbBaruchID.Text);
comm.Parameters.AddWithValue("@id", FirstName.Text);
comm.Parameters.AddWithValue("@id", LastName.Text);
comm.ExecuteNonQuery();
conn.Close();
}
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Junglists/Documents/Visual Studio 2013/Projects/SACC_Baruch/SACC_Baruch/Teams.accdb;Persist Security Info=False;"))
{
OleDbCommand comm = new OleDbCommand("SELECT TeamNum FROM Teams WHERE TeamName='" + cbTeam.Text +"'", conn);
conn.Open();
OleDbDataReader dr = comm.ExecuteReader(CommandBehavior.SingleResult);
if (dr.Read())
{
team = dr["TeamNum"].ToString();
}
conn.Close();
}
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Junglists/Documents/Visual Studio 2013/Projects/SACC_Baruch/SACC_Baruch/Teams.accdb;Persist Security Info=False;"))
{
OleDbCommand comm = new OleDbCommand("INSERT INTO TeamPlayers(ID, BaruchID, TeamID) VALUES(@i, @id, @teamid)", conn);
conn.Open();
comm.Parameters.AddWithValue("@i", 1);
comm.Parameters.AddWithValue("@id", tbBaruchID.Text);
comm.Parameters.AddWithValue("@teamid", int.Parse(team));
conn.Close();
}
MessageBox.Show("Student Added for team"+ cbTeam.Text);
}
答案 0 :(得分:4)
添加参数值时,不使用第一个INSERT语句中的参数名称。所有comm.Parameters.AddWithValue("@id", .....);
行都使用@id
。因此,实际ID值永远不会保存到表学生。
第二个INSERT始终使用1作为'id'的值。假设'id'是主键,它只能包含唯一值。将“id”字段设置为IDENTITY字段,然后将其从INSERT语句中删除。每次将记录添加到表中时,将以递增的顺序给出下一个数字。