向SQL Server数据库中添加数据

最近一些朋友问我u3d PC端 连接数据库的问题。现在抽出一点时间,为大家写一个连接数据库以及打印出数据表中的数据案例


首先,我们需要添加一个外部引用 Unity3D连接Sql Server数据库详解    


然后在VS 中添加引用


Unity3D连接Sql Server数据库详解


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


Unity3D连接Sql Server数据库详解


Unity3D连接Sql Server数据库详解


好了!准备工作我们已经做好啦~~


最后我们会提供源码文件下载地址


接下来我们来试着连接数据库。


我就直接贴出代码了:


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);
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值