Transferred from: http://unity.jb51.net/chengxukaifa/shujukubiancheng/1078.html
Recently some friends asked me to u3d the PC-side connection database problem. Now take a moment to write a connection database and print out a case of data in the data table.
first, we need to add an external reference
Then add a reference in VS
The table of the database test and the data in the data table are posted to everyone:
All right! We're ready to do the work.
(We will provide the source files in the end)
Next we try to connect to the database.
I just put out the code:
using unityengine;using system.collections;using system.data.sqlclient;public class conect : monobehaviour{ /// <summary> /// 1.data source the selected server. Use "." Here. refers to the machine. You can also use the IP address /// 2.Initial Catalog=Test for to specify a database with the name Test /// 3. Login Username ID is sa (not much to say here) /// 4.password set for himself. You can also modify /// </summary> sqlconnection sqlcon = new sqlconnection ("Data source=.;i nitial catalog=test; user id=sa; password=123456; "); sqlcommand cmd = new sqlcommand (); private string tempip; void start () { conectsql (); } /// <summary> /// Connection Database /// </summary> void conectsql () { try { cmd. Connection = sqlcon; cmd. commandtype = system.data.commandtype.text; cmd. commandtext = "Select age from presonal"; // because there's only one piece of data in my database, so here's what it says. sqldataadapter da = new sqldataadapter (cmd); da. SelectCommand.Connection.Open (); &nbsP;tempip = da. Selectcommand.executescalar (). ToString (); da. SelectCommand.Connection.Close (); Sqlcon. Close (); sqlcon. Dispose (); debug.log (TEMPIP); } catch ( System.exception e) { print (e); } }}
Project source code and database : http://unity.jb51.net/yuanma/1079.html
Mount the above script on the object and run it. You will see the effect ...
Unity3d Connecting SQL Server database