有没有一种方法来检查表是否存在,而不选择和检查它的值?
也就是说,我知道我可以去SELECT testcol FROM testtable并检查返回字段的计数,但似乎必须有一个更直接/优雅的方式来做到这一点。
有没有一种方法来检查表是否存在,而不选择和检查它的值?
也就是说,我知道我可以去SELECT testcol FROM testtable并检查返回字段的计数,但似乎必须有一个更直接/优雅的方式来做到这一点。
当前回答
你可以这样做:
string strCheck = "SHOW TABLES LIKE \'tableName\'";
cmd = new MySqlCommand(strCheck, connection);
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
cmd.Prepare();
var reader = cmd.ExecuteReader();
if (reader.HasRows)
{
Console.WriteLine("Table Exist!");
}
else
{
Console.WriteLine("Table does not Exist!");
}
其他回答
除了SELECT选项,其他选项都不允许使用SELECT中的数据库名称,所以我这样写:
SELECT COUNT(*) AS cnt FROM information_schema.TABLES
WHERE CONCAT(table_schema,".",table_name)="db_name.table_name";
下面是一个不是SELECT * FROM的表
SHOW TABLES FROM `db` LIKE 'tablename'; //zero rows = not exist
这是从一个数据库专家那里得到的,这是我被告知的:
select 1 from `tablename`; //avoids a function call
select * from INFORMATION_SCHEMA.tables where schema = 'db' and table = 'table' // slow. Field names not accurate
SHOW TABLES FROM `db` LIKE 'tablename'; //zero rows = does not exist
你可以这样做:
string strCheck = "SHOW TABLES LIKE \'tableName\'";
cmd = new MySqlCommand(strCheck, connection);
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
cmd.Prepare();
var reader = cmd.ExecuteReader();
if (reader.HasRows)
{
Console.WriteLine("Table Exist!");
}
else
{
Console.WriteLine("Table does not Exist!");
}
您可以查询INFORMATION_SCHEMA表的系统视图:
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'databasename'
AND table_name = 'testtable';
如果没有返回行,则表不存在。
SELECT count(*)
FROM information_schema.TABLES
WHERE (TABLE_SCHEMA = 'your_db_name') AND (TABLE_NAME = 'name_of_table')
如果得到非零计数,则表存在。