简体   繁体   中英

How to connect SQL Server with Unity?

I am trying to store or retrieve an image dynamically using Unity from SQL Server. I am facing issues trying to connect to the SQL Server. How do I connect to the SQL Server?

Unity uses the MONO.NET framework , which is very similar to the Microsoft.NET framework . This is sample code:

public void connect(){
         string connectionString =
             "Server=servername;" +
             "Database=dbname;" +
             "User ID=userid;" +
             "Password=pass;" +
             "Integrated Security=True";

         result = new List<float> ();
         resultCas = new List<DateTime> ();

         using(SqlConnection conn = new SqlConnection(connectionString))
         {
             SqlCommand c; SqlDataReader da; SqlParameter param1; SqlParameter param2; SqlParameter param3; SqlParameter param4;
              conn.Open();
             c = new SqlCommand();
             c.Connection = conn;
             c.CommandType = CommandType.StoredProcedure;
             c.CommandText = "commandtext";
             param1 = c.Parameters.Add("@identify",SqlDbType.Int);        
             param1.Value = 1;
             param2 = c.Parameters.Add("@startTime",SqlDbType.DateTime);
             param2.Value = "2010-11-10 07:45:00.000";
             param3 = c.Parameters.Add("@endTime",SqlDbType.DateTime);
             param3.Value = "2010-11-12 10:15:00.000";
             param4 = c.Parameters.Add("@args",SqlDbType.NVarChar);
             param4.Value = "I";
             da = c.ExecuteReader();
             while (da.Read())
             {
                 resultCas.Add(da.GetDateTime(0));
                 result.Add((float)da.GetDouble(1));
             }
         }
     }

From Unity, use the WWW or UnityWebRequest class to communicate with that script and then, you will be able to send and receive information from Unity to the server. There are many examples out there. You can also receive data multiple with json .

Visit this complete example from this Unity wiki. It shows how to interact with a database in Unity using php and C# on the server side and Unity on the client side.

Hope it Helps.Thanks!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM