今天想实现一个功能,程序能自动创建数据库,采用C#实现。
涉及到的相关SQL语句如下:
判断数据库是否存在:
select Count(*) as A from information_schema.schemata where schema_name='test1'
创建数据库
CREATE DATABASE test1
部分代码如下:
DBMysql dBMysql = new DBMysql();
dBMysql.ConnectMySql("127.0.0.1", 3306, "root", "sa");
string strSql = string.Format(@"select Count(*) as A from information_schema.schemata where schema_name='test1'");
System.Data.DataSet dataSet = new DataSet();
var bRet = dBMysql.SqlExe(strSql,ref dataSet);
if(false == bRet)
{
return;
}
if(1 != dataSet.Tables[0].Rows.Count)
{
return;
}
DataRow row = dataSet.Tables[0].Rows[0];
var a = row["A"];
if("0" == a.ToString())
{
string strCreat = string.Format(@"CREATE DATABASE test1");
Console.WriteLine(dBMysql.SqlExe(strCreat) +" "+strCreat);
}
效果检查:
成功创建了数据库