#include <windows.h>
#include <string>
#include <iostream>
#include <mysql.h>
#include <stdio.h>
int main()
{
char *host = "localhost";
char *user = "root";
char *pass = "ab1234";
char *db = "db1";
unsigned int port = 3306;
MYSQL *sock;
MYSQL_RES *res;
MYSQL_FIELD *fd;
MYSQL_ROW row;
char szSqlText[500]="";
int i;
int tcreate = 0;
sock = mysql_init(0);
if(sock && mysql_real_connect(sock, host, user, pass, db, 0, NULL, 0))
{
std::cout<<"connect mysql succeed!"<<std::endl;
mysql_query(sock, "set names gb2312");
if(!tcreate)
{
sprintf(szSqlText, "create table datatable (id int(3) auto_increment not null primary key, time datetime, name char(10) not null, address varchar(20), year date, s1 char(11), s2 int default'1') CHARACTER SET utf8");
std::cout<<"Create table tttable!"<<std::endl;
tcreate = 1;
if(mysql_query(sock, szSqlText))
{
std::cout<<"can't create table:"<<mysql_error(sock)<<std::endl;
mysql_close(sock);
return FALSE;
}
}
sprintf(szSqlText, "insert into datatable values('1', '2010-10-08', 'bj', 'szyz', '2010-10-08', 'MySQLTest', 20)");
std::cout<<"Insert data to table!"<<std::endl;
if(mysql_query(sock, szSqlText))
{
std::cout<<"Can't insert data o table "<<mysql_error(sock)<<std::endl;
mysql_close(sock);
return FALSE;
}
sprintf(szSqlText, "select * from datatable");
std::cout<<"select * from datatable!"<<std::endl;
if(mysql_query(sock, szSqlText))
{
mysql_close(sock);
return FALSE;
}
else
{
std::cout<<"mysql_store_result!"<<std::endl;
res=mysql_store_result(sock);
i = (int)mysql_num_rows(res);
std::cout << "Query: " << szSqlText << "\n" <<i<<" records bound:"<<std::endl;
for(i=0; fd = mysql_fetch_field(res); i++)
std::cout<<fd->name<<"\t";
std::cout<<std::endl;
while(row = mysql_fetch_row(res))
std::cout<<row[0]<<"\t"<<row[1]<<"\t"<<row[2]<<"\t"<<row[3]<<"\t"<<row[4]<<std::endl;
mysql_free_result(res);
}
}
else
{
std::cout<<"can't connect to the sock server "<< mysql_error(sock)<<std::cout;
mysql_close(sock);
return FALSE;
}
mysql_close(sock);
system("pause");
return 0;
}