str*_*ing 1 c# mysql database postgresql postgresql-9.1
我正在尝试以 C# 编程方式创建一个 postGres 数据库,之前我已经手动创建了数据库,并使用连接字符串来打开它并对其进行操作,并且它运行良好。
现在我必须首先检查该 DBB 是否已经存在,如果不存在,则首先创建它,然后执行其他操作,例如读取写入它。
我这样做的代码是:
internal void createDataBaseIfDoNotExist()
{
string connStr = string.Empty;
connStr =
"Server=" + "localhost"
+ ";Port=" + "5432"
+ ";User Id=" + "openpg"
+ ";Password=" + "oppwd"
+ ";";
var m_conn = new NpgsqlConnection(connStr);
var m_createdb_cmd = new NpgsqlCommand(@"CREATE DATABASE IF NOT EXISTS testDb ;", m_conn);
try
{
m_conn.Open();
m_createdb_cmd.ExecuteNonQuery();
m_conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Errr on createDataBaseIfDoNotExist query :" + ex);
}
}
And it gives followign error:
database "openpg" does not exist Severity: FATAL Code: 3D000
Run Code Online (Sandbox Code Playgroud)
虽然我保留的数据库名称是“testDb”,但它不是“openpg”
之前我创建了一个数据库名称“NewDB”并创建了如下连接字符串:
connStr =
"Database=" + "NewDB"
+ ";Server=" + "localhost"
+ ";Port=" + "5432"
+ ";User Id=" + "openpg"
+ ";Password=" + "oppwd"
+ ";";
Run Code Online (Sandbox Code Playgroud)
它工作得很好,那么为什么现在出现错误以及如何解决它?
您需要添加Database=postgres连接字符串
connStr = "Server=localhost;Port=5432;User Id=postgres;Password=password_of_the_user;Database=postgres";
Run Code Online (Sandbox Code Playgroud)
因为postgres是PostgreSQL的默认管理连接数据库