最近MOMO身心疲惫。。今天是周末在家无聊我还是决定来学习。不知道学什么,就学MySQL吧。本篇主要记录从MySQL安装到局域网内任意机器连接数据库,也算是对自己学习的总结。今天我没用Mac电脑,而是选择Windows,没有别有用心,而是想熟悉一下Windows下操作Unity。
官网上下载MySQL的安装程序,这里有一篇详细的安装文章,http://www.jb51.net/article/23876.htm 为了让中文完美的运行,配置MySQL的时候Character Set处设置成UTF-8,好像默认是不能显示中文。配置完毕后就可以在本机中启动MySQL,也可以在cmd命令行中start和stop 启动与关闭MySQL。
net start mysql
net stop mysql
为了让本机MySQL数据库可以在局域网中任意机器都可以访问,请看 下面这个网址。
http://dzb3688.blog.163.com/blog/static/105068522201292671444891/
文章有一点点讲的不是很清楚,所以我在补充一下、
我用的是Navicat Pewmium查看数据库,我觉得这个数据库挺好的,因为我在Mac上也是用的这个数据库 。(大家可以在网络上下载它,Windows版本居然有汉化的)如下图所示,点击用户,然后双击”root@%” 最后把主机的名字改成 “%”即可、
下面就是重点了,打开cmd 窗口cd到MySQL的路径下,一定要cd到这个路径下,不然mysql 会是无法识别的指令噢。
然后执行命令:
mysql grant all privileges on *.* to root@”%” identified by ‘abc’ with grant option;
flush privileges;
在执行命令:
mysql flush privileges;
OK这样就行了。
然后开始看看代码怎么写,为了方便数据库的创建、增加、删除、修改、查询、我封装了一个类。欢迎大家测试 啦啦啦啦。
SqlAccess.cs
using UnityEngine;
using System;
using System.Data;
using System.Collections;
using MySql.Data.MySqlClient;
using MySql.Data;
using System.IO;
public class SqlAccess
{
public static MySqlConnection dbConnection;
//如果只是在本地的话,写localhost就可以。
// static string host = "localhost";
//如果是局域网,那么写上本机的局域网IP
static string host = "192.168.1.106";
static string id = "root";
static string pwd = "1234";
static string database = "xuanyusong";
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);
}
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 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);
}
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 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;
}
}
然后在来看看调用,把如下脚本绑定在任意对象即可,调用包括、创建表、插入信息、查找信息、删除信息、更新信息。代码比较简单我就不一一注释了,这里我用try catch如果有错误信息将打印在屏幕中。 创建表包括是否递增ID,所以有两种创建表的方式。如果你的数据库是提前预制的话可以这样来读取数据库。
using UnityEngine;
using System;
using System.Data;
using System.Collections;
using MySql.Data.MySqlClient;
using MySql.Data;
using System.IO;
public class NewBehaviourScript : MonoBehaviour {
string Error = null;
void Start ()
{
try
{
SqlAccess sql = new SqlAccess();
sql.CreateTableAutoID("momo",new string[]{"id","name","qq","email","blog"}, new string[]{"int","text","text","text","text"});
//sql.CreateTable("momo",new string[]{"name","qq","email","blog"}, new string[]{"text","text","text","text"});
sql.InsertInto("momo",new string[]{"name","qq","email","blog"},new string[]{"xuanyusong","289187120","xuanyusong@gmail.com","xuanyusong.com"});
sql.InsertInto("momo",new string[]{"name","qq","email","blog"},new string[]{"ruoruo","34546546","ruoruo@gmail.com","xuanyusong.com"});
DataSet ds = sql.SelectWhere("momo",new string[]{"name","qq"},new string []{"id"},new string []{"="},new string []{"1"});
if(ds != null)
{
DataTable table = ds.Tables[0];
foreach (DataRow row in table.Rows)
{
foreach (DataColumn column in table.Columns)
{
Debug.Log(row[column]);
}
}
}
sql.UpdateInto("momo",new string[]{"name","qq"},new string[]{"'ruoruo'","'11111111'"}, "email", "'xuanyusong@gmail.com'" );
sql.Delete("momo",new string[]{"id","email"}, new string[]{"1","'000@gmail.com'"} );
sql.Close();
}catch(Exception e)
{
Error = e.Message;
}
}
// Update is called once per frame
void OnGUI ()
{
if(Error != null)
{
GUILayout.Label(Error);
}
}
}
然后是用到的dll 一个都不能少,不然会出现各种问题。最后的下载地址我会给出,并且包含这些文件。
为了测试局域网的连接, 我还编译到了Android手机上,在Android上访问这个数据库,也是没问题的。当然手机和电脑用的是同一个wifi网络。 目前这个项目在 Windows 和 Android上都可以很好的运行,我感觉在Mac上和iPhone上应该也木有问题,欢迎大家测试,如果发现在别的平台下有问题请告诉我,我会进一步研究的。 欢迎大家留言,一起学习啦啦啦啦 嘿嘿嘿~~。。
下载地址:http://vdisk.weibo.com/s/B5ac9
- 本文固定链接: https://www.xuanyusong.com/archives/2326
- 转载请注明: 雨松MOMO于 雨松MOMO程序研究院 发表





垃圾 只能在PC运行
你牛逼。。
松老师!问个前面的问题——Unity3D研究院之IOS触摸屏手势控制镜头旋转与缩放(八)——能不能实现摄像机目标物体不固定,是我点击的物体变成摄像机目标,而且又不能影响单点触摸的旋转
看看能整合啥ORM框架用呢?想用Linq
宣老师你好,我刚学Unity3D,看了下你的博文,好像大部分是运行在iphone,可是我们公司是做在PC上的,那我看你这些博文还有用吗? 貌似代码会不一样的, 如果有用应该从那部分开始看起啊
下载了打不开什么情况?中文名字的问题?
谢谢松哥了啊,好东西
unity与AR制作有没有啊
我们能做相应的项目,512372842
在ipad上运行时报错:CodePage 1252 not supported,不知道其他同学是否也遇到这个问题?谢谢
刚才的问题已经解决了,PlayerSettings 面板中把Api Compilation Level设置为.NET 2.0,Stripping Level*设置为Strip Assemblies,不过在ipad上运行时报错:CodePage 1252 not supported,不知道这个问题应该如何解决。谢谢
雨松兄,最近很忙吗
Cross compilation job System.Drawing.dll failed.UnityEngine.UnityException: Failed AOT cross compiler: /Applications/Unity/Unity.app/Contents/BuildTargetTools/iPhonePlayer/mono-xcompiler –aot=full,asmonly,nodebug,static,outfile=”System.Drawing.dll.s” “System.Drawing.dll” current dir : /Users/apple/Documents/TestALL/Temp/StagingArea/Data/Managed result file exists: Falsestdout: Mono Ahead of Time compiler – compiling assembly /Users/apple/Documents/TestALL/Temp/StagingArea/Data/Managed/System.Drawing.dllmarshaling type 12 not implemented* Assertion: should not be reached at marshal.c:1915stderr: at UnityEditor.MonoProcessUtility.RunMonoProcess (System.Diagnostics.Process process, System.String name, System.String resultingFile) [0x00000] in :0 at UnityEditor.MonoCrossCompile.CrossCompileAOT (BuildTarget target, System.String crossCompilerAbsolutePath, System.String assembliesAbsoluteDirectory, CrossCompileOptions crossCompileOptions, System.String input, System.String output, System.String additionalOptions) [0x00000] in :0 at UnityEditor.MonoCrossCompile JobCompileAOT.ThreadPoolCallback (System.Object threadContext) [0x00000] in :0 UnityEditor.PostprocessBuildPlayer:Postprocess(BuildTarget, String, String, String, Int32, Int32, String, String, BuildOptions, RuntimeClassRegistry)Error building Player: UnityException: Cross compilation failed.工程文件我未作修改,这是我这里直接发布到ipad时报的错,不确定其他人是否也遇到这个问题
Cross compilation job System.Drawing.dll failed.UnityEngine.UnityException: Failed AOT cross compiler: /Applications/Unity/Unity.app/Contents/BuildTargetTools/iPhonePlayer/mono-xcompiler –aot=full,asmonly,nodebug,static,outfile=”System.Drawing.dll.s” “System.Drawing.dll” current dir : /Users/apple/Documents/TestALL/Temp/StagingArea/Data/Managed result file exists: Falsestdout: Mono Ahead of Time compiler – compiling assembly /Users/apple/Documents/TestALL/Temp/StagingArea/Data/Managed/System.Drawing.dllmarshaling type 12 not implemented* Assertion: should not be reached at marshal.c:1915stderr: at UnityEditor.MonoProcessUtility.RunMonoProcess (System.Diagnostics.Process process, System.String name, System.String resultingFile) [0x00000] in :0 at UnityEditor.MonoCrossCompile.CrossCompileAOT (BuildTarget target, System.String crossCompilerAbsolutePath, System.String assembliesAbsoluteDirectory, CrossCompileOptions crossCompileOptions, System.String input, System.String output, System.String additionalOptions) [0x00000] in :0 at UnityEditor.MonoCrossCompile+JobCompileAOT.ThreadPoolCallback (System.Object threadContext) [0x00000] in :0 UnityEditor.PostprocessBuildPlayer:Postprocess(BuildTarget, String, String, String, Int32, Int32, String, String, BuildOptions, RuntimeClassRegistry)Error building Player: UnityException: Cross compilation failed.工程文件我未作修改,这是我这里直接发布到ipad时报的错,不确定其他人是否也遇到这个问题
为什么我在untiy中运行就可以连接,导出版本的时候连接不上呢,谢谢
PlayerSetting中的Api Compatibility Level选.NET 2.0就可以了(PC)
已经设置了,可以导出版本,只是导出的版本连接不上数据库。mysql的权限和连接数都设置了啊,你们都能连接上吗?
你能写一片关于 TK2D (3D TOOLKIT) 教程吗?资源实在是太少了谢谢
请问Plugins下面的那些依赖文件是从哪里下载的?另外,在MAC下面,test在数据库中会变成CLOB类型的,我用varchar就OK。不知是不是数据库版本的问题。
可能把 呵呵
33行是 DataTable table = ds.Tables[0];
33行是 DataTable table = ds.Tables[0];
大大的程式很好用哦,我下載在獨立項目中,執行的很順。於是我把它移到我的項目後,出現了這個問題,是system.data.dll的問題嗎?
你把我的工程下在下来, 里面有所有dll的。。
我是全都移過去的呀。
说好的 toolManager捏
还没研究啊 兄弟。。嘿嘿
介个也就能在 CS软件里用用咯。 手机用不鸟手机都是用Sqlite 嘿嘿
联网或者局域网的话可以用。。。