C#判断表是否存在MySQL、PostgreSQL、SqlSer
2020-07-01 本文已影响0人
triplestudio
MySQL
public static bool IsTableExists(string connectionString, string tblName)
{
string sql = "SELECT table_name FROM information_schema.TABLES WHERE table_name =@tableName";
string result = MySQLHelper.ExecuteScalar(connectionString,
System.Data.CommandType.Text, sql,
new MySqlParameter("tableName", tblName)) as string;
return String.IsNullOrEmpty(result) ? false : true;
}
PostgreSQL
public static bool IsTableExists(string connectionString, string tblName)
{
string sql = "select to_regclass(@tableName)";
string result = PostgreSQLHelper.ExecuteScalar(connectionString,
System.Data.CommandType.Text, sql,
new NpgsqlParameter("tableName", tblName)) as string;
return String.IsNullOrEmpty(result) ? false : true;
}
SqlServer
public static bool IsTableExists(string connectionString, string tblName)
{
string sql = "if object_id(@tableName) is not null select 'ok' else select ''";
string result = SqlHelper.ExecuteScalar(connectionString,
System.Data.CommandType.Text, sql,
new SqlParameter("tableName", tblName)) as string;
return String.IsNullOrEmpty(result) ? false : true;
}