windows vs2022 c/c++连接操作postgresql数据库 - 增删改查

7 篇文章 0 订阅
6 篇文章 0 订阅

关于环境的配置请参考上一篇文章,本文仅包含示例代码

namespace idealand
{
	typedef int (*PGResultHandler)(PGresult*);

  class DB
  {
  public:
		const char* conn_string = "user=** password=** host=** port=** dbname=** connect_timeout=5";
		const char* set_secure = "SELECT pg_catalog.set_config('search_path', 'public', false)";
		PGconn* conn=0;
		PGresult* res=0;


		void close()
		{
			if(conn) PQfinish(conn); 
		}

		void ouput()
		{
			int nFields, i, j;

			// first, print out the attribute names 
			nFields = PQnfields(res);	for (i = 0; i < nFields; i++) 	printf("%-15s", PQfname(res, i));
			printf("\n");

			// next, print out the rows
                                                      int rows=PQntuples(res);
			for (i = 0; i < rows; i++)
			{
				for (j = 0; j < nFields; j++) printf("%-15s", PQgetvalue(res, i, j));
				printf("\n");
			}
		}

		int exe_select(const char* sql, PGResultHandler handler)
		{
			int r = 0;
			char* cmd = string("DECLARE myportal CURSOR FOR %s", sql);

			conn = PQconnectdb(conn_string); if (PQstatus(conn) != CONNECTION_OK) goto fail;
			/* Set always-secure search path, so malicious users can't take control. */
			res = PQexec(conn, set_secure); if (PQresultStatus(res) != PGRES_TUPLES_OK) { goto fail; } PQclear(res);
			/* Start a transaction block */
			res = PQexec(conn, "BEGIN"); if (PQresultStatus(res) != PGRES_COMMAND_OK) { goto fail; } PQclear(res); 

			res = PQexec(conn, cmd); if (PQresultStatus(res) != PGRES_COMMAND_OK) { goto fail; } PQclear(res);


			res = PQexec(conn, "FETCH ALL in myportal"); if (PQresultStatus(res) != PGRES_TUPLES_OK) { goto fail; }

			if (handler)
			{
				handler(res);
			}
			else
			{
				ouput();
			}

			PQclear(res);

			res = PQexec(conn, "END"); PQclear(res); goto ok;
		  
		fail: IdealandF(cmd); log_show("Postgres failed: %s", PQerrorMessage(conn)); if (res) PQclear(res); close(); return -2;
		ok:	IdealandF(cmd); close(); return 0;
		}

		int exe_insert(const char* sql, PGResultHandler handler)
		{
			int r = 0;
			char* cmd = string("%s RETURNING id;", sql);
			
			conn = PQconnectdb(conn_string); if (PQstatus(conn) != CONNECTION_OK) goto fail;
			/* Set always-secure search path, so malicious users can't take control. */
			res = PQexec(conn, set_secure); if (PQresultStatus(res) != PGRES_TUPLES_OK) { goto fail; } PQclear(res);
			/* Start a transaction block */
			res = PQexec(conn, "BEGIN"); if (PQresultStatus(res) != PGRES_COMMAND_OK) { goto fail; } PQclear(res);

			res = PQexec(conn, cmd); if (PQresultStatus(res) != PGRES_TUPLES_OK) { goto fail; }
			if (handler)
			{
				handler(res);
			}
			else
			{
				r = atoi(PQgetvalue(res, 0, 0));
			}

			PQclear(res);

			res = PQexec(conn, "END"); PQclear(res); goto ok;

		fail:IdealandF(cmd); log_show("Postgres failed: %s", PQerrorMessage(conn)); if (res) PQclear(res); close(); return -2;
		ok:IdealandF(cmd); close(); return r;
		}

		int exe_update_delete(const char* sql, PGResultHandler handler)
		{
			int r = 0;

			conn = PQconnectdb(conn_string); if (PQstatus(conn) != CONNECTION_OK) goto fail;
			/* Set always-secure search path, so malicious users can't take control. */
			res = PQexec(conn, set_secure); if (PQresultStatus(res) != PGRES_TUPLES_OK) { goto fail; } PQclear(res);
			/* Start a transaction block */
			res = PQexec(conn, "BEGIN"); if (PQresultStatus(res) != PGRES_COMMAND_OK) { goto fail; } PQclear(res);

			res = PQexec(conn, sql); if (PQresultStatus(res) != PGRES_COMMAND_OK) { goto fail; }
			if (handler)
			{
				handler(res);
			}
			else
			{
				ouput();
			}

			PQclear(res);

			res = PQexec(conn, "END"); PQclear(res); goto ok;

		fail:log_show("Postgres failed: %s", PQerrorMessage(conn)); if (res) PQclear(res); close(); return -2;
		ok:close(); return r;
		}


  };

}





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,我可以为您提供一个示例代码,用于封装Python连接PostgreSQL数据库,支持增、删、改、查操作。请先确保您已经安装了`psycopg2`库,它是Python连接PostgreSQL数据库的驱动程序。 首先,我们需要定义一个`PostgreSQL`类,用于连接数据库、执行SQL语句等操作。示例代码如下: ```python import psycopg2 class PostgreSQL: def __init__(self, dbname, user, password, host, port): self.conn = psycopg2.connect(dbname=dbname, user=user, password=password, host=host, port=port) self.cursor = self.conn.cursor() def execute(self, sql): self.cursor.execute(sql) self.conn.commit() return self.cursor.fetchall() def close(self): self.cursor.close() self.conn.close() ``` 在`__init__`方法中,我们使用`psycopg2`库连接数据库,并创建一个游标对象。`execute`方法用于执行SQL语句,并返回结果集。`close`方法用于关闭游标和连接。 接下来,我们可以在`PostgreSQL`类中添加增、删、改、查方法,示例代码如下: ```python class PostgreSQL: def __init__(self, dbname, user, password, host, port): self.conn = psycopg2.connect(dbname=dbname, user=user, password=password, host=host, port=port) self.cursor = self.conn.cursor() def execute(self, sql): self.cursor.execute(sql) self.conn.commit() return self.cursor.fetchall() def close(self): self.cursor.close() self.conn.close() def insert(self, table, columns, values): sql = f"INSERT INTO {table} ({','.join(columns)}) VALUES ({','.join(['%s']*len(values))})" self.cursor.execute(sql, values) self.conn.commit() def delete(self, table, condition): sql = f"DELETE FROM {table} WHERE {condition}" self.cursor.execute(sql) self.conn.commit() def update(self, table, columns, values, condition): sql = f"UPDATE {table} SET {','.join([f'{column}=%s' for column in columns])} WHERE {condition}" self.cursor.execute(sql, values) self.conn.commit() def select(self, table, columns=None, condition=None): sql = f"SELECT {','.join(columns) if columns else '*'} FROM {table}" if condition: sql += f" WHERE {condition}" self.cursor.execute(sql) return self.cursor.fetchall() ``` `insert`方法用于插入数据,需要传入表名、列名和值。`delete`方法用于删除数据,需要传入表名和条件。`update`方法用于修改数据,需要传入表名、列名、值和条件。`select`方法用于查询数据,需要传入表名、列名和条件。 使用示例: ```python pg = PostgreSQL(dbname='test', user='postgres', password='123456', host='localhost', port='5432') # 插入数据 pg.insert('students', ['name', 'age', 'gender'], ['张三', 18, '男']) # 查询数据 result = pg.select('students', ['name', 'age'], "gender='男'") print(result) # [('张三', 18)] # 修改数据 pg.update('students', ['age'], [20], "name='张三'") # 删除数据 pg.delete('students', "name='张三'") pg.close() ``` 这样,我们就封装了一个可以连接PostgreSQL数据库、支持增、删、改、查操作的Python类。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qiuzen

您的资助将帮助我创作更好的作品

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值