最近数据库用的比较多,顺便整理下MySQL的常用语句。
1.打开数据库
SqlAccess sql = new SqlAccess();
sql.OpenSql(“数据库名称”);
public MySqlConnection dbConnection;
string host = "localhost";
string id = "root";
public void OpenSql(string db)
{
try
{
string connectionString = string.Format("Server = {0};port={4};Database = {1}; User ID = {2}; Password = {3};charset=utf8;", host, db, id, "密码","端口");
dbConnection = new MySqlConnection(connectionString);
dbConnection.Open();
}
catch (Exception e)
{
UnityEngine.Debug.Log("SQL:服务器连接失败,请重新检查是否打开MySql服务。" + e.Message.ToString());
}
}
2.创建表
sql.CreateTableAutoID(“tablename”,new string[] {“学号”,“姓名” },new string[] { “VARCHAR(255)”,“VARCHAR(255)” });
///
/// 创建表
///
/// 表名
/// 字段名
/// 字段类型
///
public DataSet CreateTableAutoID(string name, string[] col, string[] colType)
{
if (col.Length != colType.Length)
{
UnityEngine.Debug.Log("SQL:columns.Length != colType.Length");
}
//可空类型 最后加" NOT NULL AUTO_INCREMENT"
//不是可空类型 不需要加
string query = "CREATE TABLE " + name.ToString() +" (" + col[0] + " " + colType[0];//+ " NOT NULL AUTO_INCREMENT";
for (int i = 1; i < col.Length; ++i)
{
query += ", " + col[i] + " " + colType[i];
}
query += ", PRIMARY KEY (" + col[0] + ")" + ")";
return ExecuteQuery(query);
}
3.删除表
sql.DeleteTable(“tablename”);
public DataSet DeleteTable(string name)
{
string query = "DROP TABLE " + name.ToString();//+ " NOT NULL AUTO_INCREMENT";
return ExecuteQuery(query);
}
4.插入一条数据
sql.InsertInto(“tablename”,new string[] {“学号”,“姓名” },new string[] { “001”,“张三” });
///
/// 插入数据
///
/// 表名
/// 格式
/// 要插入的数据
///
public DataSet InsertInto(string tableName, string[] col, string[] values)
{
if (col.Length != values.Length)
{
UnityEngine.Debug.Log("SQL:columns.Length != colType.Length");
}
string query = "INSERT INTO " + tableName + " (" + col[0];
for (int i = 1; i < col.Length; ++i)
{
query += ", " + col[i];
}
query += ") VALUES (" + "'" + values[0] + "'";
for (int i = 1; i < values.Length; ++i)
{
query += ", " + "'" + values[i] + "'";
}
query += ")";
return ExecuteQuery(query);
}
5.同时插入多条数据
sql.InsertIntos(“tablename”,new string[] { “学号”, “姓名” },new List
///
/// 插入多条数据
///
/// 表名
/// 格式
/// 要插入的数据
///
public DataSet InsertIntos(string tableName, string[] col, List<string[]> values)
{
try
{
string query = "INSERT IGNORE INTO " + tableName + " (" + col[0];
for (int i = 1; i < col.Length; ++i)
{
query += ", " + col[i];
}
query += ") VALUES " ;
for (int i = 0; i < values.Count; i++)
{
string[] value = values[i];
if (i!=0)
{
query += ",(" + "'" + value[0] + "'";
}
else
{
query += "(" + "'" + value[0] + "'";
}
for (int j = 1; j < value.Length; ++j)
{
query += ", " + "'" + value[j] + "'";
}
query += ")";
}
return ExecuteQuery(query);
}
catch (Exception)
{
return null;
}
}
6.删除数据
///
/// 删除指定数据 cols 键 colsvalues键对应的值 这样可以一次删除多条数据
///
/// 表名
/// 主键
/// 主键对应的值
///
public DataSet Delete(string tableName, string cols, string[] colsvalues)
{
string query = "DELETE FROM " + tableName + " WHERE " + cols + " = '" + colsvalues[0] + "'";
for (int i = 1; i < colsvalues.Length; ++i)
{
query += " or " + cols + " = '" + colsvalues[i]+"'";
}
return ExecuteQuery(query);
}
7.查找
///
/// 获取指定表下的指定数据
///
/// 表名
/// 搜索的字段名称
/// 指定字段的值
/// 匹配的数据
public List<string> SearchAssign(string table, string key, string match)
{
List<string> txet = new List<string>();
if (dbConnection == null)
return txet;
string sqlSearch = "select * from " + table + " WHERE " + key + "=" + match;
MySqlCommand mySqlCommand = new MySqlCommand(sqlSearch, dbConnection);
MySqlDataReader reader = mySqlCommand.ExecuteReader();
try
{
while (reader.Read())
{
if (reader.HasRows)
{
for (int i = 0; i < reader.FieldCount; i++)
{
txet.Add(reader.GetString(i));
}
}
}
}
catch (Exception e)
{
}
finally
{
reader.Close();
}
return txet;
}
///
/// 获取指定表下的匹配数据(LIKE)
///
/// 表名
/// 赛选的字段名称
/// 关键词
/// 匹配的数据
public Dictionary<string, List<string>> SearchMatch(string table,string key,string match)
{
Dictionary<string, List<string>> txet = new Dictionary<string, List<string>>();
if (dbConnection == null)
return txet;
//a可以是N个字符或者汉字
//'%a%' 包含a的
//'%a' 以a结尾的
//'a%' 以a开始的
string sqlSearch = "select * from "+ table+ " WHERE " + key+" LIKE "+ "'%"+ match+ "%'";
MySqlCommand mySqlCommand = new MySqlCommand(sqlSearch, dbConnection);
MySqlDataReader reader = mySqlCommand.ExecuteReader();
try
{
while (reader.Read())//循环表中的所有键
{
if (reader.HasRows)
{
List<string> data = new List<string>();
for (int i = 0; i < reader.FieldCount; i++)
{
data.Add(reader.GetString(i));
}
if (data.Count > 0)
txet.Add(data[0], data);
}
}
}
catch (Exception e)
{
Console.WriteLine("SQL:查询失败了!" + e.Message);
}
finally
{
reader.Close();
}
return txet;
}
那么如果是读取表中所有数据的话SQL语句直接把where去掉就可以
8.更新(同时更新多条数据且要修改的值相同)
AND 同时满足多个条件
///
/// 更新数据表
///
/// 表
/// 要修改的字段
/// 字段修改后的值
/// 通过指定字段找一条数据
/// 指定字段的值
///
public DataSet UpdateIntos(string tableName, string[] cols, string[] colsvalues, List<string> selectkey, List<string> selectvalue)
{
//例:表中有 ID Name 两个字段 ID为主键 当前修改name的值
// cols=Name colsvalues 要修改的名称 selectkey=ID selectvalue= 1
string query = "UPDATE " + tableName + " SET " + cols[0] + " = '" + colsvalues[0] + "'";
for (int i = 1; i < colsvalues.Length; ++i)
{
query += ", " + cols[i] + " = '" + colsvalues[i] + "'";
}
query += " WHERE " + selectkey[0] + " = '" + selectvalue[0] + "'";
for (int i = 1; i < selectvalue.Count; i++)
{
query += " AND " + selectkey[i] + " = '" + selectvalue[i] + "'";
}
UnityEngine.Debug.Log(query);
return ExecuteQuery(query);
}
把AND 改为 OR 就可以赛选满足一项的数据
同时更新(替换 如果不希望替换则使用insert into)多条数据 中的一个字段 值可不同
public DataSet UpdateIntos1(string tableName, string cols, List<string> colsvalues, string selectkey, List<string> selectvalue)
{
string query = "replace into " + tableName + " (" + selectkey + "," + cols + ")";
query += " VALUES (" + selectvalue[0] + ",'" + colsvalues[0] + "')";
for (int i = 1; i < colsvalues.Count; ++i)
{
query += ",(" + selectvalue[i] + ",'" + colsvalues[i] + "')";
}
return ExecuteQuery(query);
}
同时更新(替换)多条数据 中的多个个字段 值可不同
public DataSet UpdateIntos2(string tableName, List<string> cols, List<string[]> colsvalues, string selectkey, List<string> selectvalue)
{
string query = "replace into " + tableName + " (" + selectkey + "," + cols[0];
for (int i = 1; i < cols.Count; i++)
{
query += "," + cols[i];
}
query += ")";
query += " VALUES ";
for (int i = 0; i < colsvalues.Count; i++)
{
if (i==0)
query += "(" + selectvalue[i];
else
query += ",(" + selectvalue[i];
string[] values = colsvalues[i];
for (int j = 0; j < values.Length; j++)
{
query += ",'" + values[j] + "'";
}
query += ")";
}
return ExecuteQuery(query);
}
最后贴出执行sql语句的方法
public DataSet ExecuteQuery(string sqlString)
{
if (dbConnection==null)
return null;
if (dbConnection.State == ConnectionState.Open)
{
DataSet ds = new DataSet();
try
{
MySqlDataAdapter da = new MySqlDataAdapter(sqlString, dbConnection);
da.Fill(ds);
}
catch (Exception ee)
{
//Console.WriteLine("zheli"+ee.Message);
UnityEngine.Debug.Log("SQL:" + sqlString + "\n" + ee.Message.ToString());
ds = null;
}
finally
{
}
return ds;
}
return null;
}
只是贴出了主要语句,很多地方没有详细的去解释,是因为不希望大家只是复制,一定要思考。
这些方法基本上已经满足Mysql的普通使用者,并且很多方法支持高并发,每秒几千条数据是没有问题的。
另外本人也是业余Mysql,如果那里有错误的语法 望指出。谢谢!