资源描述:
《vc使用capi连接操作mysql数据库》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、VC使用CAPI连接操作MySQL数据库一切尽在代码中,代码中也太多了if/else,可以对它进行更好的函数及至类的封装,规范的处理好异常。1.#include2.//需要在VC的Options设置一个include路径指向'%mysql_home%/inlude'目录 3.#include 4.//设置一个lib路径指向'%mysql_home%/lib/opt'目录 (mysql5.0是个目录) 5.#pragma comment(lib,"libmysql.lib"
2、) 6.#define host_name "localhost" //数据库服务器 7.#define db_name "test" //数据库名 8.#define user_name "root" //用户名 9.#define password "" //密码 10.int main(int argc,char * argv[]) { 11. 12. char szSqlText[500] ; 13. 14. MYSQL *conn
3、; 15. MYSQL_RES *rs; 16. MYSQL_ROW row; //注意它的声明 typedef char **MYSQL_ROW,字符串数组 17. BOOL bCreate = FALSE; 18. 19. conn = mysql_init(NULL); 20. if(conn == NULL) 21. { 22. fprintf(stderr,"mysql_init() failed (probably out of memory)"); 23. exit(1
4、); 24. } 25. 26. if (mysql_real_connect(conn,host_name,user_name,password, 27. db_name,MYSQL_PORT,NULL,0) == NULL) 28. { 29. //在MYSQL初始化之后的操作如果有错误,可以用mysql_errno(MYSQL*)和 30. //mysql_errer(MYSQL*) 分别获得出错代号和描述 31. fprintf(stderr,"mysql_real_connect
5、() failed:Error %u (%s)", 32. mysql_errno(conn),mysql_error(conn)); 33. exit(1); 34. } 35. 36. printf("connect to db successful."); 37. if (bCreate) { 38. //第一次运行创建一个表mytable 39. sprintf(szSqlText,"create table mytable(time datetime,s1 char
6、(6),s2 char(11),s3 int,s4 int)"); 40. if (mysql_query(conn,szSqlText)) { 1. printf("Can't create table."); 2. mysql_close(conn); 3. return 0; 4. } 5. } 6. sprintf(szSqlText,"insert into mytable values('2000-3-10 21:01:30','Test','MySQLTest',20
7、00,3)"); 7. if (mysql_query(conn,szSqlText)) { 8. printf("Insert values error:Error %u (%s)", 9. mysql_errno(conn),mysql_error(conn)); 10. mysql_close(conn); 11. return 0; 12. } 13. else{ 14. //insert/delete/update 语句可用mysql-affected_rows()得到
8、受作用的行 15. printf("INSERT statement succeeded: %lu rows affected", 16. (unsigned long)mysql_affected_rows(conn)); 17. } 18. 19. //查询数据 20. sprintf(szSqlText,"select * fr