Advertisement
Guest User

MySQL Connector UNITY3D

a guest
Apr 15th, 2013
733
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 12.74 KB | None | 0 0
  1. using UnityEngine;
  2. using MySql.Data;
  3. using MySql.Data.MySqlClient;
  4. using System;
  5. using System.Data;
  6. using System.Collections;
  7. using System.Collections.Generic;
  8.  
  9. public class MySQLCS : MonoBehaviour
  10. {
  11.     // In truth, the only things you want to save to the database are dynamic objects
  12.     // static objects in the scene will always exist, so make sure to set your Tag
  13.     // based on the documentation for this demo
  14.  
  15.     // values to match the database columns
  16.     string ID, Name, levelname, objectType;
  17.     float posx, posy, posz, tranx, trany, tranz;
  18.  
  19.     bool saving = false;
  20.     bool loading = false;
  21.     // MySQL instance specific items
  22.     string constr = "Server=localhost;Database=unity.db;User ID=UNIYENGINE;Password=UNIYENGINEUNIYENGINE;Pooling=true";
  23.     // connection object
  24.     MySqlConnection con = null;
  25.     // command object
  26.     MySqlCommand cmd = null;
  27.     // reader object
  28.     MySqlDataReader rdr = null;
  29.     // object collection array
  30.     GameObject[] bodies;
  31.     // object definitions
  32.     public struct data
  33.     {
  34.         public int UID;
  35.         public string ID, Name, levelname, objectType;
  36.         public float posx, posy, posz, tranx, trany, tranz;
  37.     }
  38.     // collection container
  39.     List<data> _GameItems;
  40.     void Awake()
  41.     {
  42.         try
  43.         {
  44.             // setup the connection element
  45.             con = new MySqlConnection(constr);
  46.  
  47.             // lets see if we can open the connection
  48.             con.Open();
  49.             Debug.Log("Connection State: " + con.State);
  50.         }
  51.         catch (Exception ex)
  52.         {
  53.             Debug.Log(ex.ToString());
  54.         }
  55.  
  56.     }
  57.  
  58.     void OnApplicationQuit()
  59.     {
  60.         Debug.Log("killing con");
  61.         if (con != null)
  62.         {
  63.             if (con.State.ToString() != "Closed")
  64.                 con.Close();
  65.             con.Dispose();
  66.         }
  67.     }
  68.  
  69.     // Use this for initialization
  70.     void Start()
  71.     {
  72.  
  73.     }
  74.  
  75.     // Update is called once per frame
  76.     void Update()
  77.     {
  78.  
  79.     }
  80.  
  81.  
  82.     // gui event like a button, etc
  83.     void OnGUI()
  84.     {
  85.         if (GUI.Button(new Rect(10, 70, 50, 30), "Save") && !saving)
  86.         {
  87.             saving = true;
  88.             // first lets clean out the databae
  89.             DeleteEntries();
  90.             // now lets save the scene information
  91.             InsertEntries();
  92.             // you could also use the update if you know the ID of the item already saved
  93.  
  94.             saving = false;
  95.         }
  96.         if (GUI.Button(new Rect(10, 110, 50, 30), "Load") && !loading)
  97.         {
  98.             loading = true;
  99.             // lets read the items from the database
  100.             ReadEntries();
  101.             // now display what is known about them to our log
  102.             LogGameItems();
  103.             loading = false;
  104.         }
  105.     }
  106.  
  107.     // Insert new entries into the table
  108.     void InsertEntries()
  109.     {
  110.         prepData();
  111.         string query = string.Empty;
  112.         // Error trapping in the simplest form
  113.         try
  114.         {
  115.             query = "INSERT INTO demo_table (ID, Name, levelname, objectType, posx, posy, posz, tranx, trany, tranz) VALUES (?ID, ?Name, ?levelname, ?objectType, ?posx, ?posy, ?posz, ?tranx, ?trany, ?tranz)";
  116.             if (con.State.ToString() != "Open")
  117.                 con.Open();
  118.             using (con)
  119.             {
  120.                 foreach (data itm in _GameItems)
  121.                 {
  122.                     using (cmd = new MySqlCommand(query, con))
  123.                     {
  124.                         MySqlParameter oParam = cmd.Parameters.Add("?ID", MySqlDbType.VarChar);
  125.                         oParam.Value = itm.ID;
  126.                         MySqlParameter oParam1 = cmd.Parameters.Add("?Name", MySqlDbType.VarChar);
  127.                         oParam1.Value = itm.Name;
  128.                         MySqlParameter oParam2 = cmd.Parameters.Add("?levelname", MySqlDbType.VarChar);
  129.                         oParam2.Value = itm.levelname;
  130.                         MySqlParameter oParam3 = cmd.Parameters.Add("?objectType", MySqlDbType.VarChar);
  131.                         oParam3.Value = itm.objectType;
  132.                         MySqlParameter oParam4 = cmd.Parameters.Add("?posx", MySqlDbType.Float);
  133.                         oParam4.Value = itm.posx;
  134.                         MySqlParameter oParam5 = cmd.Parameters.Add("?posy", MySqlDbType.Float);
  135.                         oParam5.Value = itm.posy;
  136.                         MySqlParameter oParam6 = cmd.Parameters.Add("?posz", MySqlDbType.Float);
  137.                         oParam6.Value = itm.posz;
  138.                         MySqlParameter oParam7 = cmd.Parameters.Add("?tranx", MySqlDbType.Float);
  139.                         oParam7.Value = itm.tranx;
  140.                         MySqlParameter oParam8 = cmd.Parameters.Add("?trany", MySqlDbType.Float);
  141.                         oParam8.Value = itm.trany;
  142.                         MySqlParameter oParam9 = cmd.Parameters.Add("?tranz", MySqlDbType.Float);
  143.                         oParam9.Value = itm.tranz;
  144.                         cmd.ExecuteNonQuery();
  145.                     }
  146.                 }
  147.             }
  148.         }
  149.         catch (Exception ex)
  150.         {
  151.             Debug.Log(ex.ToString());
  152.         }
  153.         finally
  154.         {
  155.         }
  156.     }
  157.  
  158.     // Update existing entries in the table based on the iddemo_table
  159.     void UpdateEntries()
  160.     {
  161.         prepData();
  162.         string query = string.Empty;
  163.         // Error trapping in the simplest form
  164.         try
  165.         {
  166.             query = "UPDATE demo_table SET ID=?ID, Name=?Name, levelname=?levelname, objectType=?objectType, posx=?posx, posy=?posy, posz=?posz, tranx=?tranx, trany=?trany, tranz=?tranz WHERE iddemo_table=?UID";
  167.             if (con.State.ToString() != "Open")
  168.                 con.Open();
  169.             using (con)
  170.             {
  171.                 foreach (data itm in _GameItems)
  172.                 {
  173.                     using (cmd = new MySqlCommand(query, con))
  174.                     {
  175.                         MySqlParameter oParam = cmd.Parameters.Add("?ID", MySqlDbType.VarChar);
  176.                         oParam.Value = itm.ID;
  177.                         MySqlParameter oParam1 = cmd.Parameters.Add("?Name", MySqlDbType.VarChar);
  178.                         oParam1.Value = itm.Name;
  179.                         MySqlParameter oParam2 = cmd.Parameters.Add("?levelname", MySqlDbType.VarChar);
  180.                         oParam2.Value = itm.levelname;
  181.                         MySqlParameter oParam3 = cmd.Parameters.Add("?objectType", MySqlDbType.VarChar);
  182.                         oParam3.Value = itm.objectType;
  183.                         MySqlParameter oParam4 = cmd.Parameters.Add("?posx", MySqlDbType.Float);
  184.                         oParam4.Value = itm.posx;
  185.                         MySqlParameter oParam5 = cmd.Parameters.Add("?posy", MySqlDbType.Float);
  186.                         oParam5.Value = itm.posy;
  187.                         MySqlParameter oParam6 = cmd.Parameters.Add("?posz", MySqlDbType.Float);
  188.                         oParam6.Value = itm.posz;
  189.                         MySqlParameter oParam7 = cmd.Parameters.Add("?tranx", MySqlDbType.Float);
  190.                         oParam7.Value = itm.tranx;
  191.                         MySqlParameter oParam8 = cmd.Parameters.Add("?trany", MySqlDbType.Float);
  192.                         oParam8.Value = itm.trany;
  193.                         MySqlParameter oParam9 = cmd.Parameters.Add("?tranz", MySqlDbType.Float);
  194.                         oParam9.Value = itm.tranz;
  195.                         MySqlParameter oParam10 = cmd.Parameters.Add("?UID", MySqlDbType.Int32);
  196.                         oParam10.Value = itm.UID;
  197.  
  198.                         cmd.ExecuteNonQuery();
  199.                     }
  200.                 }
  201.             }
  202.         }
  203.         catch (Exception ex)
  204.         {
  205.             Debug.Log(ex.ToString());
  206.         }
  207.         finally
  208.         {
  209.         }
  210.     }
  211.  
  212.     // Delete entries from the table
  213.     void DeleteEntries()
  214.     {
  215.         string query = string.Empty;
  216.         // Error trapping in the simplest form
  217.         try
  218.         {
  219.             // optimally you will know which items you want to delete from the database
  220.             // using the following code and the record ID, you can delete the entry
  221.             //-----------------------------------------------------------------------
  222.             // query = "DELETE FROM demo_table WHERE iddemo_table=?UID";
  223.             // MySqlParameter oParam = cmd.Parameters.Add("?UID", MySqlDbType.Int32);
  224.             // oParam.Value = 0;
  225.             //-----------------------------------------------------------------------
  226.             query = "DELETE FROM demo_table WHERE iddemo_table";
  227.             if (con.State.ToString() != "Open")
  228.                 con.Open();
  229.             using (con)
  230.             {
  231.                 using (cmd = new MySqlCommand(query, con))
  232.                 {
  233.                     cmd.ExecuteNonQuery();
  234.                 }
  235.             }
  236.         }
  237.         catch (Exception ex)
  238.         {
  239.             Debug.Log(ex.ToString());
  240.         }
  241.         finally
  242.         {
  243.         }
  244.     }
  245.  
  246.     // Read all entries from the table
  247.     void ReadEntries()
  248.     {
  249.         string query = string.Empty;
  250.         if (_GameItems == null)
  251.             _GameItems = new List<data>();
  252.         if (_GameItems.Count > 0)
  253.             _GameItems.Clear();
  254.         // Error trapping in the simplest form
  255.         try
  256.         {
  257.             query = "SELECT * FROM view_demo";
  258.             if (con.State.ToString() != "Open")
  259.                 con.Open();
  260.             using (con)
  261.             {
  262.                 using (cmd = new MySqlCommand(query, con))
  263.                 {
  264.                     rdr = cmd.ExecuteReader();
  265.                     if (rdr.HasRows)
  266.                         while (rdr.Read())
  267.                         {
  268.                             data itm = new data();
  269.                             itm.UID = int.Parse(rdr["iddemo_table"].ToString());
  270.                             itm.ID = rdr["ID"].ToString();
  271.                             itm.levelname = rdr["levelname"].ToString();
  272.                             itm.Name = rdr["Name"].ToString();
  273.                             itm.objectType = rdr["objectType"].ToString();
  274.                             itm.posx = float.Parse(rdr["posx"].ToString());
  275.                             itm.posy = float.Parse(rdr["posy"].ToString());
  276.                             itm.posz = float.Parse(rdr["posz"].ToString());
  277.                             itm.tranx = float.Parse(rdr["tranx"].ToString());
  278.                             itm.trany = float.Parse(rdr["trany"].ToString());
  279.                             itm.tranz = float.Parse(rdr["tranz"].ToString());
  280.                             _GameItems.Add(itm);
  281.                         }
  282.                     rdr.Dispose();
  283.                 }
  284.             }
  285.         }
  286.         catch (Exception ex)
  287.         {
  288.             Debug.Log(ex.ToString());
  289.         }
  290.         finally
  291.         {
  292.         }
  293.     }
  294.  
  295.     /// <summary>
  296.     /// Lets show what was read back to the log window
  297.     /// </summary>
  298.     void LogGameItems()
  299.     {
  300.         if (_GameItems != null)
  301.         {
  302.             if (_GameItems.Count > 0)
  303.             {
  304.                 foreach (data itm in _GameItems)
  305.                 {
  306.                     Debug.Log("UID: " + itm.UID);
  307.                     Debug.Log("ID: " + itm.ID);
  308.                     Debug.Log("levelname: " + itm.levelname);
  309.                     Debug.Log("Name: " + itm.Name);
  310.                     Debug.Log("objectType: " + itm.objectType);
  311.                     Debug.Log("posx: " + itm.posx);
  312.                     Debug.Log("posy: " + itm.posy);
  313.                     Debug.Log("posz: " + itm.posz);
  314.                     Debug.Log("tranx: " + itm.tranx);
  315.                     Debug.Log("trany: " + itm.trany);
  316.                     Debug.Log("tranz: " + itm.tranz);
  317.                 }
  318.             }
  319.         }
  320.     }
  321.  
  322.     /// <summary>
  323.     /// This method prepares the data to be saved into our database
  324.     ///
  325.     /// </summary>
  326.     void prepData()
  327.     {
  328.         bodies = GameObject.FindGameObjectsWithTag("Savable");
  329.         _GameItems = new List<data>();
  330.         data itm;
  331.         foreach (GameObject body in bodies)
  332.         {
  333.             itm = new data();
  334.             itm.ID = body.name + "_" + body.GetInstanceID();
  335.             itm.Name = body.name;
  336.             itm.levelname = Application.loadedLevelName;
  337.             itm.objectType = body.name.Replace("(Clone)", "");
  338.             itm.posx = body.transform.position.x;
  339.             itm.posy = body.transform.position.y;
  340.             itm.posz = body.transform.position.z;
  341.             itm.tranx = body.transform.rotation.x;
  342.             itm.trany = body.transform.rotation.y;
  343.             itm.tranz = body.transform.rotation.z;
  344.             _GameItems.Add(itm);
  345.         }
  346.         Debug.Log("Items in collection: " + _GameItems.Count);
  347.     }
  348. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement