windows 10下使用c语言通过odbc链接mysql
windows 10下使用c语言通过odbc链接mysql数据库 安装mysqlconnector/odbc 配置数据源名称dsn 查看c语言的 odbc api 编写代码 链接 运行
安装mysqlconnector/odbc
配置数据源名称dsn
控制面板->管理工具->odbc 数据源(32 位)
在指定的dsn中,驱动程序和应用程序之间的体系结构不匹配
然后按官网上的步骤配置即可
configuring a connector/odbc dsn on windows with the odbc data source administrator gui
添加->mysql odbc driver->填写相应的信息
查看c语言的 odbc api
通过以下头文件访问odbc api
odbc api reference
#include
#include
#include
#include
#include
#include
编写代码
c语言odbc操作mysql数据库
#include
#include
#include
#include
#include
#include
#pragma coment(lib, "c:\\windows\\system32\\odbc32.dll")
#define false 0
#define true 1
#define con_str_len 255
#define sql_query_buff_size 512
int initconnect(void);
int main()
{
// sqlhenv henv = 0;
// sqlallochandle(sql_handle_env, sql_null_handle, & henv);
printf("hello world!\n");
initconnect();
return 0;
}
int initconnect(void)
{
sqlhenv henv = 0;
sqlhdbc hdbc = 0;
sqlhstmt hstmt = 0;
sqlreturn retcode;
sqlchar szconstr[con_str_len];
sqlchar szstmt[sql_query_buff_size];
int16 cbconlen;
// 分配环境句柄
retcode = sqlallochandle(sql_handle_env, sql_null_handle, &henv);
if (retcode != sql_success)
{
printf("00sqlallochandle error!");
return -1;
}
// 设置环境句柄
retcode = sqlsetenvattr(henv, sql_attr_odbc_version, (void *)sql_ov_odbc3, 0);
if (retcode != sql_success)
{
printf("11sqlsetenvattr error!");
return -2;
}
// 分配连接句柄
retcode = sqlallochandle(sql_handle_dbc, henv, &hdbc);
printf("%hd",retcode);
if (retcode != sql_success && retcode != sql_success_with_info )
{
printf("22sqlallochandle error!");
return -3;
}
retcode = sqlconnect(hdbc, (sqlchar *)"mysql32", sql_nts, (sqlchar *)"root",
sql_nts, (sqlchar *)".787929814ligang", sql_nts);
printf("%hd",retcode);
if (retcode != sql_success && retcode != sql_success_with_info)
{
printf("sqlconnect error!");
return -4;
}
}
链接
在命令行cmd下
使用如下gcc 命令链接
任选一个,并不知道那个是有效的
gcc xxx.c -w "c:\windows\system32\odbc32.dll" -o xxx.exe
gcc xxx.c -w "c:\windows\syswow64\odbc32.dll" -o xxx.exe
注:gcc命令一般是在安装的集成开发环境的mingw目录的bin目录下
或者自己安装一个mingw,然后将c:\mingw\bin目录加入环境变量
运行
在命令行输入xxx.exe
没有错误信息即成功链接