用于创建、列出和删除数据库的 libpq 代码(C++/VC++、PostgreSQL) [英] libpq code to create, list and delete databases (C++/VC++, PostgreSQL)

查看:51
本文介绍了用于创建、列出和删除数据库的 libpq 代码(C++/VC++、PostgreSQL)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 PostgreSQL 数据库的新手.我的 Visual C++ 应用程序需要做的是创建多个表并从中添加/检索数据.

I am new to the PostgreSQL database. What my visual c++ application needs to do is to create multiple tables and add/retrieve data from them.

我的应用程序的每个会话都应该创建一个新的独特的数据库.我可以使用当前日期和时间作为唯一的数据库名称.

Each session of my application should create a new and distinct database. I can use the current date and time for a unique database name.

还应该有删除所有数据库的选项.

There should also be an option to delete all the databases.

我已经研究了如何连接到数据库、创建表以及向表中添加数据.如果用户想清除所有数据库,我不确定如何为每次运行创建一个新数据库,或者如何检索数据库的数量和名称.

I have worked out how to connect to a database, create tables, and add data to tables. I am not sure how to make a new database for each run or how to retrieve number and name of databases if user want to clear all databases.

请帮忙.

推荐答案

参见 文档中的 libpq 示例.示例程序向您展示了如何列出数据库,以及如何对数据库执行命令.那里的示例代码很容易适应创建和删除数据库.

See the libpq examples in the documentation. The example program shows you how to list databases, and in general how to execute commands against the database. The example code there is trivial to adapt to creating and dropping databases.

创建数据库很简单CREATE DATABASE SQL 语句,与任何其他 libpq 操作相同.您必须连接到临时数据库(通常是 template1)以发出 CREATE DATABASE,然后断开连接并与您刚刚创建的数据库建立新连接.

Creating a database is a simple CREATE DATABASE SQL statement, same as any other libpq operation. You must connect to a temporary database (usually template1) to issue the CREATE DATABASE, then disconnect and make a new connection to the database you just created.

与其创建新的数据库,不如考虑创建新的模式反而.少很多麻烦,因为您需要做的就是更改 search_path 或为您的表引用添加前缀,您无需断开连接并重新连接即可更改架构.请参阅有关架构的文档.

Rather than creating new databases, consider creating new schema instead. Much less hassle, since all you need to do is change the search_path or prefix your table references, you don't have to disconnect and reconnect to change schemas. See the documentation on schemas.

不过,我怀疑您的设计是否明智.对于应用程序来说,创建和删除数据库(或表,临时表除外)作为其操作的正常部分很少是一个好主意.也许如果您详细说明了为什么要这样做,我们可以提出比您当前的方法更容易和/或性能更好的解决方案.

I question the wisdom of your design, though. It is rarely a good idea for applications to be creating and dropping databases (or tables, except temporary tables) as a normal part of their operation. Maybe if you elaborated on why you want to do this, we can come up with solutions that may be easier and/or perform better than your current approach.

这篇关于用于创建、列出和删除数据库的 libpq 代码(C++/VC++、PostgreSQL)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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