在进行ODBC实验时,遇到的问题记录
编译器:DevC++
语言:C语言
样例代码:
int main(){
SQLHENV env = SQL_NULL_HENV;
SQLHDBC conn = SQL_NULL_HDBC;
SQLHSTMT stmt = SQL_NULL_HSTMT;
SQLRETURN ret;
char city[255] = {0};
int pci = 0;
int lenOut1 = 0,lenOut2 = 0;
char *sqlquery = "select CITY,PCI from tbCell";
ret = SQLAllocHandle(SQL_HANDLE_ENV,SQL_NULL_HANDLE,&env);
printf("%d\n",ret);
ret = SQLSetEnvAttr(env,SQL_ATTR_ODBC_VERSION,(void*)SQL_OV_ODBC3,0);
printf("%d\n",ret);
ret = SQLAllocHandle(SQL_HANDLE_DBC,env,&conn);
printf("%d\n",ret);
ret = SQLConnect(conn,"ourdatabase",SQL_NTS,"sa",SQL_NTS,"boogie",SQL_NTS);
printf("%d\n",ret);
ret = SQLAllocHandle(SQL_HANDLE_STMT,conn,&stmt);
printf("%d\n",ret);
ret = SQLExecDirect(stmt,sqlquery,SQL_NTS);
printf("%d\n",ret);
if(ret == SQL_SUCCESS){
SQLBindCol(stmt,1,SQL_C_CHAR,city,255,&lenOut1);
SQLBindCol(stmt,2,SQL_C_SBIGINT,&pci,0,&lenOut2);
while(SQLFetch(stmt) == SQL_SUCCESS){
printf("%s %d\n",city,pci);
}
}
SQLFreeHandle(SQL_HANDLE_STMT,stmt);
SQLDisconnect(conn);
SQLFreeHandle(SQL_HANDLE_DBC,conn);
SQLFreeHandle(SQL_HANDLE_ENV,env);
getchar();
return 0;
}
1.出现的报错如下:
undefined reference to `SQLSetEnvAttr'
undefined reference to `SQLAllocHandle'
undefined reference to `SQLConnect'
undefined reference to `SQLAllocHandle'
``````
解决方法:
在Dev的菜单栏中选择【工具/tool】->【编译器选项/compiler options】就可以看见如下窗口
-lodbc32
2.第二个报错
[Warning] passing argument 6 of 'SQLBindCol' from incompatible pointer type
[Note] expected 'SQLLEN *' but argument is of type 'int *'
其实就是数据类型的不匹配,查看原函数的参数类型,照着改一改就可以了,别忘了还有函数调用的地方也要改一下吼
3。经过再三测试,总是运行到while (SQLFetch(stmt)== SQL_SUCCESS){“`}那一句时会出现程序停止运行
查了很久,也不知道为什么,然后和舍友对了代码之后,尝试把SQLBindCol(stmt,1,SQL_C_CHAR,city,255,&lenOut1);中【&lenOut】改成了【0】,就没有出现程序运行停止了,我也不知道为什么,估计这个域还蛮重要的,有时间弄清楚了再来补充吧
4。解决完上面的错误之后发现运行的结果总是无法获取【city】的值,只能得到【pci】的值,经过多番检查和尝试,我把select的语句换成了
char *sqlquery = "select PCI,CITY from tbCell where SECTOR_ID = '124672-1'";
绑定的代码换成了:
SQLBindCol(stmt,1,SQL_C_SBIGINT,&pci,0,0);
SQLBindCol(stmt,2,SQL_C_CHAR,city,50,0);
这里其实就是换了个顺序,但是结果就出来了,我也不知道为什么·····