有没有一种方法可以直接将文本文件加载到sqlite数据库中,而不在代码内部进行处理,但仍然使用c#?

有没有一种方法可以直接将文本文件加载到sqlite数据库中,而不在代码内部进行处理,但仍然使用c#?,c#,.net,regex,performance,sqlite,C#,.net,Regex,Performance,Sqlite,我目前正在开发一个程序,它从一个巨大的(40000行+*.txt)文件中读取数据。线条如下所示: 4,Barbarendorf,505,552,1575899232,378,0 5,Der+letzte+macht+das+Licht+aus,484,458,1576458064,5757,0 一般而言: $id, $name, $x, $y, $player, $points, $rank 因此,我编写的将这些数据输入SQLite数据库的函数如下: void ThreadMethod()

我目前正在开发一个程序,它从一个巨大的(40000行+*.txt)文件中读取数据。线条如下所示:

4,Barbarendorf,505,552,1575899232,378,0
5,Der+letzte+macht+das+Licht+aus,484,458,1576458064,5757,0
一般而言:

$id, $name, $x, $y, $player, $points, $rank
因此,我编写的将这些数据输入SQLite数据库的函数如下:

void ThreadMethod()
{
    string sql = "";
    SQLiteConnection m_dbConnection;
    m_dbConnection = new SQLiteConnection("Data Source=villages.db;Version=3;");
    m_dbConnection.Open();
    SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
    try
    {
        using (StreamReader sr = new StreamReader("village.txt"))
        {
            String line;
            while ((line = File.ReadLines("village.txt").Last()) != null)
            {
                Regex regex = new Regex(",");
                string[] substrings = regex.Split(line);
                int i = 0;
                string[] strVillage = new string[7];
                foreach (string match in substrings)
                {
                    strVillage[i++] = match;
                }
                sql = "INSERT INTO villages (villageID, villageName, xCoord, yCoord, playerName, villagePoints, villageRank) values (" + strVillage[0] + ", '" + strVillage[1] + "', " + strVillage[2] + ", " + strVillage[3] + ", '" + strVillage[4] + "', " + strVillage[5] + ", " + strVillage[6] + ")";
                command = new SQLiteCommand(sql, m_dbConnection);
                command.ExecuteNonQuery();
                var lines = System.IO.File.ReadAllLines("village.txt");
                System.IO.File.WriteAllLines("village.txt", lines.Take(lines.Length - 1).ToArray());
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    m_dbConnection.Close();
}
它能工作,但速度很慢。 我希望你们能帮助我提高成绩。
致以最良好的祝愿

通过使用已编译的正则表达式,而不是为每一行创建一个新实例,可以立即显著提高性能。因此,在方法所在的类中:

public class ClassThatThisMethodIsIn 
{
    private static Regex regex = new Regex(",", RegexOptions.Compiled);

    // rest of code goes here
}
并在方法中删除该行:

Regex regex = new Regex(",");
如果逗号拆分是使用正则表达式的唯一原因,请完全删除正则表达式,而使用字符串。拆分:

var substrings = line.Split(',');

进一步的性能可以通过在插入中批处理插入。。。选择UNION语句并一次插入多行,而不是每行插入一行。

您做了哪些基准测试,哪一部分特别慢?使用
string.Split()
,使用批量插入()。您尝试过什么?您是否考虑过只寻找一个可以重用的CSV库?