Accessing MySQL database using c# on unity?

前端 未结 6 396
面向向阳花
面向向阳花 2021-01-01 23:06

I have just started using C# and do not know much about it. I am using the 3d game engine called Unity and trying to write a c# script to access the MySQL database that I am

6条回答
  •  灰色年华
    2021-01-01 23:57

    I have faced the same problem yesterday and I've found a satisfying solution that works both on PC and Android.

    1: Download .DLL file from here matching your Visual studio project target .NET version (for me 3.5, version 6.9.8.0 worked just fine). If you download a wrong version you will get an error in Unity editor. links to download the file: https://www.dllme.com/dll/files/mysql_data_dll.html or this one: https://downloads.mysql.com/archives/c-net/

    2: Unpack the .DLL file and include it in the project (put it anywhere inside of the Assets folder).

    3: Program your connection to the database ;) here is a short example:

     using System;
     using System.Data;
    
     using MySql.Data;
     using MySql.Data.MySqlClient;
    
     public class Tutorial4
     {
         public static void Main()
         {
             string connStr = "server=localhost;user=root;database=world;port=3306;password=******";
             MySqlConnection conn = new MySqlConnection(connStr);
             try
             {
                 Console.WriteLine("Connecting to MySQL...");
                 conn.Open();
    
                 string sql = "SELECT COUNT(*) FROM Country";
                 MySqlCommand cmd = new MySqlCommand(sql, conn);
                 object result = cmd.ExecuteScalar();
                 if (result != null)
                 {
                     int r = Convert.ToInt32(result);
                     Console.WriteLine("Number of countries in the world database is: " + r);
                 }
    
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.ToString());
             }
    
             conn.Close();
             Console.WriteLine("Done.");
         }
     }
    

提交回复
热议问题