mysql和c#在类型转换的问题

1、char(36)和string

mysql在将char(36)类型的会转成System.GUID,如果char(36)字段里存的不是guid,最好不要用char(36),改成char(37)这样的就没事了。

在.net开放中(asp.net core\ef core\mysql)连接mysql数据库的时候,其中一个表字段类型是char(36),但里面存的并不是36位的,结果一直报如下错误

An unhandled exception occurred while processing the request.

FormatException: One of the identified items was in an invalid format.

MySqlConnector.Core.TextRow.GetValueCore(ReadOnlySpan<byte> data, ColumnDefinitionPayload columnDefinition) in C:\projects\mysqlconnector\src\MySqlConnector\Core\TextRow.cs, line 57

 

后来看网络上回答才知道mysql将char(36)进行特殊处理了,具体mysql说明是这样的

https://dev.mysql.com/doc/connector-net/en/connector-net-8-0-connection-options.html

The back-end representation of a GUID type was changed from BINARY(16) to CHAR(36). This was done to allow developers to use the server function UUID()  to populate a GUID table - UUID() generates a 36-character string. Developers of older applications can add 'Old Guids=true' to the connection string to use a GUID of data type BINARY(16).

 

2、tinyint(1)和boolean类型

System.InvalidCastException: Unable to cast object of type 'System.Boolean' to type 'System.SByte'.

如果在连接字符串中加入了TreatTinyAsBoolean=true,在mysql数据中的tinyint(1)类型转化到对应的.net中的sbyte类型时会报以上错误,所以改成TreatTinyAsBoolean=false就可以了。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在 C# 窗体程序中从 MySQL 数据库中下载文件,可以采用以下步骤: 1. 首先,需要在 MySQL 数据库中创建一个 BLOB 字段,并将文件存储在该字段中。 2. 在 C# 窗体程序中,需要使用 MySQL 数据库连接库和命令库来连接 MySQL 数据库,并执行 SQL 查询语句,以获取包含文件内容的 BLOB 字段。 3. 将 BLOB 数据转换为 byte[] 数组,并将其写入磁盘上的文件中。 下面是一个示例代码,演示如何从 MySQL 数据库中下载文件: ```c# using System; using System.Data; using System.IO; using System.Windows.Forms; using MySql.Data.MySqlClient; namespace DownloadFileFromMySQL { public partial class Form1 : Form { private MySqlConnection connection; private MySqlCommand command; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // 连接 MySQL 数据库 connection = new MySqlConnection("server=localhost;database=test;uid=root;pwd=123456;"); connection.Open(); // 查询包含文件内容的 BLOB 字段 command = new MySqlCommand("SELECT file_content FROM files WHERE file_name=@name", connection); command.Parameters.AddWithValue("@name", "test.txt"); MySqlDataReader reader = command.ExecuteReader(); if (reader.Read()) { // 将 BLOB 数据转换为 byte[] 数组,并将其写入磁盘上的文件中 byte[] fileData = (byte[])reader["file_content"]; File.WriteAllBytes("test.txt", fileData); MessageBox.Show("Download completed!"); } else { MessageBox.Show("File not found!"); } reader.Close(); connection.Close(); } } } ``` 以上代码中,假设在 MySQL 数据库中已经创建了一个名为 `files` 的表,其中包含两个字段 `file_name` 和 `file_content`,`file_content` 字段为 BLOB 类型。下载文件时,根据文件名查询对应的 BLOB 数据,并将其写入磁盘上的文件中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值