我正在尝试使用 ECPG - C 中的嵌入式 SQL - 使用游标从表中获取一行。
例如:
struct{
char *col1;
char *col2;
....
}test_struct;
EXEC SQL DECLARE mycursor CURSOR FOR select * from test
EXEC SQL SET TRANSCATION read only
EXEC SQL OPEN mycursor
EXEC SQL FETCH FROM mycursor INTO :test_struct
但似乎我必须定义一个与表test对应的struct test_struct,这意味着我已经知道表中有多少列以及它们的类型和名称。如何从我不知道其架构的任何表中获取一行?
例如:
select * from arbitrary_table_in_my_db
///////////////////////////////////////// ////////////////////////
/// 修改:SQLDA 工作正常,这里是来自http://www.postgresql.org/message-id/4C206CD8.7050801@gmail.com的示例代码
//做了一些修改
#include <pgtypes_date.h>
#include <pgtypes_numeric.h>
EXEC SQL include sqlda.h;
sqlda_t *sqlda1;
int
main(void)
{
EXEC SQL CONNECT TO ....
EXEC SQL DECLARE cur CURSOR FOR SELECT * FROM test;
EXEC SQL OPEN cur;
EXEC SQL WHENEVER NOT FOUND DO BREAK;
while (1) {
/* Open a cursor and assign descriptor to the cursor */
EXEC SQL FETCH NEXT FROM cur INTO DESCRIPTOR sqlda1;
while (1) {
int i;
char name_buf[1024];
char var_buf[1024];
for (i=0 ; i<sqlda1->sqld ; i++) {
sqlvar_t v = sqlda1->sqlvar[i];
char *sqldata = v.sqldata;
short sqllen = v.sqllen;
strncpy(name_buf, v.sqlname.data, v.sqlname.length);
name_buf[v.sqlname.length] = '\0';
strncpy(var_buf, sqldata, sqllen);
var_buf[sqllen] = '\0';
if(v.sqltype == 16)
printf("%s = %s, (type:%d)\n", name_buf, PGTYPESnumeric_to_asc((numeric*)sqldata,0), v.sqltype);
else if(v.sqltype == 18){
printf("%s = %s, (type:%d)\n", name_buf, PGTYPESdate_to_asc(*v.sqldata), v.sqltype);
}
else
printf("%s = %s, (type:%d)\n", name_buf, var_buf, v.sqltype);
}
printf("\n");
if ( sqlda1->desc_next==NULL )
break;
}
}
EXEC SQL CLOSE cur;
EXEC SQL COMMIT;
EXEC SQL DISCONNECT ALL;
return (0);
}