Skip to main content
 首页 » 编程设计

c#之使用 C# 将数据同时导出到 Access 到两个表中

2024年02月13日12xiaohuochai

我正在尝试将 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); 
        } 

请您参考如下方法:

添加参数值时不使用第一个 INSERT 语句中的参数名称。所有 comm.Parameters.AddWithValue("@id", .....); 行都使用 @id。因此,实际的 id 值永远不会保存到表 student。

第二个 INSERT 始终使用 1 作为“id”的值。假设 'id' 是主键,它只能包含唯一值。使“id”字段成为 IDENTITY 字段,然后将其从 INSERT 语句中删除。每次将记录添加到表中时,都会以不断递增的顺序为它提供下一个数字。

更正后的代码:http://dotnetfiddle.net/Dr9842