草庐IT

c# - 将 blob 更新到 mysql 时执行命令时遇到 fatal error

coder 2023-10-06 原文

String query = "";
        string constr = ConfigurationSettings.AppSettings["MySQLConnectionStringForIMS"];
        using (MySqlConnection con = new MySqlConnection(constr))
        {
            //string query = "INSERT INTO user(name, files,contentType) VALUES (@name,@files,@contentType)";
            if (update == "mainSec")
            {
                query = "update main_section set contentType=@contentType,fileData=@fileData,fileNameAfterUploading=@fname,haveDir=@dir where id=@id";
            }
            else
            {
                query = "update sub_section set subContentType=@contentType,subFileData=@fileData,fileNameAfterUploading=@fname,haveDir=@dir where MainSecId=@id and id=@subId";
            }
            using (MySqlCommand cmd = new MySqlCommand(query))
            {
                cmd.Connection = con;
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@contentType", contentType);
                cmd.Parameters.AddWithValue("@fileData", data);
                cmd.Parameters.AddWithValue("@fname", filename);
                cmd.Parameters.AddWithValue("@dir", 1);
                cmd.Parameters.AddWithValue("@id", mainId);
                if (update == "subSec")
                {
                    cmd.Parameters.AddWithValue("@subId", subId);
                }
                con.Open();
                int st = cmd.ExecuteNonQuery();
                if (st == 1)
                {
                    //Uri uri = new Uri(url, UriKind.Absolute);
                    //System.IO.File.Delete(uri.LocalPath);
                }
                con.Close();
            }
        }

我们使用的是 MySql.Data.dll 版本 6.9.5.0。

这失败并出现错误:mysql 在命令执行期间遇到 fatal error 。关于为什么这会失败的任何想法?

最佳答案

Tl;DR

由于不匹配的分支比较,您正在执行具有 6 个未绑定(bind)变量的查询,但您只绑定(bind)了 5 个参数。

详情

堆栈跟踪/异常中没有提供足够的信息来明确回答,但似乎对上述分支中不良做法的猜测是根本原因,即在这两个分支中:

if (update == "mainSec")
{
    query = ... Query has 5 unbound variables
}
else
{
    query = ... Query has 6 unbound variables
}

if (update == "subSec")
{
     ... bind the 6th parameter here
}

.. 因为 update类型/模式字符串不限于 mainSec 的范围内或 subSec , 有一个分支使用了 sub_section使用 6 个参数标记查询,但没有绑定(bind)第 6 个标记,导致错误。

在这种情况下,我建议不要使用弱约束字符串,而是严格限制 update 的输入范围。 ,例如用enum :

enum UpdateMode
{
    Invalid = 0, // This will be the default, and can be used to ensure assignment
    MainSection,
    SubSection
}

由于只有两种可能的模式,您可以避免使用条件分配的第一个查询分配分支,即

Contract.Assert(updateMode != UpdateMode.Invalid);
var query = updateMode == UpdateMode.MainSection
      ? "update main_section set contentType=@contentType ... "
      : "update sub_section set subContentType=@contentType ... ";

这有声明和分配 query 的好处可以捆绑在一起(并提供额外的编译器保证必须分配 query)。

(如果有两个以上的查询(和两个以上的枚举状态),那么 static IReadOnlyDictionary<enum, string> 将允许扩展此模式。)

绑定(bind)也将更改为

if (updateMode == UpdateMode.SubSection)
{
    cmd.Parameters.AddWithValue("@subId", subId);
}

一些注意事项

  • con.Close();不需要,因为你已经有一个 using new Connection周围- Dispose会调用.Close如果它是开放的
  • 我知道这已被注释掉,但我强烈建议此时不要进行文件 IO

 if (st == 1)
 {
     // File.IO
 }

  • 从关注点分离的角度来看,删除文件属于别处。如果删除仅依赖于更新的一行,则可以从此 Blob 更新方法返回。
  • I/O 将在 using 的范围内 block ,这可能会阻止 MySql 连接的释放(到连接池)
  • IO 可能会失败,并且根据任何事务控制,这可能会使您的系统处于有问题的状态,即记录被删除但文件没有。

关于c# - 将 blob 更新到 mysql 时执行命令时遇到 fatal error ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50609595/

有关c# - 将 blob 更新到 mysql 时执行命令时遇到 fatal error的更多相关文章

  1. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  2. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  3. ruby - 在 Ruby 中编写命令行实用程序 - 2

    我想用ruby​​编写一个小的命令行实用程序并将其作为gem分发。我知道安装后,Guard、Sass和Thor等某些gem可以从命令行自行运行。为了让gem像二进制文件一样可用,我需要在我的gemspec中指定什么。 最佳答案 Gem::Specification.newdo|s|...s.executable='name_of_executable'...endhttp://docs.rubygems.org/read/chapter/20 关于ruby-在Ruby中编写命令行实用程序

  4. ruby - 通过 RVM (OSX Mountain Lion) 安装 Ruby 2.0.0-p247 时遇到问题 - 2

    我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search

  5. ruby-on-rails - 使用 rails 4 设计而不更新用户 - 2

    我将应用程序升级到Rails4,一切正常。我可以登录并转到我的编辑页面。也更新了观点。使用标准View时,用户会更新。但是当我添加例如字段:name时,它​​不会在表单中更新。使用devise3.1.1和gem'protected_attributes'我需要在设备或数据库上运行某种更新命令吗?我也搜索过这个地方,找到了许多不同的解决方案,但没有一个会更新我的用户字段。我没有添加任何自定义字段。 最佳答案 如果您想允许额外的参数,您可以在ApplicationController中使用beforefilter,因为Rails4将参数

  6. ruby - Chef 执行非顺序配方 - 2

    我遵循了教程http://gettingstartedwithchef.com/,第1章。我的运行list是"run_list":["recipe[apt]","recipe[phpap]"]我的phpapRecipe默认Recipeinclude_recipe"apache2"include_recipe"build-essential"include_recipe"openssl"include_recipe"mysql::client"include_recipe"mysql::server"include_recipe"php"include_recipe"php::modul

  7. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

  8. ruby - 为什么 Ruby 的 each 迭代器先执行? - 2

    我在用Ruby执行简单任务时遇到了一件奇怪的事情。我只想用每个方法迭代字母表,但迭代在执行中先进行:alfawit=("a".."z")puts"That'sanalphabet:\n\n#{alfawit.each{|litera|putslitera}}"这段代码的结果是:(缩写)abc⋮xyzThat'sanalphabet:a..z知道为什么它会这样工作或者我做错了什么吗?提前致谢。 最佳答案 因为您的each调用被插入到在固定字符串之前执行的字符串文字中。此外,each返回一个Enumerable,实际上您甚至打印它。试试

  9. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  10. C# 到 Ruby sha1 base64 编码 - 2

    我正在尝试在Ruby中复制Convert.ToBase64String()行为。这是我的C#代码:varsha1=newSHA1CryptoServiceProvider();varpasswordBytes=Encoding.UTF8.GetBytes("password");varpasswordHash=sha1.ComputeHash(passwordBytes);returnConvert.ToBase64String(passwordHash);//returns"W6ph5Mm5Pz8GgiULbPgzG37mj9g="当我在Ruby中尝试同样的事情时,我得到了相同sha

随机推荐