今天在网上发现unity连接mysql的教程了学习了有关Unity连接mysql 数据库的方法 好啦不用废话直接代码如下:

?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
usingUnityEngine;
usingSystem;
usingSystem.Collections;
usingSystem.Data;
usingMySql.Data.MySqlClient;
 
publicclassCMySql : MonoBehaviour {
    // Global variables
    privatestaticMySqlConnection dbConnection;
  
     staticstringhost ="192.168.1.100";
     staticstringid ="蛮牛教育";
     staticstringpwd ="123456";
      
     staticstringresult ="";
      
     voidOnGUI()
     {
         host = GUILayout.TextField( host, 200, GUILayout.Width(200));
         id = GUILayout.TextField( id, 200, GUILayout.Width(200));
         pwd = GUILayout.TextField( pwd, 200, GUILayout.Width(200));
         if(GUILayout.Button("Test"))
         {
             stringconnectionString ="Server="+host+";Database=test;User ID="+id+";Password="+pwd+";Pooling=false";
             openSqlConnection( connectionString );
         }
         GUILayout.Label(result);
     }
 
    // On quit
    publicstaticvoidOnApplicationQuit() {
        closeSqlConnection();
    }
    
    // Connect to database
    privatestaticvoidopenSqlConnection(stringconnectionString) {
        dbConnection =newMySqlConnection(connectionString);
        dbConnection.Open();
        result = dbConnection.ServerVersion;
        Debug.Log("Connected to database."+result);
    }
    
    // Disconnect from database
    privatestaticvoidcloseSqlConnection() {
        dbConnection.Close();
        dbConnection =null;
        //Debug.Log("Disconnected from database."+result);
    }
 
    // MySQL Query
    publicstaticvoiddoQuery(stringsqlQuery) {
        IDbCommand dbCommand = dbConnection.CreateCommand();
        dbCommand.CommandText = sqlQuery;
        IDataReader reader = dbCommand.ExecuteReader();
        reader.Close();
        reader =null;
        dbCommand.Dispose();
        dbCommand =null;
    }