憨辰 2023-02-07 11:44 采纳率: 50%
浏览 55
已结题

MySql数据库存储、读取图片

在Unity中怎么实现连接MySql数据库并实现如下功能
  1. 向数据库存储图片
  2. 从数据库读取图片
  • 写回答

2条回答 默认 最新

  • 梦想橡皮擦 Python领域优质创作者 2023-02-07 12:38
    关注

    方案来自 梦想橡皮擦 狂飙组基于 GPT 编写的 “程秘”


    要在Unity中连接MySQL数据库并实现存储和读取图片,可以使用以下方法:

    首先,需要安装MySQL Connector for .NET,这是一个用于在.NET环境中连接MySQL数据库的库。

    接下来,可以使用代码来连接数据库,存储图片,并读取图片。下面是一个简单的示例:

    using UnityEngine;
    using MySql.Data.MySqlClient;
    
    public class DatabaseManager : MonoBehaviour
    {
        private void Start()
        {
            string connectionString = "server=localhost;database=testdb;user=root;password=password;";
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();
                string insertSql = "INSERT INTO images (image) VALUES (@image)";
                using (MySqlCommand command = new MySqlCommand(insertSql, connection))
                {
                    // convert the image to a byte array
                    byte[] imageBytes = System.IO.File.ReadAllBytes("path/to/image.jpg");
                    command.Parameters.AddWithValue("@image", imageBytes);
                    command.ExecuteNonQuery();
                }
                string selectSql = "SELECT image FROM images WHERE id = @id";
                using (MySqlCommand command = new MySqlCommand(selectSql, connection))
                {
                    command.Parameters.AddWithValue("@id", 1);
                    using (MySqlDataReader reader = command.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            byte[] imageBytes = (byte[])reader["image"];
                            Texture2D texture = new Texture2D(2, 2);
                            texture.LoadImage(imageBytes);
                            // use the texture in your game
                        }
                    }
                }
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 2月15日
  • 已采纳回答 2月7日
  • 修改了问题 2月7日
  • 创建了问题 2月7日