Unity3D接入MySQL数据库

Unity3D接入MySQL数据库

系統环境:

  • Windows 10(x64)(version 1909)
  • Unity3D (version 2018.3.0f2)
  • Microsoft Visual Studio Community 2017 (version 15.9.4)

操作步驟:

  • (1)准備一個本地或者綫上Mysql數據庫。Y Cheung 的數據庫設置如下:
DATABASE Host: 127.0.0.1
DATABASE Port: 3306
DATABASE Name: my_db
DATABASE Username: root
DATABASE Password: 7vWe4Z@ZT2N#
  • (2) (可選)下載並安裝Mysql Connector/ODBC,如果安裝過程中遇到錯誤(Error 1918),前往官網下載並安裝最新的適合你系統的Visual C++ Redistributable。安裝完成后可以在C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools\ODBC 数据源(64 位)的驅動程序中看到安裝好的驅動
    Mysql Connector/ODBC driver

  • (3)下載並安裝 Mysql Connector/NET ,安裝完成后可以在C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.19\Assemblies\v4.5.2看到以下文件
    MySQL\MySQL Connector Net 8.0.19\Assemblies\v4.5.2

  • (4)在Unity3D Assets中導入上一步驟中C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.19\Assemblies\v4.5.2文件夾裏的以下文件

MySql.Data.dll
BouncyCastle.Crypto.dll
Google.Protobuf.dll
Renci.SshNet.dll
SshNet.Security.Cryptography.dll
Ubiety.Dns.Core.dll

Unity3D import MySQL Connector Net dll

  • (5) 開始你對數據庫操作的代碼,一個簡單的例子
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MySql.Data.MySqlClient;

public class MysqlAccess
{
    public static MySqlConnection mySqlConnection;
    static string host = "127.0.0.1";
    static string user = "root";
    static string pwd = "7vWe4Z@ZT2N";
    static string db = "my_db";
    static string port = "3306";

    public void connectDB()
    {
        Open();
    }
    public static void Open()
    {
        try
        {
            string connectionString = string.Format("Server = {0};port={4};Database = {1}; User ID = {2}; Password = {3};", host, db, user, pwd, port);
            mySqlConnection = new MySqlConnection();
            mySqlConnection.Open();
        }catch(System.Exception e)
        {
            throw new System.Exception(""+e.Message.ToString());
        }
    }

    public void Close()
    {
        if (mySqlConnection != null)
        {
            mySqlConnection.Close();
            mySqlConnection.Dispose();
            mySqlConnection = null;
        }
    }
}

:本文係幫助朋友解決Unity3D對接Mysql的問題,但Y Cheung不建議Unity3D在生產環境直接對數據庫進行操作,這是很危險的行爲

Y Cheung

Y Cheung

Blogger, Programer & Traveler.
Shanghai