43
46

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UnityでMySQLを使用する

Last updated at Posted at 2014-03-24

UnityでMySQLを使用する

実行環境 :
MacOS 10.7.5, Windows8.1
Unity4.3.1

MySQL Connectorのダウンロード

http://dev.mysql.com/downloads/connector/net/
こちらよりMono用のMySQL Connectorをダウンロードします.

Select Platform: で .NET & Mono を選択

ConnectorをUnityにインポート

ダウンロードして得られたファイルの中で、
mysql-connector-net-x.x.x-noinstall > v2.0 > mysql.data.dll
をUnityAsset内の Plugins フォルダに入れる.

Api Compatibility Level を変更

Player Settings > Optimization > Api Compatibility Level を
.NET 2.0 に変更

コード例


using UnityEngine;
using System;
using System.Collections;

using MySql.Data;
using MySql.Data.MySqlClient;

public class MySQLTest : MonoBehaviour {

	string SERVER    = "localhost";
	string DATABASE  = "database";
	string USERID    = "root";
	string PORT      = "3306";
	string PASSWORD  = "pass";
        string TABLENAME = "hoge";
	
	void Start () {

		StartCoroutine ( SelectData () );
			
	}

	IEnumerator SelectData () {

		MySqlConnection con = null;

		string conCmd = 
				"server="+SERVER+";" +
				"database="+DATABASE+";" +
				"userid="+USERID+";" +
				"port="+PORT+";" +
				"password="+PASSWORD;

		try {

			con = new MySqlConnection( conCmd );
			con.Open ();

		} catch (MySqlException ex){
			Debug.Log ( ex.ToString() );
		}

		string selCmd = "SELECT * FROM TABLENAME LIMIT 0, 1200;";
		
		MySqlCommand cmd = new MySqlCommand( selCmd, con );
		
		IAsyncResult iAsync = cmd.BeginExecuteReader ();
		
		while ( !iAsync.IsCompleted ){
			yield return 0;
		}
		
		MySqlDataReader rdr = cmd.EndExecuteReader ( iAsync );
		
		while ( rdr.Read() ) {
			if( !rdr.IsDBNull ( rdr.GetOrdinal ("ID") ) ){
				//Debug.Log ( "ID : " + rdr.GetString ("ID") );
			}
		}
		
		rdr.Close ();
		rdr.Dispose ();
		con.Close ();
		con.Dispose ();
	}
}


※非同期で動きません (> <)

43
46
10

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
43
46

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?