C# 是否使用同一MySQL连接插入多行?

C# 是否使用同一MySQL连接插入多行?,c#,mysql,C#,Mysql,我想知道如何使用一个连接将多行插入MySQL数据库,而不是打开和关闭多个连接。插入的数据来自字符串[],因此我使用foreach循环来获取每个值 下面是我当前的非工作C#代码: 我可以在foreach循环中打开和关闭连接,但在插入大量行时,这已被证明是不可靠的,因此有没有办法在C#中使用一个连接插入多行 更新:没关系,我发现了我的问题。它是关于使用命令.ExecuteReader()而不是命令.ExecuteNonQuery()您发布的代码已经使用了只有一个连接。我建议使用参数化查询,而不是您正

我想知道如何使用一个连接将多行插入MySQL数据库,而不是打开和关闭多个连接。插入的数据来自字符串[],因此我使用foreach循环来获取每个值

下面是我当前的非工作C#代码:

我可以在foreach循环中打开和关闭连接,但在插入大量行时,这已被证明是不可靠的,因此有没有办法在C#中使用一个连接插入多行


更新:没关系,我发现了我的问题。它是关于使用
命令.ExecuteReader()
而不是
命令.ExecuteNonQuery()
您发布的代码已经使用了只有一个连接。我建议使用参数化查询,而不是您正在使用的查询

为什么你的代码不起作用?你能用你得到的错误更新你的问题吗


如果发出insert命令,则应使用
ExecuteNonQuery
而不是
ExecuteReader

使用MySQL可以执行以下操作:

INSERT INTO ATable (X, Y) VALUES (1, 2), (3, 4), (5, 6), (7, 8)
这将插入4行。因此,只要更新您的代码以构建一条语句,并在一行中执行多条
INSERT
语句时执行该语句即可


不确定但我试过的其他方法 最终返回mysql错误,例如 “必须关闭现有连接”


这很可能是因为您使用的是
ExecuteReader
,而不是前面指出的
ExecuteNonQuery

这里,对它进行了一些清理。是的,它只使用一个连接

string[] tempfin = table.Split(',');
    string username = null;
    try
    {
        connection.Open();
        SQLParameter parUserName = new SqlParameter("@username", System.Data.SqlDbType.VarChar,100);
        if(username != null) parUserName.Value = username; else parUserName.Value = DBNull.Value;

        SQLParameter parHope = new SqlParameter("@hope", System.Data.SqlDbType.VarChar,256);

        command.Parameters.Add(parUserName);
        command.Parameters.Add(parHope);

        command.CommandText = "INSERT INTO ATable (Tried, Username) VALUES (@hope,@username)";
        foreach (string hope in tempfin)
        {
            parHope.Value = hope;
            command.ExecuteNonQuery();
        }
    }
    finally{
        if (connection.State != System.Data.ConnectionState.Closed)
            connection.Close();
        if(command != null)
            command.Dispose();  
    }

为什么您认为需要打开和关闭多个连接?不确定,但我尝试的其他方法最终返回了mysql错误,例如“必须关闭现有连接”您仍然应该将SQL修改为Sean的解决方案,因为这比运行多个查询的性能更好。是以某种方式支持多个SQLParameters,还是我必须自己创建具有多个值字符串的insert命令?
string[] tempfin = table.Split(',');
    string username = null;
    try
    {
        connection.Open();
        SQLParameter parUserName = new SqlParameter("@username", System.Data.SqlDbType.VarChar,100);
        if(username != null) parUserName.Value = username; else parUserName.Value = DBNull.Value;

        SQLParameter parHope = new SqlParameter("@hope", System.Data.SqlDbType.VarChar,256);

        command.Parameters.Add(parUserName);
        command.Parameters.Add(parHope);

        command.CommandText = "INSERT INTO ATable (Tried, Username) VALUES (@hope,@username)";
        foreach (string hope in tempfin)
        {
            parHope.Value = hope;
            command.ExecuteNonQuery();
        }
    }
    finally{
        if (connection.State != System.Data.ConnectionState.Closed)
            connection.Close();
        if(command != null)
            command.Dispose();  
    }