【问题标题】:Insert multiple row using the same MySQL connection?使用相同的 MySQL 连接插入多行?
【发布时间】:2010-11-15 17:38:20
【问题描述】:

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

这里是我当前不工作的 C# 代码:

string[] tempfin = table.Split(',');
string username = null;
connection.Open();
foreach (object hope in tempfin)
{
    command.CommandText = "INSERT INTO ATable (Tried, Username) VALUES" + "('" + hope + "','" + username + "')";
    command.ExecuteReader();
} 
connection.Close();

我可以在 foreach 循环中打开和关闭连接,但是在插入大量行时这对我来说是不可靠的,那么有没有办法在 C# 中使用一个连接插入多行?

更新:没关系,我发现了我的问题。这是关于使用command.ExecuteReader() 而不是command.ExecuteNonQuery()

【问题讨论】:

  • 为什么你认为需要打开和关闭多个连接?
  • 不确定,但我尝试的其他方法最终返回 mysql 错误,例如“必须关闭现有连接”

标签: c# mysql


【解决方案1】:

您发布的代码已经在使用只有一个连接。我建议使用参数化查询而不是您正在使用的查询。

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

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

【讨论】:

    【解决方案2】:

    你可以用 MySQL 做这样的事情:

    INSERT INTO ATable (X, Y) VALUES (1, 2), (3, 4), (5, 6), (7, 8)
    

    这将插入 4 行。因此,如果您担心连续执行多个 INSERT 语句,只需更新您的代码以构建单个语句并执行该语句即可。

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

    这很可能是因为您使用的是ExecuteReader 而不是ExecuteNonQuery,正如Pablo Santa Cruz 指出的那样。

    【讨论】:

    • 您仍然应该将您的 SQL 修改为 Sean 的解决方案,因为它比运行多个查询在性能方面更好。
    • 是否以某种方式支持多个 SQLParameters,还是我必须自己创建具有多个值字符串的插入命令?
    【解决方案3】:

    那里,清理了一下。是的,它只使用一个连接。

    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();  
        }
    

    【讨论】:

      猜你喜欢
      • 2011-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-21
      • 2018-07-22
      • 1970-01-01
      • 2013-03-13
      相关资源
      最近更新 更多