Unity连接MySql数据库(2)

前段时间由于要做项目,所以研究了下unity连接mysql数据库的一些相关知识,现在讲自己的一些理解写下来,如果有更好的做法,可以连接我哦。

首先我们需要安装mysql数据库和Navicat for MySQL

mysql和Navicat for MySQL的安装网上有很多,在这里我就不多说了。安装完成后,创建一个名为:testmysql的数据库,字符集选择utf8,如图所示

这里写图片描述

然后自己创建表并设计表,我设计的表如图:

这里写图片描述

自己随便插入一些数据,接下来我们就可以回到unity中了。

unity连接数据库需要通过c#来连接,然后在unity中在调用c#脚本中的方法获取数据库的数据。

首先,我们要创建一个c#代码,命名为SqlAccess,代码如下:

?
1
2
3
4
5
6
7
8
9
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using UnityEngine;
 
 
public class SqlAccess
{
     // static void Main(string[] args) { }
         public static MySqlConnection dbConnection;
         //如果只是在本地的话,写localhost就可以。
         // static string host = "localhost"
         //如果是局域网,那么写上本机的局域网IP
         static string host = "localhost" ;//ip地址,如果是本机则写localhost,如果不是本机,则写安装数据库电脑的ip
         static string id = "root" ;//数据库的用户名
         static string pwd = "1234" ;//数据库的密码
         static string database = "testmysql" ;//数据库的名称  这里我的数据库名称为:examsystem
 
      public SqlAccess()
     {
         OpenSql();
     }
 
 
//}
     public static void OpenSql()
     {
 
         try
         {
             string connectionString = string.Format( "Server = {0};port={4};Database = {1}; User ID = {2}; Password = {3};" , host, database , id, pwd, "3306" );
             dbConnection = new MySqlConnection(connectionString);
             dbConnection. Open ();
         }
         catch (Exception e)
         {
             throw new Exception( "服务器连接失败,请重新检查是否打开MySql服务。" + e.Message.ToString());
 
         }
 
     }
     //添加一个   表
     public DataSet CreateTable(string name , string[] col, string[] colType)
     {
         if (col.Length != colType.Length)
         {
 
             throw new Exception( "columns.Length != colType.Length" );
 
         }
 
         string query = "CREATE TABLE " + name + " (" + col[0] + " " + colType[0];
 
         for ( int i = 1; i < col.Length; ++i)
         {
 
             query += ", " + col[i] + " " + colType[i];
 
         }
 
         query += ")" ;
 
         return ExecuteQuery(query);
     }
 
     public DataSet CreateTableAutoID(string name , string[] col, string[] colType)
     {
         if (col.Length != colType.Length)
         {
 
             throw new Exception( "columns.Length != colType.Length" );
 
         }
 
         string query = "CREATE TABLE " + name + " (" + col[0] + " " + colType[0] + " NOT NULL AUTO_INCREMENT" ;
 
         for ( int i = 1; i < col.Length; ++i)
         {
 
             query += ", " + col[i] + " " + colType[i];
 
         }
 
         query += ", PRIMARY KEY (" + col[0] + ")" + ")" ;
 
         Debug.Log(query);
 
         return ExecuteQuery(query);
     }
 
     //插入一条数据,包括所有,不适用自动累加ID。
     public DataSet InsertInto(string tableName, string[] values )
     {
 
         string query = "INSERT INTO " + tableName + " VALUES (" + "'" + values [0] + "'" ;
 
         for ( int i = 1; i < values .Length; ++i)
         {
 
             query += ", " + "'" + values [i] + "'" ;
 
         }
 
         query += ")" ;
 
         Debug.Log(query);
         return ExecuteQuery(query);
 
     }
 
     //插入部分ID
     public DataSet InsertInto(string tableName, string[] col, string[] values )
     {
 
         if (col.Length != values .Length)
         {
 
             throw new Exception( "columns.Length != colType.Length" );
 
         }
 
         string query = "INSERT INTO " + tableName + " (" + col[0];
         for ( int i = 1; i < col.Length; ++i)
         {
 
             query += ", " + col[i];
 
         }
 
         query += ") VALUES (" + "'" + values [0] + "'" ;
         for ( int i = 1; i < values .Length; ++i)
         {
 
             query += ", " + "'" + values [i] + "'" ;
 
         }
 
         query += ")" ;
 
//        Debug.Log(query);
         return ExecuteQuery(query);
 
     }
     //选择数据库中的id
     public DataSet SelectWhere1(string tableName,string[] items) {
         string query = "SELECT " + items[0];
 
         for ( int i = 1; i < items.Length; ++i)
         {
 
             query += ", " + items[i];
 
         }
 
         query += " FROM " + tableName;
         return ExecuteQuery(query);
     }
     public DataSet SelectWhere(string tableName, string[] items, string[] col, string[] operation, string[] values )
     {
 
         if (col.Length != operation.Length || operation.Length != values .Length)
         {
 
             throw new Exception( "col.Length != operation.Length != values.Length" );
 
         }
 
         string query = "SELECT " + items[0];
 
         for ( int i = 1; i < items.Length; ++i)
         {
 
             query += ", " + items[i];
 
         }
 
         query += " FROM " + tableName + " WHERE " + col[0] + operation[0] + "'" + values [0] + "' " ;
 
         for ( int i = 1; i < col.Length; ++i)
         {
 
             query += " AND " + col[i] + operation[i] + "'" + values [0] + "' " ;
 
         }
 
         return ExecuteQuery(query);
 
     }
     //从数据库中获取所有的用户
     public DataSet GetAllUser(string tableName,string[] items) {
         string query = "SELECT " + items[0];
         for ( int i = 1; i < items.Length; ++i)
         {
 
             query += ", " + items[i];
 
         }
         query += " From " + tableName;
 
         return ExecuteQuery(query);
     }
 
     public DataSet UpdateInto(string tableName, string[] cols, string[] colsvalues, string selectkey, string selectvalue)
     {
 
         string query = "UPDATE " + tableName + " SET " + cols[0] + " = " + colsvalues[0];
 
         for ( int i = 1; i < colsvalues.Length; ++i)
         {
 
             query += ", " + cols[i] + " =" + colsvalues[i];
         }
 
         query += " WHERE " + selectkey + " = " + selectvalue + " " ;
 
         return ExecuteQuery(query);
     }
     //更新一条数据,例如  分数为90,现在想更新为99
     public DataSet updatewhere(string tableName,string score1,string userName) {
         string query= "update " +tableName+ " set score = '" +score1+ "' where user" + " = '" +userName+ "'" ;
 
 
         return ExecuteQuery(query);
     }
 
//求数据库中有多少行数据
public DataSet Count (string tableName){
string query= "select count(*) from " +tableName;
 
return ExecuteQuery(query);
// return query;
}
//检查密码是否正确
     public DataSet CheckPassword111(string tableName,string[] user ) {
         string query = "select password from " + tableName + " where user = '" + user [0]+ "'" ;
 
         return ExecuteQuery(query);
     }
     public DataSet Delete (string tableName, string[] cols, string[] colsvalues)
     {
         string query = "DELETE FROM " + tableName + " WHERE " + cols[0] + " = " + colsvalues[0];
 
         for ( int i = 1; i < colsvalues.Length; ++i)
         {
 
             query += " or " + cols[i] + " = " + colsvalues[i];
         }
         Debug.Log(query);
         return ExecuteQuery(query);
     }
     //删除用户
     public DataSet DeleteUser(string tableName,string col,string colvalue) {
         string query = "delete from " + tableName + " where " + col + " = '" + colvalue + "' " ;
 
         return ExecuteQuery(query);
     }
 
     public void Close ()
     {
 
         if (dbConnection != null )
         {
             dbConnection. Close ();
             dbConnection.Dispose();
             dbConnection = null ;
         }
 
     }
 
     public static DataSet ExecuteQuery(string sqlString)
     {
         if (dbConnection.State == ConnectionState. Open )
         {
             DataSet ds = new DataSet();
             try
             {
 
                 MySqlDataAdapter da = new MySqlDataAdapter(sqlString, dbConnection);
                 da.Fill(ds);
 
             }
             catch (Exception ee)
             {
                 throw new Exception( "SQL:" + sqlString + "/n" + ee.Message.ToString());
 
             }
             finally
             {
             }
             return ds;
         }
         return null ;
     }
 
}

以上代码是连接数据库和一些获取数据库数据的一些方法!对于一些学过数据库语言的同学,会比较好理解,如果没有学过数据库语言,看本文章会有些吃力,建议先去了解一下数据库语言在来看本文章!
接下来我们再创建一个ConnectMysql.cs脚本,代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using UnityEngine;
using System.Collections;
using System.Data;
 
 
public class ConnectMysql : MonoBehaviour {
 
     SqlAccess sql = new SqlAccess();//调用SqlAccess脚本
 
// Use this for initialization
void Start () {
         GetMessageFromSQL();
}
// Update is called once per frame
void Update () {
}
     //从数据库中获取数据
     void GetMessageFromSQL() {
         //调用SqlAccess里面的函数
         DataSet ds=sql.SelectWhere( "login" ,new string[]{ "id" , "userName" , "password" },new string []{ "id" },new string[]{ "=" },new string[]{ "1" });//这句代码的意思是:从表login中,选择出id,userName, password ,当id=1的时候
         if (ds != null ) {
             DataTable table = ds.Tables[0];
             print( "id:" + table . Rows [0][0]+ "    userName:" + table . Rows [0][1]+ "   password:" + table . Rows [0][2]);//输出得到的结果,并打印出来
         }
     }
}

然后我们运行unity,可以看到输出了结果:

这里写图片描述

我们可以与我们数据库中的数据对应一下:

这里写图片描述

unity连接mysql数据库就讲到这里,有兴趣的同学可以多研究一下其他功能!并且数据库语言基础的同学可以在SqlAccess.cs代码里面按照我给的形式自己添加一些函数。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Unity连接MySQL数据库可以通过使用MySQL Connector/NET来实现。下面是一些基本步骤: 1. 下载并安装MySQL Connector/NET:首先,你需要从MySQL官方网站下载并安装MySQL Connector/NET。这是一个用于在.NET应用程序中连接和操作MySQL数据库的驱动程序。 2. 导入MySQL Connector/NET到Unity项目:在Unity中,你需要将MySQL Connector/NET的DLL文件导入到项目中。可以将DLL文件直接拖放到Unity的Assets文件夹中。 3. 编写连接代码:在Unity中,你可以使用C#编写代码来连接MySQL数据库。首先,你需要在代码中引入MySQL Connector/NET的命名空间。然后,使用连接字符串来指定数据库连接信息,包括服务器地址、用户名、密码等。最后,使用MySQL Connector/NET提供的类和方法来执行数据库操作,如查询、插入、更新等。 以下是一个简单的示例代码,展示了如何连接MySQL数据库并执行查询操作: ```csharp using System; using MySql.Data.MySqlClient; public class MySQLConnector : MonoBehaviour { private MySqlConnection connection; private string server = "localhost"; private string database = "your_database_name"; private string uid = "your_username"; private string password = "your_password"; void Start() { string connectionString = $"Server={server};Database={database};Uid={uid};Pwd={password};"; connection = new MySqlConnection(connectionString); try { connection.Open(); Debug.Log("Connected to MySQL database!"); // 执行查询操作 string query = "SELECT * FROM your_table_name"; MySqlCommand cmd = new MySqlCommand(query, connection); MySqlDataReader dataReader = cmd.ExecuteReader(); while (dataReader.Read()) { // 处理查询结果 string column1 = dataReader.GetString(0); string column2 = dataReader.GetString(1); Debug.Log($"Column 1: {column1}, Column 2: {column2}"); } dataReader.Close(); } catch (Exception e) { Debug.Log("Error connecting to MySQL database: " + e.Message); } finally { connection.Close(); } } } ``` 请注意,上述代码仅为示例,你需要根据你的实际情况进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值