- Ivy Seo
PostgreSQL check if exists() in C#
A function that checks if the table already exists in the database:
private static bool CheckIfTableExists()
{ // check if the table already exists in database -> return true
bool tableExist = false;
// connect to postgresql
var cs = "Host=epic-works-pg.postgres.database.azure.com; Username=username@epic-works-pg; Password=YourPassword; Database=epic-works-test";
using var con = new NpgsqlConnection(cs);
con.Open();
// SELECT if table EXISTS
string sql = "SELECT EXISTS (SELECT 1 FROM pg_tables WHERE tablename = 'm7_data_table')";
using var cmd = new NpgsqlCommand(sql, con);
using NpgsqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine("table exist bool: {0}", rdr.GetBoolean(0));
tableExist = rdr.GetBoolean(0);
}
return tableExist;
}