如何从Unity连接到数据库

问题描述:

我正尝试通过Unity连接到MS SQL数据库。但是,当我尝试打开连接时,出现IOException:连接丢失。如何从Unity连接到数据库

我已经从Unity \ Editor \ Data \ Mono \ lib \ mono \ 2.0导入System.Data.dll。我用下面的代码:

using UnityEngine; 
using System.Collections; 
using System.Data.Sql; 
using System.Data.SqlClient; 

public class SQL_Controller : MonoBehaviour { 

    string conString = "Server=myaddress.com,port;" + 
      "Database=databasename;" + 
      "User ID=username;" + 
      "Password=password;"; 

    public string GetStringFromSQL() 
    { 
     LoadConfig(); 
     string result = ""; 

     SqlConnection connection = new SqlConnection(conString); 
     connection.Open(); 
     Debug.Log(connection.State); 
     SqlCommand Command = connection.CreateCommand(); 
     Command.CommandText = "select * from Artykuly2"; 
     SqlDataReader ThisReader = Command.ExecuteReader(); 
     while (ThisReader.Read()) 
     { 
      result = ThisReader.GetString(0); 
     } 
     ThisReader.Close(); 
     connection.Close(); 

     return result; 
    } 
} 

这是我的错误:

IOException: Connection lost 
Mono.Data.Tds.Protocol.TdsComm.GetPhysicalPacketHeader() 
Mono.Data.Tds.Protocol.TdsComm.GetPhysicalPacket() 
Mono.Data.Tds.Protocol.TdsComm.GetByte() 
Mono.Data.Tds.Protocol.Tds.ProcessSubPacket() 
Mono.Data.Tds.Protocol.Tds.NextResult() 
Mono.Data.Tds.Protocol.Tds.SkipToEnd() 
Rethrow as TdsInternalException: Server closed the connection. 
Mono.Data.Tds.Protocol.Tds.SkipToEnd() 
Mono.Data.Tds.Protocol.Tds70.Connect (Mono.Data.Tds.Protocol.TdsConnectionParameters connectionParameters) 
Mono.Data.Tds.Protocol.Tds80.Connect (Mono.Data.Tds.Protocol.TdsConnectionParameters connectionParameters) 

请忽略这种方法的任何安全隐患,我需要进行测试做到这一点,安全以后还会来。 谢谢你的时间。

请忽略任何安全风险,这种做法

不要做这样。安全性会在之前还是之后出现并不重要。您将重写整个代码,因为密码在您的应用程序中被硬编码,可以反编译和检索容易。现在以正确的方式进行连接,以便您不必重写整个应用程序。

在你的服务器上用php,perl或任何你喜欢的语言在服务器上运行你的数据库命令,但是这应该在服务器上完成。

从Unity开始,使用WWWUnityWebRequest类与该脚本进行通信,然后,您将能够从Unity向服务器发送和接收信息。有很多examplesthere。即使这样,你仍然需要实现自己的安全,但是这比现在好得多。

您还可以用json接收数据倍数。

以下是来自this Unity Wiki的完整示例。它展示了如何在Unity中使用服务器端的php和客户端的Unity + C#与数据库进行交互。

服务器端

添加分数与PDO

<?php 
     // Configuration 
     $hostname = 'localhot'; 
     $username = 'yourusername'; 
     $password = 'yourpassword'; 
     $database = 'yourdatabase'; 

     $secretKey = "mySecretKey"; // Change this value to match the value stored in the client javascript below 

     try { 
      $dbh = new PDO('mysql:host='. $hostname .';dbname='. $database, $username, $password); 
     } catch(PDOException $e) { 
      echo '<h1>An error has ocurred.</h1><pre>', $e->getMessage() ,'</pre>'; 
     } 

     $realHash = md5($_GET['name'] . $_GET['score'] . $secretKey); 
     if($realHash == $hash) { 
      $sth = $dbh->prepare('INSERT INTO scores VALUES (null, :name, :score)'); 
      try { 
       $sth->execute($_GET); 
      } catch(Exception $e) { 
       echo '<h1>An error has ocurred.</h1><pre>', $e->getMessage() ,'</pre>'; 
      } 
     } 
?> 

找回得分与PDO

<?php 
    // Configuration 
    $hostname = 'localhost'; 
    $username = 'yourusername'; 
    $password = 'yourpassword'; 
    $database = 'yourdatabase'; 

    try { 
     $dbh = new PDO('mysql:host='. $hostname .';dbname='. $database, $username, $password); 
    } catch(PDOException $e) { 
     echo '<h1>An error has occurred.</h1><pre>', $e->getMessage() ,'</pre>'; 
    } 

    $sth = $dbh->query('SELECT * FROM scores ORDER BY score DESC LIMIT 5'); 
    $sth->setFetchMode(PDO::FETCH_ASSOC); 

    $result = $sth->fetchAll(); 

    if(count($result) > 0) { 
     foreach($result as $r) { 
      echo $r['name'], "\t", $r['score'], "\n"; 
     } 
    } 
?> 

服务器上启用跨域策略:

该文件应命名为“crossdomain.xml”,并放置在Web服务器的根目录下。 Unity要求您希望通过WWW请求访问的网站具有跨域策略。

<?xml version="1.0"?> 
<cross-domain-policy> 
<allow-access-from domain="*"/> 
</cross-domain-policy> 

客户端/统一侧

从Unity客户端代码连接到服务器,以PDO相互作用并增加或检索分数取决于哪个函数被调用。此客户端代码稍作修改以使用最新的Unity版本进行编译。

private string secretKey = "mySecretKey"; // Edit this value and make sure it's the same as the one stored on the server 
public string addScoreURL = "http://localhost/unity_test/addscore.php?"; //be sure to add a ? to your url 
public string highscoreURL = "http://localhost/unity_test/display.php"; 

//Text to display the result on 
public Text statusText; 

void Start() 
{ 
    StartCoroutine(GetScores()); 
} 

// remember to use StartCoroutine when calling this function! 
IEnumerator PostScores(string name, int score) 
{ 
    //This connects to a server side php script that will add the name and score to a MySQL DB. 
    // Supply it with a string representing the players name and the players score. 
    string hash = Md5Sum(name + score + secretKey); 

    string post_url = addScoreURL + "name=" + WWW.EscapeURL(name) + "&score=" + score + "&hash=" + hash; 

    // Post the URL to the site and create a download object to get the result. 
    WWW hs_post = new WWW(post_url); 
    yield return hs_post; // Wait until the download is done 

    if (hs_post.error != null) 
    { 
     print("There was an error posting the high score: " + hs_post.error); 
    } 
} 

// Get the scores from the MySQL DB to display in a GUIText. 
// remember to use StartCoroutine when calling this function! 
IEnumerator GetScores() 
{ 
    statusText.text = "Loading Scores"; 
    WWW hs_get = new WWW(highscoreURL); 
    yield return hs_get; 

    if (hs_get.error != null) 
    { 
     print("There was an error getting the high score: " + hs_get.error); 
    } 
    else 
    { 
     statusText.text = hs_get.text; // this is a GUIText that will display the scores in game. 
    } 
} 

public string Md5Sum(string strToEncrypt) 
{ 
    System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding(); 
    byte[] bytes = ue.GetBytes(strToEncrypt); 

    // encrypt bytes 
    System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); 
    byte[] hashBytes = md5.ComputeHash(bytes); 

    // Convert the encrypted bytes back to a string (base 16) 
    string hashString = ""; 

    for (int i = 0; i < hashBytes.Length; i++) 
    { 
     hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0'); 
    } 

    return hashString.PadLeft(32, '0'); 
} 

这仅仅是如何正确地做到这一点的例子。如果您需要实施会话功能并关心安全性,请查看协议的OAuth 2.0。应该有现有的库,可以帮助开始使用协议OAuth协议。

+0

我已经设法建立一个连接跟随你的第一个例子,并发布并从表中获取结果。谢谢。 – MLazowski

+0

太棒了。很高兴你没有坚持这样做。 – Programmer