to myself 的分类学习日志

做自己想做的事
posts - 232, comments - 6, trackbacks - 0, articles - 0

mysql编程的简单实例

Posted on 2010-08-03 15:33 kongkongzi 阅读(223) 评论(0)  编辑 收藏 引用 所属分类: mysql
student.sql --- 预先需要的数据
use test;

 
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `id` 
int(10) unsigned NOT NULL DEFAULT '0' COMMENT '学生编号',
  `name` 
varchar(32NOT NULL DEFAULT '' COMMENT '学生姓名',
  
PRIMARY KEY (`id`)
) ENGINE
=InnoDB DEFAULT CHARSET=utf8;


insert into student(id, name) values(1'Richard'), (2'张三');

main.cpp --- 工程需要include mysql的头文件,link Ws2_32.lib libmysql.lib
#include <cstdio>
#include 
"winsock2.h"
#include 
"mysql/mysql.h"


int main(int argc, char *argv[])
{
    WORD wVersionRequested;
    WSADATA wsaData;
    wVersionRequested 
= MAKEWORD( 22 );
    WSAStartup( wVersionRequested, 
&wsaData );

    
const char* m_host = "localhost";
    
const char* m_user = "root";
    
const char* m_passwd = "root";
    
const char* m_db = "test";
    unsigned 
int m_port = 3306;

    MYSQL 
*pMySql = mysql_init((MYSQL*)NULL);
    
if (pMySql != NULL)
    {
        
if (!mysql_real_connect(pMySql, m_host, m_user, m_passwd, m_db, m_port, NULL, 0))
        {
            fprintf(stdout, 
"Connect DB  Error:%s", mysql_error(pMySql));
            
return false;
        }

        
char* query = "select * from student";
        
if (mysql_real_query(pMySql,  query, (unsigned long)strlen(query)))
        {
            fprintf(stdout, 
"Query DB Error:%s", mysql_error(pMySql));
            
return false;
        }

        MYSQL_RES 
* result = mysql_store_result(pMySql);
        
if (result)
        {
            MYSQL_ROW row;
            unsigned 
int num_field = mysql_field_count(pMySql);
            fprintf(stdout, 
"Query DB result:\n");
            unsigned 
int id;
            
char name[20= {'\0'};
            
while ((row = mysql_fetch_row(result)) != NULL)
            {
                id 
= atoi(row[0]);
                memcpy(name, row[
1], 20);
                fprintf(stdout, 
"student[%d]:%s\n", id, name);
            }
        }
        
else if (mysql_field_count(pMySql) != 0)
        {
            fprintf(stdout, 
"Store DB result Error:%s", mysql_error(pMySql));
            
return false;
        }
    }
    
return 0;
}