一、判断某数据库是否存在
(一)单纯判断数据库dbname是否存在
SQL语句为:
SELECT * FROM information_schema.SCHEMATA where SCHEMA_NAME=’dbname’;
c#实现代码如下:
String sqlConn = "server=10.0.0.3;port=3306;user=root;password=mypassword;";
MySqlConnection conn = new MySqlConnection(sqlConn);//
string sqlDB = "SELECT * FROM information_schema.SCHEMATA where SCHEMA_NAME='dbname';";
MySqlDataAdapter adp = new MySqlDataAdapter(sqlDB, conn);
DataSet ds = new DataSet();
adp.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
MessageBox.Show("数据库已存在");
else
MessageBox.Show("数据库不存在!");
(二)如果判断数据库dbname存在,则删除
SQL语句如下:
DROP DATABASE IF EXISTS `test1`;
MySqlCommand cmd=new MySqlCommand(string.Format("DROP DATABASE IF EXISTS 'test';"));
cmd.ExecuteNonQuery();
(三)如果判断数据库dbname不存在,则创建数据库
SQL语句如下:
CREATE DATABASE IF NOT EXISTS `test1` ;
c#执行代码如下:
MySqlCommand cmd=new MySqlCommand(string.Format("CREATE DATABASE IF NOT EXISTS 'test';"));
cmd.ExecuteNonQuery();
二、判断数据库中某数据表是否存在
(一)单纯判断dbname数据库中是否存在tbname表格
SQL语句为:
SELECT * FROM information_schema.TABLES where table_name=’tbname’ and TABLE_SCHEMA=’dbname’;
c#实现代码如下:
String sqlConn = "server=10.0.0.3;port=3306;user=root;password=mypassword;";
MySqlConnection conn = new MySqlConnection(sqlConn);//
string sqlTB = "SELECT * FROM information_schema.TABLES where table_name='tbname' and TABLE_SCHEMA ='dbname';";
MySqlDataAdapter adp = new MySqlDataAdapter(sqlTB, conn);
DataSet ds = new DataSet();
adp.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
MessageBox.Show("数据库表已存在");
else
MessageBox.Show("数据库表不存在!");
(二)如果判断dbname数据库中不存在tbname数据表,则创建
SQL语句为:
CREATE TABLE IF NO NOT EXISTS `tbname` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`unit` varchar(45) DEFAULT NULL,
`name` varchar(45) DEFAULT NULL,
`phone` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=56370 DEFAULT CHARSET=utf8;
C#实现代码如下:
MySqlCommand cmd;
cmd=new MySqlCommand(string.Format("CREATE DATABASE IF NOT EXISTS dbname;"),conn);
cmd.ExecuteNonQuery();
string sqlcreatetable = string.Format("CREATE TABLE IF NOT EXISTS dbname.tbname(id int(11) NOT NULL AUTO_INCREMENT,unit varchar(45) DEFAULT NULL,name varchar(45) DEFAULT NULL,phone varchar(45) DEFAULT NULL,PRIMARY KEY (id)) ENGINE=InnoDB AUTO_INCREMENT=56370 DEFAULT CHARSET=utf8;");
cmd = new MySqlCommand(sqlcreatetable, conn);
cmd.ExecuteNonQuery();
(三)如果判断dbname数据库中存在tbname数据表,则删除
SQL语句为:
Drop table if exists dbname.tbname;
c#实现代码如下:
MySqlCommand cmd;
cmd=new MySqlCommand(string.Format("Drop table if exists dbname.tbname;"),conn);
cmd.ExecuteNonQuery();