copy入库
最近更新时间: 2024-10-17 17:10:00
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "libpq-fe.h"
int
main(int argc, char **argv){
const char *conninfo;
PGconn *conn;
PGresult *res;
const char *buffer = "1,tbase\n2,pgxz\n3,Tbase牛";
if (argc > 1){
conninfo = argv[1];
}else{
conninfo = "dbname = postgres";
}
conn = PQconnectdb(conninfo);
if (PQstatus(conn) != CONNECTION_OK){
fprintf(stderr, "连接数据库失败: %s",PQerrorMessage(conn));
}else{
printf("连接数据库成功!\n");
}
res=PQexec(conn,"COPY tbase FROM STDIN DELIMITER ',';");
if(PQresultStatus(res) != PGRES_COPY_IN){
fprintf(stderr, "copy数据出错1: %s",PQresultErrorMessage(res));
}else{
int len = strlen(buffer);
if(PQputCopyData(conn,buffer,len) == 1){
if(PQputCopyEnd(conn,NULL) == 1){
res = PQgetResult(conn);
if(PQresultStatus(res) == PGRES_COMMAND_OK){
printf("copy数据成功!\n");
}else{
fprintf(stderr, "copy数据出错2: %s",PQerrorMessage(conn));
}
}else{
fprintf(stderr, "copy数据出错3: %s",PQerrorMessage(conn));
}
}else{
fprintf(stderr, "copy数据出错4: %s",PQerrorMessage(conn));
}
}
PQclear(res);
PQfinish(conn);
return 0;
}
编译
gcc -c -I /usr/local/install/tbase_pgxz/include/ copy.c
gcc -o copy copy.o -L /usr/local/install/tbase_pgxz/lib/ -lpq
运行
./copy "dbname=postgres port=15432"
#连接数据库成功!
copy数据成功!