linux下在C中嵌入SQL连接免费数据库PostgreSQL的有关问题

linux下在C中嵌入SQL连接免费数据库PostgreSQL的有关问题

linux下在C中嵌入SQL连接免费数据库PostgreSQL的问题
我想在linux下用在C语言中应用嵌入SQL的方法连接PostgreSQL数据库,看了一些书最后通过PQconnectdb的方式连上了但是没弄明白怎么用嵌入SQL语法的方式来连接和操作数据库

谁能给我一个具体的能成功编译运行的例子啊?最好是有详细注释的


先编写.pgc文件如下:
#include <stdlib.h>

exec sql include sqlca;

main ()
{
exec sql connect to tcp:postgresql://127.0.0.1:5432/andy as conn user postgres;

exec sql BEGIN WORK;
exec sql UPDATE children SET fname = 'Gavin ' WHERE childno = 10;
exec sql COMMIT WORK;
exec sql disconnect all;
return EXIT_SUCCESS;
}

然后用ecpg预处理为.c程序,再编译,就ok了


/*建数据库过程略*/
/*结构*/
/*数据库名:wangxsDB
表名:t
a b c d e
1 1 a 1 1
2 2 b 2 2
3 3 c 3 3
4 4 d 4 4
5 5 e 5 5
6 6 f 6 6
*/
/*代码*/
#include <stdio.h>
#include <stdlib.h>
EXEC SQL include sqlca;
main()
{
EXEC SQL BEGIN DECLARE SECTION;
char result[3];
char database[20];
char username[20];
char password[20];
EXEC SQL END DECLARE SECTION;

strcpy(database, "wangxsDB ");
strcpy(username, "wangxs ");
EXEC SQL CONNECT TO :database USER :username;
EXEC SQL SELECT a INTO :result FROM t WHERE a=1;

printf( "result = %sn ", result );
EXEC SQL DISCONNECT;

}

/*编译*/

/*?.dbc

ecpg ?.dbc -> ?.c*/

ecpg esqltest.dbc

[wangxs@localhost ~]$ cc ?.c -I /usr/local/postgre/include/ -L /usr/local/p
ostgre/lib/ -lecpg -lpq -o ?

/*或者*/

ecpg esqltest.dbc

[root@localhost wangxs]# cc ?.c -I /var/lib/pgsql/include -L /var/lib/pgsql
/lib -lecpg -lpq -o ?

/*makefile的编写*/

INCLUDE=/usr/local/postgre/include/
LIB=/usr/local/postgre/lib/
FILEDBC=esqltest.dbc
FILEC=esqltest.c
FILE=esqltest
ESQL=ecpg
CC=cc

.exe:$(FILEC)
$(CC) -I $(INCLUDE) -L $(LIB) -lecpg -lpq -o $(FILE)
.c:$(FILEDBC)
$(ESQL) $(FILEDBC)


//File:mypgsql.h
#include <iostream>
#include <stdio.h>
#include <libpq-fe.h>
#include <stdlib.h>
#include <unistd.h>
#include <vector>
#include <string>

using namespace std;
//static pthread_mutex_t hci_mutex=PTHREAD_MUTEX_INITIALIZER;

class mypgsql{
private:
PGconn *conn;
PGresult *res;
int row;
int col;
public:
vector <string> vcol_head; //表头名
vector <string> vdata; //表数据,按行优先
mypgsql(string hostaddr= "127.0.0.1 ",string dbmane=NULL,string user= "usr "):vcol_head(),vdata()
{
string coninfo;
coninfo= "hostaddr= "+hostaddr+ " "+ "dbname= "+dbmane+ " user= "+user;
// sprintf(coninfo, "hostaddr=%s dbname=%s ", hostaddr, dbmane);
conn = PQconnectdb(coninfo.c_str());

if (PQstatus(conn) != CONNECTION_OK)
{
fprintf(stderr, "Connection to database failed: %s n ", PQerrorMessage(conn));
PQfinish(conn);
exit(1);
}
// pthread_mutex_lock(&hci_mutex);
row = col = 0;
}

int exe(string s_exe)
{
res = PQexec(conn, s_exe.c_str());
if (PQresultStatus(res) == PGRES_TUPLES_OK) //成功执行一个返回数据的查询查询(

linux下在C中嵌入SQL连接免费数据库PostgreSQL的有关问题

相关文章:

你感兴趣的文章:

标签云: