MySQL的简单实用事例
#include<iostream>
#include<mysql/mysql.h>
#include<errno.h>
#include<string.h>
using namespace std;
int main()
{
MYSQL *mpcon = mysql_init((MYSQL *)0);
MYSQL_RES *mp_res;
MYSQL_ROW mprow;
if(!mysql_real_connect(mpcon,"127.0.0.1","root","123456",NULL,33 06,NULL,0))
{
cerr<<"sql connect fail;errno:"<<errno<<endl;
return 0;
}
if(mysql_select_db(mpcon,"chat"))
{
cerr<<"select fail:errno:"<<errno<<endl;
return 0;
}
char cmd[100] = "insert into rootlist values('lisi','456789');";
if(mysql_real_query(mpcon,cmd,strlen(cmd)))
{
cerr<<"0 query fail;errno:"<<errno<<endl;
return 0;
}
char cmd1[100] = "insert into user values('wangwu','456789');";
if(mysql_real_query(mpcon,cmd1,strlen(cmd1)))
{
cerr<<"1 query fail;errno:"<<errno<<endl;
return 0;
}
char cmd2[100] = "select * from rootList where name='lisi';";
if(mysql_real_query(mpcon,cmd2,strlen(cmd2)))
{
cerr<<"2 query fail;errno:"<<errno<<endl;
return 0;
}
mp_res = mysql_store_result(mpcon);
mp_row = mysql_fetch_row(mp_res);
cout<<"name:"<<mp_row[0]<<" "<<"num"<<mp_row[1]<<endl;
char cmd3[100] = "select * from user;";
if(mysql_real_query(mpcon,cmd3,strlen(cmd3)))
{
cerr<<"3 query fail;errno:"<<errno<<endl;
return 0;
}
mp_res = mysql_store_result(mpcon);
while(mp_row = mysql_fetch_row(mp_res))
{
cout<<"name:"<<mp_row[0]<<" "<<"num"<<mp_row[1]<<endl;
}
mysql_free_result(mp_res);
mysql_close(mp_con);
return 0;
}