通过 Connector/NET 使用 MySQL 的 C#

2024-01-08

我正在 C#(4.0 Framework)中开发 CMS 应用程序,它连接到远程服务器上的 MySQL 数据库(5.0.95) 由 MySQL 连接器 (6.5.4) 提供。

我在执行查询时遇到问题。

例如 我的连接字符串:

"Server=" + Options.DbServer + ";Database="+ Options.Database +";Uid=" + Options.DbUser + ";Pwd=" + Options.DbPassword + ";CharSet=utf8; Connect Timeout=30;";

我有管理数据库相关内容的静态类,并且有私有成员_connection。

private static MySqlConnection _connection;
public static MySqlConnection Connection
{ 
    get
    {
        if (_connection.State != ConnectionState.Open)
            _connection.Open();

        return _connection;
    } 
    set { _connection = value; }
}

这是初始化连接的方法:

public static bool Init(string cs)
{
    _connection = new MySqlConnection(cs);
    MySqlCommand command = new MySqlCommand("SET NAMES utf8", Connection);
    command.ExecuteNonQuery();
    return true;
}

这是我遇到异常的方法:

public static bool InsertRecord(MySqlCommand command)
{
    command.Connection = Connection;
    if(command.ExecuteNonQuery() > 0)
        return true;

    return false;
}

command.ExecuteNonQuery()抛出异常:命令执行期间遇到致命错误。

这是堆栈跟踪...

MySql.Data.MySqlClient.MySqlException was unhandled
  Message=Fatal error encountered during command execution.
  Source=MySql.Data
  ErrorCode=-2147467259
  Number=0
  StackTrace:
       at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
       at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()
       at CMS.Database.InsertRecord(MySqlCommand command) in C:\_myStuff\VS2010\CMS\CMS\Database.cs:line 95
       at CMS.frmAddItem.btnDo_Click(Object sender, EventArgs e) in C:\_myStuff\VS2010\CMS\CMS\frmAddItem.cs:line 138
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.RunDialog(Form form)
       at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
       at System.Windows.Forms.Form.ShowDialog()
       at CMS.frmMain.btnNovi_Click(Object sender, EventArgs e) in C:\_myStuff\VS2010\CMS\CMS\frmMain.cs:line 381
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.RunDialog(Form form)
       at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
       at System.Windows.Forms.Form.ShowDialog()
       at CMS.frmLogin.DoLogin() in C:\_myStuff\VS2010\CMS\CMS\frmLogin.cs:line 55
       at CMS.frmLogin.button2_Click(Object sender, EventArgs e) in C:\_myStuff\VS2010\CMS\CMS\frmLogin.cs:line 31
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at CMS.Program.Main() in C:\_myStuff\VS2010\CMS\CMS\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: MySql.Data.MySqlClient.MySqlException
       Message=Fatal error encountered attempting to read the resultset.
       Source=MySql.Data
       ErrorCode=-2147467259
       Number=0
       StackTrace:
            at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
            at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
       InnerException: MySql.Data.MySqlClient.MySqlException
            Message=Reading from the stream has failed.
            Source=MySql.Data
            ErrorCode=-2147467259
            Number=0
            StackTrace:
                 at MySql.Data.MySqlClient.MySqlStream.LoadPacket()
                 at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
                 at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int32& insertedId)
                 at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int32& insertedId)
                 at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
                 at MySql.Data.MySqlClient.MySqlDataReader.NextResult()
            InnerException: System.IO.EndOfStreamException
                 Message=Attempted to read past the end of the stream.
                 Source=MySql.Data
                 StackTrace:
                      at MySql.Data.MySqlClient.MySqlStream.ReadFully(Stream stream, Byte[] buffer, Int32 offset, Int32 count)
                      at MySql.Data.MySqlClient.MySqlStream.LoadPacket()
                 InnerException:

有什么建议么?


我注意到您打开了连接,但在完成连接后却没有关闭它们。我更喜欢在需要时打开连接的方法,而不是在连接尚未打开时可能打开它们。它们可能已经过时了。

缓存连接字符串但不是连接本身。

public static string ConnectionString {get;set;}

public static bool InsertRecord(sql)
{
    bool success = false;
    using (var con = new Connection(ConnectionString)){
        var command = new SqlCommand(sql,con);
        success = (command.ExecuteNonQuery() > 0);
    }
    return success;
}

当不再需要资源时,应将其释放。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 Connector/NET 使用 MySQL 的 C# 的相关文章

随机推荐

  • 程序收到信号:“EXC_BAD_ACCESS”

    我有一个字符串变量 它存储日期选择器中的日期 但是当我在其他函数中使用它的值时 我收到类似程序收到信号的错误 EXC BAD ACCESS 注意 变量是全局定义的 code void changedDate UIDatePicker pic
  • 从相机预览中的触摸事件中检索准确的 RGB 值

    我一直在开发一个 Android 应用程序 它只需要检索并在相机预览上显示触摸事件的坐标和 RGB 值 我是这种编程语言的初学者 我只是想尝试一下 但应用程序在触摸事件期间不断崩溃 这是我在 Android 中尝试过的代码 When cop
  • 在 PyQt 中显示其他语言字符

    PyQt4 有没有办法显示其他语言字符 如果有 我应该采取什么方法 方向 提前致谢 Qt 使用 Unicode 并且应该能够以您拥有合适字体的任何语言显示 Unicode 文本 例如 Roberto Alesina 的简单 Hello Wo
  • 新的“dynamic”C# 4.0 关键字是否弃用了“var”关键字?

    当 C 4 0 出现时 我们有了如此处描述的动态关键字excellent presentation by Anders Hejlsberg http channel9 msdn com pdc2008 TL16 C 的发展速度比我能跟上的要
  • OSGi - 这项技术有多成熟?

    我有一个要求 我需要共享一些网络资源 jsp html js images css等 跨越不同Spring based Struts 2应用程序 似乎OSGi可以用来实现这个吗 有人可以指点一下如何实现这一目标吗OSGi 其次我想知道的是O
  • Java 线程/易失性

    我有一个线程 class Foo extends Thread boolean active true public void run while active do stuff public void end active false p
  • 'in' 表示两个复杂度最低的排序列表

    我有两个sorted列表 例如 a 1 4 7 8 b 1 2 3 4 5 6 我想知道其中的每一项a如果它在b 对于上面的例子 我想找到 a in b True True False False 或具有索引 其中a in b is Tru
  • php检查数组值是否重复[重复]

    这个问题在这里已经有答案了 我有以下数组 PHP arr array A A B C 我想检查值 如果值重复则必须发出警报错误 PHP chk array count values array if chk 0 lt 1 chk 2 lt
  • Visual Studio 2015突然不想在类中创建新变量[关闭]

    Closed 这个问题是无法重现或由拼写错误引起 help closed questions 目前不接受答案 我几乎一整天都在为这个问题苦苦挣扎 我在互联网上找不到任何答案 我知道这个修复只是为了改变一件小事 但我不知道是哪一件 卸载 使用
  • SQL LIKE % 未搜索

    我想使用 SQL LIKE 函数执行简单的搜索 不幸的是 由于某种原因 它似乎不起作用 下面是我的代码 private void gvbind connection Open string sql if txtSearch Text Tri
  • 将小数转换为另一种基数的时间复杂度

    这是计算十进制数的基本版本的代码 我不确定它的时间复杂度 谢谢 public static String convertToBase int num int base if base gt 36 throw new IllegalArgum
  • 我有一个包含 14 个静态方法和 4 个静态属性的类 - 这很糟糕吗?

    我一直在编写一个 PHP 类 该类正好有 450 行长 它包含 14 个静态方法和 4 个静态属性以及 6 个常量 以及私有 construct and clone 我想知道我是不是做错了什么 我的班级是邪恶的吗 当您使用该类时 您总是调用
  • Firebase 的喜欢/不喜欢功能

    该系统本身很容易理解 但实施起来却很棘手 此外 安全原因让我思考如何做到这一点 我正在考虑让该功能在前端 Firebase 脚本中工作 只需执行所有操作即可检查该用户是否已经发布了喜欢 不喜欢的内容 并在用户单击时删除 添加 切换 问题在于
  • 更改 Rmarkdown pdf 中 Kable 的字体

    当编织为pdf时 有没有办法改变Rmarkdown中kable的字体 我可以找到很多有关更改大小或粗体等的信息 但不能找到有关更改实际字体的信息 我只想要一些无衬线的东西 降价文档示例 title R Notebook output pdf
  • 设置默认日期时间格式c#

    有没有办法设置或覆盖整个应用程序的默认日期时间格式 我正在用 C Net MVC 1 0 编写一个应用程序 并使用大量泛型和反射 如果我可以将默认的 DateTime ToString 格式重写为 dd MMM yyyy 则会简单得多 当站
  • WPF:使用旋转方块进行碰撞检测

    参考这个编程游戏 https stackoverflow com questions 505040 developing a robocode type game with net for a school assignment我目前正在建
  • PHP 的怪癖和陷阱 [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • + 运算符与 parseFloat

    实施例1 http knockoutjs com documentation extenders html淘汰扩展器页面的 描述了一种对用户输入进行四舍五入并确保它只是数字的方法 它工作得很好 但是查看源代码 他们做了一件我不明白的奇怪的事
  • PageRequest 构造函数已被弃用

    我正在使用 Spring Data Commons v2 快照 并且我看到PageRequest已被弃用 这似乎发生在M1 http docs spring io spring data commons docs 2 0 0 M1 api
  • 通过 Connector/NET 使用 MySQL 的 C#

    我正在 C 4 0 Framework 中开发 CMS 应用程序 它连接到远程服务器上的 MySQL 数据库 5 0 95 由 MySQL 连接器 6 5 4 提供 我在执行查询时遇到问题 例如 我的连接字符串 Server Options