以编程方式创建一个postgreSQL数据库 [英] Create a postgreSQL database programmatically

查看:87
本文介绍了以编程方式创建一个postgreSQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Visual Studio 2012中构建一个应用程序,我希望每次运行该应用程序时检查某个Postgres数据库是否存在,如果不存在,则使用指定的表等创建数据库。

I am building an application in Visual Studio 2012, which I would like every time it is run to check if a certain postgres database exists and if not then create one, with specified tables etc.

我在Google周围四处没有运气。我希望以编程方式从应用程序内部创建数据库,但是如果有人知道是否以及如何使用安装程序向导来做到这一点,那也很好。该应用程序只能在Windows上运行,而不能在所有计算机上运行。

I've looked around in Google without luck. I want the database to be created from within my application programmatically but if someone knows if and how I can do this using an installer wizard that would be good too. The application is meant to be running on windows only but on all machines without exceptions.

推荐答案

无论使用何种工具和编程语言您将要使用的方法是相同的:

Irrespective of the tools and programming languages used the approach you'll want to use for this is the same:


  1. 在程序中,在启动期间连接到 template1 postgres 数据库,这些数据库在PostgreSQL安装中始终可用,并从pg_database发出 SELECT 1 WHERE datname =?,并作为第一个参数传递所需的数据库名称。

  1. In your program, during startup connect to the template1 or postgres databases that're always available in a PostgreSQL install and issue a SELECT 1 FROM pg_database WHERE datname = ? and as the first parameter pass the desired database name.

检查返回的结果集。如果返回一行,则表明数据库已存在,您就完成了,无需采取进一步的措施。如果未返回任何行,则该数据库不存在,您需要创建该数据库,因此:

Check the result set that is returned. If a row is returned then database exists, you're done, no further action required. If no row is returned then the database doesn't exist and you need to create it, so:

发出 CREATE DATABASE mydatabasename ; ,并根据手册创建所需的任何选项,例如 OWNER ENCODING 等数据库自身。新数据库将为空。

Issue a CREATE DATABASE mydatabasename; with any desired options like OWNER, ENCODING, etc per the manual to create the database its self. The new database will be empty.

通过连接到应用程序中的新数据库并直接从应用程序发送一系列SQL命令来填充数据库,或者在外壳上调用 psql 命令以读取 sql 脚本文件并将其发送到数据库。通常,我通常希望直接在应用程序中运行SQL。

Populate the database either by connecting to the new database in your application and sending a sequence of SQL commands from your application directly, or by invoking the psql command on the shell to read a sql script file and send that to the database. I'd generally prefer to run the SQL directly within my application.

如果您想在此期间创建数据库安装主要取决于您和您的安装程序,但是通常会像在PostgreSQL启动后通过 CREATE DATABASE 调用一样简单,然后提供 psql 一个规则。

If you instead want to create the DB during install that's mostly up to you and your installer, but it'll usually be as simple as a CREATE DATABASE call after PostgreSQL has started, then feeding psql a srcipt.

这篇关于以编程方式创建一个postgreSQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆