使用C#在Access数据库中插入错误的数据

时间:2017-03-26 12:52:58

标签: c# access

当插入数据时,我对Access数据库有一个小问题。

我有一个按钮,可以在点击时插入数据。这是代码:

string[] read = File.ReadAllLines("Harta_Distantelor.txt");

string[] orase = { "Constanta", "Varna", "Burgas", "Istambul", "Kozlu", "Samsun", "Batumi", "Sokhumi", "Soci", "Anapa", "Yalta", "Sevastopol", "Odessa" };

 OleDbCommand cmd;

        for (int i = 0; i < read.Length; i++)
        {
            int j = 0;
            string[] numbers = read[i].Split(' ');
            while (j < read.Length)
            {
                //cmd = new OleDbCommand("UPDATE Distante SET ID_Port='" + (i + 1) + "', ID_Port_Destinatie='" + (j + 1) + "', Nume_Port_Destinatie='" + orase[j] + "' WHERE Distanta='" + numbers[j] + "' ", conn);
                cmd = new OleDbCommand("INSERT INTO [Distante]([ID_Port], [ID_Port_Destinatie], [Nume_Port_Destinatie], [Distanta]) VALUES ('" + (i + 1).ToString() + "', '" + (j + 1).ToString() + "', '" + orase[j] + "', '" + numbers[j] + "')", conn);
                cmd.ExecuteNonQuery();
                j++;
            }
        }

问题是,不是像ID_Port = 1,ID_Port_Destinatie = 1,Nume_Port_Destinatie =“Constanta”,ID_Port = 1,ID_Port_Destinatie = 2,Nume_Port_Destinatie =“Varna”等等,我得到这个... < / p>

https://i.stack.imgur.com/OjMQm.png

文件“Harta_Distantelor.txt”是一个具有距离的矩阵,因此我尝试从一行(string[] numbers = read[i].Split(' ');)中分割每个数字。我必须提到正确插入[Distanta]数据,但其余数据是完全随机插入的。我试图找出问题所在,但我不知道。哪里出错了?为了正确显示数据,我应该尝试做些什么?

1 个答案:

答案 0 :(得分:0)

1。)创建一个名为HartaDistantelor的表,其中包含ID_Port,ID_Port_Destinatie和Distanta的列

2。)用您的矩阵值填充表格HartaDistantelor。您也许可以直接复制并粘贴到Access中

3。)创建一个名为Orase的表,其中包含ID_Port和Nume_Port的列

4。)用数组中的13个值填充Orase表。它应该看起来像这样:

1    Constanta
2    Varna
3    Burgas
4    ...

5。)更改您的代码:

OleDbCommand cmd;

for (int i = 0; i < 12; i++)
{
    for (int j = 0; j < 12; j++)
    {
        cmd = new OleDbCommand("INSERT INTO Distante (ID_Port, ID_Port_Destinatie, Nume_Port_Destinatie, Distanta) SELECT " + (i + 1).ToString() + ", " + (j + 1).ToString() + ", o.Nume_Port, h.Distanta FROM Orase o JOIN HartaDistantelor h ON h.ID_Port = o.ID_Port WHERE h.ID_Port = i AND h.ID_Port_Destinatie = j", conn);
        cmd.ExecuteNonQuery();
    }
}

我的方法使用匹配的ID值联接来自两个表的记录。我认为您没有犯任何错误,但是使用了比必要的方法复杂的方法。