需要先导入dll 在unity安装目录下Editor\Data\Mono\lib\mono\unity中找到 I18N,I18N.CJK,I18N.West,System.Data这几个dll
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Data.SqlClient;
using System;
using System.Data;
public class SQL : MonoBehaviour
{
private string connectionString;
private SqlConnection dbConnection;
// Start is called before the first frame update
void Start()
{
ConnectSQL();
// Write();
// Del();
Modify("25","1");
}
float a = 0;
// Update is called once per frame
void Update()
{
if (Time.time>a)
{
a += 30f;
ReadSQL();
}
}
//连接
public void ConnectSQL()
{
connectionString = "Server=127.0.0.1;user=sa;pwd =123456;database=Play";
dbConnection = new SqlConnection(connectionString); //连接
try
{
dbConnection.Open();
Debug.Log("ok");
}
catch (Exception e)
{
Debug.Log("no" + e);
throw;
}
}
//读取
public void ReadSQL()
{
string str = "";
//数据库操作语句
string sql = "select * from Player";
//数据库操作
SqlDataAdapter sda = new SqlDataAdapter(sql, connectionString);
//结果集
DataSet ds = new DataSet();
//将查询的结果放入结果集
sda.Fill(ds, "Player");
//按行和列打印出数据
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
{
str += ds.Tables[0].Rows[i][j].ToString().Trim() + " ";
if (j == ds.Tables[0].Columns.Count - 1)
{
print(str);
str = "";
}
}
}
print("jhsgahjdh");
string st = ds.Tables[0].Rows[0][1].ToString().Trim();//Tables 第几张表
print(st + "st");
}
//写入
public void Write()
{
string sql = "insert into Player(Usname,Age) VALUES('c',3)"; //Player表名 (Usname,Age)列名 ('c',3)插入的值
SqlCommand cmd = new SqlCommand(sql, dbConnection);
try
{
cmd.ExecuteNonQuery();
Debug.Log("写入成功");
}
catch (Exception e)
{
Debug.Log( e);
throw;
}
// dbConnection.Dispose();
}
//删除
public void Del()
{
string sql = "DELETE FROM Player WHERE Usname='c';"; //Player表名 Usname列名 'c'删除列的值
SqlCommand cmd = new SqlCommand(sql, dbConnection);
try
{
cmd.ExecuteNonQuery();
Debug.Log("删除成功");
}
catch (Exception e)
{
Debug.Log( e);
throw;
}
// dbConnection.Dispose();
}
//修改
public void Modify(string ne,string old)
{
//string sql = "UPDATE Player SET Age='25' WHERE Age='1';"; //Player表名 Age修改的列名 新数据where需要修改的数据
string sql = "UPDATE Player SET Age='"+ne+"' WHERE Age='"+old+"';";
SqlCommand cmd = new SqlCommand(sql, dbConnection);
try
{
cmd.ExecuteNonQuery();
Debug.Log("修改成功");
}
catch (Exception e)
{
Debug.Log( e);
throw;
}
//dbConnection.Dispose();
}
}