Unity3d connecting MySQL database notes 4-unity3d code

Source: Internet
Author: User

New Unity3d Project

Create a new plugins folder

Put the required DLLs into the plugins

New C # script named ToMysql.cs

Not much to say, directly on the code, very simple there are comments, we see it

Using unityengine;using system;using system.collections;using system.data;using Mysql.data.mysqlclient;public class       Tomysql:monobehaviour {public static mysqlconnection dbConnection;/*mysql Database Connection Object */static string host = "";       static string id = "";       static string pwd = "";     static string database = "";             static string result = "";       private string strcommand;  public static DataSet MYOBJ; public string connectionstring;public Vector2 ppos;public Vector2 psize;public DataTable pdatatable;public DataSet pData Set;public Vector2 conpos;public Vector2 consize;  void Awake () {host = "127.0.0.1";  /*mysql Database server address */id = "root";  /*mysql User name */pwd = "123456";  /* Password */database = ' Test ';  /*mysql version number information staged */strcommand = "Select uname from Tuser";  /* Coordinate configuration information for some UI buttons 11*/PPOs = new Vector2 (50,50); PSize = new Vector2 (100,35);  /* Coordinate configuration information for some UI buttons 22*/Conpos = new Vector2 (300,60); Consize = new Vector2(150, 50); /* Default text box default value when initially giving a new employee information */Pkey = "100291";       Name = "Name";  Sex = "male";  Age = "25";  adress = "Home detailed address";     Money = "2800";}   void Ongui () {/* first connected to MySQL database */connectfirstserver ();  /* Displays the version number of the MySQL database to which you are connected */Guilayout.label (result);   /* Major list showing changes to employee information delete function*/showp_guidata ();   /* Add employee Information */addperson ();       /* After modifying the editing information, */Showedit_persondata ();      }/* Close the Unity program */public static void Onapplicationquit () {closesqlconnection (); }/* First connected to MySQL database */public void Connectfirstserver () {if (dbConnection = = null) {GUI.   button (new Rect (Conpos.x, CONPOS.Y,CONSIZE.X,CONSIZE.Y), "Database server address"); Host = GUI.             TextField (New Rect (Conpos.x, CONPOS.Y+50,CONSIZE.X,CONSIZE.Y), host); Gui.   button (new Rect (Conpos.x, conpos.y+100,consize.x,consize.y), "MySQL user name"); id = GUI.          TextField (New Rect (Conpos.x, CONPOS.Y+150,CONSIZE.X,CONSIZE.Y), id); Gui.    button (new Rect (Conpos.x, conpos.y+200,consize.x,consize.y), "password");       PWD = GUI.   TextField (New Rect (Conpos.x, conpos.y+250,consize.x,consize.y), PWD); Gui.            button (new Rect (Conpos.x, CONPOS.Y+300,CONSIZE.X,CONSIZE.Y), "database name"); Database = GUI.     TextField (New Rect (Conpos.x, CONPOS.Y+350,CONSIZE.X,CONSIZE.Y), database); connectionString = string. Format ("Server = {0};D atabase = {1}; User = {2};           Password = {3}; ", host,database,id,pwd); if (GUI. button (new Rect (conpos.x+180, conpos.y+200,consize.x,consize.y), "Login Database")) {opensqlconnection (Conne                ctionstring);            MYOBJ = GetDataSet (strcommand);           /* Read the DATA Function Debug Administrator account password */readerdata ();/* Test Method Debug Administrator account password */showdataset ();/* Reread all employee information in P_info table */selectpdataset ();          }}}//Connect to database private static void Opensqlconnection (string connectionString) {  DbConnection = new Mysqlconnection (connectionString);          try{Dbconnection.open ();  result = Dbconnection.serverversion; /* Get MySQL version */}catch (MySqlException e) {Debug.Log (e.message);d bconnection = Null;host = "Server Connection wrong", id = "Username or password error";p WD = "Username or password error";}    Debug.Log (result);          }/* Close MySQL connection */private static void Closesqlconnection () {dbconnection.close ();      DbConnection = null; }/* Executes some MYSQL statements */public static void Doquery (String sqlquery) {IDbCommand DbCommand = Dbconnec tion.              CreateCommand ();          Dbcommand.commandtext = sqlquery;          IDataReader reader = Dbcommand.executereader (); Reader.          Close ();         reader = null;          Dbcommand.dispose ();      DbCommand = null; #region Get DataSet/* Get a DataSet Object */Public DataSet GetDataSet (string sqlString) {DataSet D          s = new DataSet ();              try {mysqldataadapter da = new Mysqldataadapter (sqlString, dbConnection); Da.               Fill (DS); } catch (Exception ee) {Debug.Log ("SQL:" + Sqlstring + "\ n" + EE.  Message.tostring ());        DbConnection = null;          } return DS; } #endregion/*debug Display the Administrator account password */void Readerdata () {Mysqlcommand Mysqlcommand = new Mysqlcommand ("        SELECT * from Tuser; ", dbConnection);        Mysqldatareader reader = Mysqlcommand.executereader (); try {while (reader. Read ()) {if (reader. HasRows) {print ("uname:" + reader. GetString (0) + "--upwd:" + reader.                GetString (1)); }}} catch (Exception e) {Debug.Log ("Query failed!        "+ e.message);d bconnection = null; } finally {reader.        Close ();                }/*DEBUG Displays the Administrator account password */void showdataset () {String commandstring = "SELECT * from Tuser"; /* Create a DataSet Command object and dataset*/if (dbconnection.state! = ConnectionState.Open) {dbConnection = new Mysqlconnection (c     onnectionstring); Try{Dbconnection.open ();  result = Dbconnection.serverversion;      /* Get MySQL version */} catch (Mysqlexception e) {Debug.Log (e.message);    DbConnection = null;               }} using (Mysqldataadapter DataAdapter = new Mysqldataadapter (CommandString, connectionString)) {                DataSet DataSet = new DataSet ();                /* Populate the DataSet Object */DataAdapter.Fill (DataSet, "Tuser");     /* Get a table from the Dataset */datatable datatable = Dataset.tables[0]; for (int i = 0; i < DataTable. Rows.Count; i++) {Debug.Log (DataTable). rows[i]["Uname"].                    ToString ()); Debug.Log (DataTable. rows[i]["Upwd"].       ToString ());                }}}/* Displays employee information function*/void Selectpdataset () {String commandstring = "SELECT * from P_info"; /* Create a DataSet Command object and dataset*/if (dbconnection.state! = ConnectionState.Open) {dbConnection = new MySQlconnection (connectionString);          try{Dbconnection.open ();  result = Dbconnection.serverversion;           /* Get MySQL version */}catch (mysqlexception e) {Debug.Log (e.message);}}     using (mysqldataadapter DataAdapter = new Mysqldataadapter (CommandString, connectionString)) {if (Pdataset!=null)     {pdataset = null;                } Pdataset = new DataSet ();                /* Populate the DataSet Object */DataAdapter.Fill (Pdataset, "p_info");    /* Get a table from the dataset */if (pdatatable! = null) {pdatatable = null;    } pdatatable = Pdataset.tables[0];  }}/* main list Displays modification of employee information Delete function*/void Showp_guidata () {if (pdatatable! = null) {if (pdatatable = null) return;try{for (int i = 0; I < pdatatable. Rows.Count; i++) {GUI.                    button (new Rect (Ppos.x, Psize.x,psize.y), "name"); Gui.    button (new Rect (ppos.x+100, psize.x,psize.y), "gender"); Gui. Button (New Rect (ppos.x+200, psize.x,PSIZE.Y), "age"); Gui.    button (new Rect (ppos.x+300, psize.x +200,psize.y), "Home detail address"); Gui.                                       button (new Rect (ppos.x+600,15, Psize.x,psize.y), "monthly salary"); Gui. Button (New Rect (ppos.x, Ppos.y +i*35, Psize.x,psize.y), pdatatable. rows[i]["PName"].                    ToString ()); Gui. Button (New Rect (ppos.x+100, Ppos.y +i*35, Psize.x,psize.y), pdatatable. rows[i]["Psex"].    ToString ()); Gui. Button (New Rect (ppos.x+200, Ppos.y +i*35, Psize.x,psize.y), pdatatable. rows[i]["Page"].    ToString ()); Gui. Button (New Rect (ppos.x+300, Ppos.y +i*35, psize.x +200,psize.y), pdatatable. rows[i]["Padress"].    ToString ()); Gui. Button (New Rect (Ppos.x+600,ppos.y +i*35, psize.x,psize.y), pdatatable. rows[i]["Pmoney"].   ToString ()); if (GUI.             button (new Rect (Ppos.x+710,ppos.y +i*35, psize.x,psize.y), "Modify")) {Canedit_person = true; Debug.Log (pdatatable. rows[i]["Pkey"].      ToString ()); Edit_person (pdatatable. rows[i]["Pkey"]. Tostring() );   pdatatable = null; } if (GUI. button (new Rect (Ppos.x+810,ppos.y +i*35, psize.x,psize.y), "delete")) {Deleteperson (pdatatable. rows[i]["Pkey"].     ToString ()); }}if (pdatatable. Rows.count>=1) {if (GUI.    button (new Rect (ppos.x+750,15, psize.x,psize.y), "Increase employee Information")) {Canaddperson = true;        pdatatable = null; }}}catch {Debug.Log ("Some Error");}}}  public string Pkey;public string Name;public string Sex;public string Age;public string Adress;public string money;public bool Canaddperson;public int selgridint = 0;public string[] selsex = new string[] {"Male", "female"};p ublic string sqlstr;/* Add employee Letter Function*/void Addperson () {if (Canaddperson) {GUI. button (new Rect (CONPOS.Y+100,CONSIZE.X,CONSIZE.Y), "Employee unique number"); Pkey = GUI.       TextField (New Rect (Conpos.x, conpos.y+100,consize.x,consize.y), Pkey); Gui. button (new Rect (CONPOS.Y+160,CONSIZE.X,CONSIZE.Y), "name"); Name = GUI.     TextField (New Rect (Conpos.x, conpos.y+160,consize.x,consize.y), name);        Gui. button (new Rect (CONPOS.Y+220,CONSIZE.X,CONSIZE.Y), "gender"); selgridint = GUI. Selectiongrid (New Rect (Conpos.x, conpos.y+220,100,30), Selgridint, Selsex, 2); Gui.         button (new Rect (CONPOS.Y+270,CONSIZE.X,CONSIZE.Y), "age"); Age = GUI. TextField (New Rect (Conpos.x, Conpos.y+270,consize.x,consize.y), age); Gui.   button (new Rect (CONPOS.Y+330,CONSIZE.X,CONSIZE.Y), "home detailed address"); adress = GUI. TextField (New Rect (Conpos.x, conpos.y+330,consize.x,consize.y), adress); Gui. button (new Rect (CONPOS.Y+380,CONSIZE.X,CONSIZE.Y), "employee monthly wage"); money = GUI.  TextField (New Rect (Conpos.x, conpos.y+380,consize.x,consize.y), money); if (GUI. button (new Rect (conpos.x+280, Conpos.y+220,consize.x,consize.y), "Add this employee Information")) {if (pkey. Trim () = = "" | | Name. Trim () = = "" | | Sex. Trim () = = "" | | Age. Trim () = = "" | | Adress. Trim () = = "" | | Money.             Trim () = = "") {Pkey = "Error Please re-enter";                     Name = "Name";                 Sex = "Gender must be male or female";                 Age = "must be a number";                 adress = "Home detailed address"; Money = "Monthly salary must be a number"; return;} if (Selgridint = = 0) {sex = "male";} if (Selgridint = = 1) {sex = "female";}             if (Isnumberic (age) ==false && isnumberic (Money) ==false) {Pkey = "Error Please re-enter";                     Name = "Name";                 Sex = "Gender must be male or female";                 Age = "must be a number";                  adress = "Home detailed address";  Money = "Monthly wage must be a number or exceed the limit"; return;}   #region/* Insert data */try{opensqlconnection (connectionString);    if (dbconnection.state! = ConnectionState.Open) {Dbconnection.open ();} Sqlstr = string. Format ("INSERT into P_info (' Pkey ', ' pname ', ' psex ', ' page ', ' padress ', ' Pmoney ') VALUES (' {0} ', ' {1} ', ' {2} ', ' {3} ', ' {4} ',                    ' {5} ') ", Pkey,name,sex,age,adress,money);                    Mysqlcommand cmd = new Mysqlcommand (sqlstr, dbConnection); Cmd.                    ExecuteNonQuery (); Dbconnection.close ();D ebug. Log ("InsertData"); Canaddperson = false; Selectpdataset ();} catch (Mysqlexception e) {pkey = "error insertion failed";                     Name = "Name";                 Sex = "Gender must be male or female";                 Age = "must be a number";                  adress = "Home detailed address"; Money = "Monthly wage must be a number or exceed the limit";D ebug. Log ("Information entry failed" + E.message);} #endregion}if (GUI. button (new Rect (conpos.x+280, Conpos.y+320,consize.x,consize.y), "return")) {Canaddperson = false; Selectpdataset ();}}} /* Check whether the input is a number */public bool Isnumberic (String message) {/* Determines whether an integer string */* is the case then converts it to a number and sets it to the output value of the out type, returns True, no   then false*/int result =-1; /*result definition */try {/* When the number string is less than 4 o'clock, the following three kinds can be converted, either */* If the number of bits exceeds 4, choose Convert.ToInt32 () and int . Parse () */result = Int.                Parse (message);        return true; } catch {return false;debug.        Log ("number false"); }/* Delete the method */void Deleteperson (String spkey) {#region/* Delete data */try{opensqlconnection (ConnectionS   Tring);   if (dbconnection.state! = ConnectionState.Open) {Dbconnection.open ();}             Sqlstr = string.                    Format ("Delete from P_info where pkey= ' {0} '", Spkey);                    Mysqlcommand cmd = new Mysqlcommand (sqlstr, dbConnection); Cmd.                    ExecuteNonQuery (); Dbconnection.close ();D ebug. Log ("DeleteData"); Selectpdataset ();} catch (Mysqlexception e) {Debug.Log ("Delete failed" + e.message); #endregion}public bool canedit_person;/* Incoming Check to modify the employee's primary key Pkey and read the corresponding data to multiple fields */void Edit_person (string mpkey) {if (canedit_ person) {#region Retrieves the currently selected data string commandString5 = String. Format ("select * from P_info where pkey= ' {0} '", Mpkey);                Debug.Log (COMMANDSTRING5); /* Create a DataSet Command object and dataset*/if (dbconnection.state! = ConnectionState.Open) {dbConnection = new Mysqlconnection (CO      nnectionstring);                  try{Dbconnection.open ();  result = Dbconnection.serverversion;     /* Get MySQL version */} catch (Mysqlexception e) {Debug.Log (e.message); }} using (Mysqldataadapter DataAdapter = new MySQldataadapter (CommandString5, connectionString)) {DataSet spdataset = new DataSet ();                /* Populate the DataSet Object */DataAdapter.Fill (Spdataset, "p_info");        /* Get a table from the dataset */DataTable spdatatable = spdataset.tables[0]; Pkey= spdatatable. rows[0]["Pkey"]. ToString (); Name =spdatatable. rows[0]["PName"]. ToString (); Age =spdatatable. rows[0]["Page"]. ToString (); adress=spdatatable. rows[0]["Padress"].      ToString (); Money=spdatatable. rows[0]["Pmoney"]. ToString ();} #endregion}}/* Click the Edit Data button, the details of the currently selected employee are displayed, and a text box is provided to modify the */void Showedit_persondata () {if (Canedit_person) {/* GUI. button (new Rect (CONPOS.Y+100,CONSIZE.X,CONSIZE.Y), "Employee unique number"); Pkey = GUI. TextField (New Rect (Conpos.x, conpos.y+100,consize.x,consize.y), pkey); */GUI. button (new Rect (CONPOS.Y+160,CONSIZE.X,CONSIZE.Y), "name"); Name = GUI.             TextField (New Rect (Conpos.x, conpos.y+160,consize.x,consize.y), name); Gui. Button (New Rect, Conpos.y+220,coNSIZE.X,CONSIZE.Y), "gender"); selgridint = GUI. Selectiongrid (New Rect (Conpos.x, conpos.y+220,100,30), Selgridint, Selsex, 2); Gui.         button (new Rect (CONPOS.Y+270,CONSIZE.X,CONSIZE.Y), "age"); Age = GUI. TextField (New Rect (Conpos.x, Conpos.y+270,consize.x,consize.y), age); Gui.   button (new Rect (CONPOS.Y+330,CONSIZE.X,CONSIZE.Y), "home detailed address"); adress = GUI. TextField (New Rect (Conpos.x, conpos.y+330,consize.x,consize.y), adress); Gui. button (new Rect (CONPOS.Y+380,CONSIZE.X,CONSIZE.Y), "employee monthly wage"); money = GUI. TextField (New Rect (Conpos.x, conpos.y+380,consize.x,consize.y), money);D Ebug. Log ("Editpersondata"); if (GUI. button (new Rect (conpos.x+280, Conpos.y+220,consize.x,consize.y), "return home")) {Canedit_person = false; Selectpdataset ();} if (GUI. button (new Rect (conpos.x+280, conpos.y+320,consize.x,consize.y), "Modify employee Information")) {if (pkey. Trim () = = "" | | Name. Trim () = = "" | | Sex. Trim () = = "" | | Age. Trim () = = "" | | Adress. Trim () = = "" | | Money.             Trim () = = "") {Pkey = "Error Please re-enter";                     Name = "Name"; Sex = "Gender must be male or female";                 Age = "must be a number";                  adress = "Home detailed address"; Money = "Monthly salary must be a number"; return;} if (Selgridint = = 0) {sex = "male";} if (Selgridint = = 1) {sex = "female";}             if (Isnumberic (age) ==false && isnumberic (Money) ==false) {Pkey = "Error Please re-enter";                     Name = "Name";                 Sex = "Gender must be male or female";                 Age = "must be a number";                  adress = "Home detailed address";  Money = "Monthly wage must be a number or exceed the limit"; return;}   #region/* Update data */try{opensqlconnection (connectionString);    if (dbconnection.state! = ConnectionState.Open) {Dbconnection.open ();} Sqlstr = string.                                          Format ("UPDATE p_info SET pname= ' {0} ', psex= ' {1} ', Page= ' {2} ', Padress= ' {3} ', Pmoney= ' {4} ' WHERE Pkey = ' {5} '",                    Name,sex,age,adress,money, Pkey);                    Mysqlcommand cmd = new Mysqlcommand (sqlstr, dbConnection); Cmd.                    ExecuteNonQuery (); Dbconnection.close ();D ebug. Log ("UpdatedaTa "); Canedit_person = false; Selectpdataset ();}             catch (Mysqlexception e) {pkey = "error update failed";                     Name = "Name";                 Sex = "Gender must be male or female";                 Age = "must be a number";                  adress = "Home detailed address"; Money = "Monthly wage must be a number or exceed the limit";D ebug. Log ("Information entry failed" + E.message);} #endregion}}}}

  

Create a new gameobject, drag and drop the script onto the Gameobject object

Click Run, enter

Server address: 127.0.0.1

User name: Root

Password: 123456

DB name of database to be accessed: test

Click to log into the database

If the login is successful, you will see the information we just inserted

Click to add employee information

Hey, click Add this employee information

Success! Hey!

Click to delete "deep East China" try

Delete Success!

Click to edit Zhang San information

Change gender to female, age is 18, salary is 800, click Edit Employee Information

Modified successfully!

Some friends react, publish can't connect, I test here is no problem,

Please see, after publishing the database connection

Welcome to communicate with me Unity3d technology, QQ2360450496

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.