Unity 将Excel表格中的数据导入到Mysql数据表中

1.Mysql数据表users如下:

2.即将导入的Excel表格如下:

3.代码如下:

cs 复制代码
using System;
using System.Data;
using System.IO;
using Excel;
using MySql.Data.MySqlClient;
using UnityEngine;
using UnityEditor;

public class ImportExcel
{
    // 数据库连接字符串,需根据实际情况修改
    private const string ConnectionString = "server=localhost;database=mygamedb;uid=root;pwd=123456;";

    [MenuItem("Excel操作/导入Excel数据到MySQL")]
    static void ImportExcelToMySQL()
    {
        string excelPath = Application.streamingAssetsPath + "/学生信息.xlsx";
        try
        {
            // 读取Excel数据
            DataRowCollection dataRows = ReadExcel(excelPath);
            if (dataRows != null && dataRows.Count > 0)
            {
                // 连接MySQL数据库并插入数据
                InsertDataToMySQL(dataRows);
            }
        }
        catch (Exception e)
        {
            Debug.LogError("导入数据时出错:" + e.Message);
        }
    }

    private static DataRowCollection ReadExcel(string path)
    {
        try
        {
            using (FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read))
            {
                IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
                DataSet result = excelReader.AsDataSet();
                return result.Tables[0].Rows;
            }
        }
        catch (Exception e)
        {
            Debug.LogError("读取Excel文件时出错:" + e.Message);
            return null;
        }
    }

    private static void InsertDataToMySQL(DataRowCollection dataRows)
    {
        using (MySqlConnection connection = new MySqlConnection(ConnectionString))
        {
            try
            {
                connection.Open();
                // 查询当前最大的id值
                string str_总数据条数 = "SELECT COUNT(*) AS total_records FROM users";
                MySqlCommand maxIdCommand = new MySqlCommand(str_总数据条数, connection);
                object obj_总数据条数 = maxIdCommand.ExecuteScalar();
                Debug.Log(Convert.ToInt32(obj_总数据条数));


                // 插入语句包含id字段,数据库自增长会自动赋值
                string insertQuery = "INSERT INTO users (id, username, password, registerdate) VALUES (@id, @username, @password, @registerdate)";
                using (MySqlCommand command = new MySqlCommand(insertQuery, connection))
                {
                    // 从第二行开始插入数据,跳过标题行
                    for (int i = 1; i < dataRows.Count; i++)
                    {
                        DataRow row = dataRows[i];
                        command.Parameters.Clear();
                        command.Parameters.AddWithValue("@id", Convert.ToInt32(obj_总数据条数)+i);
                        command.Parameters.AddWithValue("@username", row[0]);
                        command.Parameters.AddWithValue("@password", row[1]);
                        // 处理日期格式,假设Excel中的日期格式可直接转换
                        DateTime registerDate;
                        if (DateTime.TryParse(row[2].ToString(), out registerDate))
                        {
                            command.Parameters.AddWithValue("@registerdate", registerDate);
                        }
                        else
                        {
                            Debug.LogWarning("无法解析日期:" + row[2] + ",使用默认值");
                            command.Parameters.AddWithValue("@registerdate", DateTime.Now);
                        }
                        command.ExecuteNonQuery();
                    }
                }
                Debug.Log("数据成功导入到MySQL数据库");
            }
            catch (Exception e)
            {
                Debug.LogError("插入数据到MySQL时出错:" + e.Message);
            }
        }
    }
}
相关推荐
不羁。。1 小时前
【撸靶笔记】第七关:GET - Dump into outfile - String
数据库·笔记·oracle
yangchanghua1113 小时前
pgsql 如何查询今天范围内的数据(当天0点0分0秒 - 当天23点59分59秒....)
数据库·pgsql
larance3 小时前
SQLAlchemy 的异步操作来批量保存对象列表
数据库·python
python_chai3 小时前
从数据汇总到高级分析,SQL 查询进阶实战(下篇)—— 分组、子查询与窗口函数全攻略
数据库·sql·mysql
在努力的前端小白3 小时前
Spring Boot 敏感词过滤组件实现:基于DFA算法的高效敏感词检测与替换
java·数据库·spring boot·文本处理·敏感词过滤·dfa算法·组件开发
未来之窗软件服务3 小时前
自建知识库,向量数据库 (九)之 量化前奏分词服务——仙盟创梦IDE
数据库·仙盟创梦ide·东方仙盟·自建ai·ai分词
冒泡的肥皂6 小时前
MVCC初学demo(一
数据库·后端·mysql
大霞上仙6 小时前
实现自学习系统,输入excel文件,能学习后进行相应回答
python·学习·excel
.Shu.7 小时前
Redis Reactor 模型详解【基本架构、事件循环机制、结合源码详细追踪读写请求从客户端连接到命令执行的完整流程】
数据库·redis·架构
CodeCraft Studio9 小时前
在 Python 中操作 Excel 文件的高效方案 —— Aspose.Cells for Python
python·ui·excel·报表·aspose·aspose.cells