2.17 数据库

来源:互联网 发布:数据分享平台 编辑:程序博客网 时间:2024/05/21 09:53
一,SQLite数据库简介
二,SQL语法
(详见:http://www.w3school.com.cn/sql/index.asp)

1,SQL INSERT INTO语句
INSERT INTO 表名称 VALUES(值1,值2,...)
INSERT INTO table_name(列1,列2,...)VALUES(值1,值2,...)
2,SQL DELETE语句
删除表中的某行(表单仍在):
DELETE FROM 表名称 WHERE 条件
3,SQL UPDATE语句
UPDATE 表名称 SET 列名称=新值 WHERE 列名称=某值
4,SQL SELECT 语句
SELECT 列名称 FROM 表名称

三,Unity使用SQLite数据库
1,数据连接:使用SQLiteConnection 对象,进 行数据库连接,此操作可以创建空的数据库.
string path = "data source=" + Application.streamingAssetsPath + "/UserDatabase.sqlite";
void OpenDataBase(string connectionString)
{
try {
conn = new SqliteConnection(connectionString);
conn.Open(); }
catch (System.Exception exc)
{ Debug.Log(exc); } }
2,使用SqliteCommand 数据指令, 对象进行数据库操作
void CreateTable()
{
//判断数据库中是否有UserTable这个表
SqliteCommand cmd = conn.CreateCommand();
cmd.CommandText = "select count(*) from sqlite_master where type = 'table' and name = 'UserTable'";
SqliteDataReader reader = cmd.ExecuteReader();
bool isExit = false;
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
if (reader.GetValue(i).ToString() == "1")
{ isExit = true; }
}
}
//如果表不存在则建表
reader.Dispose();
reader.Close();
reader = null;
if (!isExit) {
Debug.Log("表不存在,建表");
cmd.CommandText = "Create Table UserTable(uname text,pwd text)";
cmd.ExecuteNonQuery();
}
cmd.Dispose();
cmd = null;
CloseDataBase();
3,插入数据
//向UserTable表中插入数据
SqliteCommand cmd = conn.CreateCommand();
cmd.CommandText = "insert into UserTable values( '" + unameInput.text + "' , '" + passwordInput.text + "' )";
try { cmd.ExecuteNonQuery(); }
catch (System.Exception exc)
{ Debug.Log(exc); }

4,查询数据
//创建查询的sql语句
string query = "select pwd from UserTable where uname="+"'"+uname+"'";
SqliteCommand cmd = conn.CreateCommand();
cmd.CommandText = query;
//执行查询操作
SqliteDataReader reader = cmd.ExecuteReader();
//标记表中是否有此条数据
bool result = false;
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
if (reader.GetValue(i).ToString()== pwd)
{
//如果有,就修改标记值
result = true;
}
}
}

5,执行SQL语句的三种方式
1、int ExecuteNonQuery() 返回受影响的行数(常用于执行增删改操作)
2、object ExecuteScalar() 返回查询到的第一个值(常用于只查询一个结果时)
3、SqliteDataReader ExecuteReader() 返回所有查询的结果(SqliteDataReader对象)