标签:
转自:http://unity.jb51.net/chengxukaifa/shujukubiancheng/1078.html
最近一些朋友问我u3d PC端 连接数据库的问题。现在抽出一点时间,为大家写一个连接数据库以及打印出数据表中的数据案例
首先,我们需要添加一个外部引用
然后在VS 中添加引用

数据库Test的表以及数据表中的数据为大家贴上图:


好了!准备工作我们已经做好啦~~
(最后我们会提供源码文件下载地址)
接下来我们来试着连接数据库。
我就直接贴出代码了:
using UnityEngine;
using System.Collections;
using System.Data.SqlClient;
public class Conect : MonoBehaviour
{
/// <summary>
/// 1.Data Source选择的服务器。这里使用“.”指本机。也可使用IP地址
/// 2.Initial Catalog=Test 为 指定名字为Test的数据库
/// 3.登录用户名Id为sa(这里不用多说)
/// 4.Password为自己设定的。也可修改
/// </summary>
SqlConnection sqlcon = new SqlConnection("Data Source=.;Initial Catalog=Test;User Id=sa;Password=123456;");
SqlCommand cmd = new SqlCommand();
private string tempip;
void Start()
{
ConectSql();
}
/// <summary>
/// 连接数据库
/// </summary>
void ConectSql()
{
try
{
cmd.Connection = sqlcon;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "SELECT age FROM Presonal"; // 因为我的数据库里面只有一条数据,所以这里就这么写了
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.SelectCommand.Connection.Open();
tempip = da.SelectCommand.ExecuteScalar().ToString();
da.SelectCommand.Connection.Close();
sqlcon.Close();
sqlcon.Dispose();
Debug.Log(tempip);
}
catch (System.Exception e)
{
print(e);
}
}
}
项目源码和数据库下载地址:http://unity.jb51.net/yuanma/1079.html
将上面的脚本挂载到物件上,运行。就会看到效果啦。。。
标签:
原文地址:http://www.cnblogs.com/lindan929/p/4380578.html