I modified it, can run normally, test environment for MYSQL5.0,XP
Key is set on the character set, set gbk,gb2312 test pass, UTF8 test failed
Set up database JJ before running the program, pay attention to the following parameters (modified for your own)
Copy Code code as follows:
char *host = "localhost";
Char *user = "root";
Char *pass = "674800";
Char *db = "JJ";
#include <windows.h>
#include <iostream>
#include <mysql.h>
#include <stdio.h>
#include <string.h>
using namespace Std;
#pragma comment (lib, "Libmysql.lib")
int conndb ();
int create_table ();
int insert_table ();
int select_table ();
int disconndb ();
MYSQL *mysql;
Mysql_res *res;
Mysql_field * FD;
Mysql_row ROW;
Char szsqltext[500]= "";
int i;
int main ()
{
Conndb ();
Create_table ();
Insert_table ();
Select_table ();
Disconndb ();
return 0;
}
Child functions
int conndb ()//Connection database
{
char *host = "localhost";
Char *user = "root";
Char *pass = "674800";
Char *db = "JJ";
MySQL = Mysql_init ((mysql*) 0);
Mysql_real_connect (MySQL, host, user, pass, db,3306, NULL, 0); Link to server
Mysql_set_character_set (MySQL, "gb2312"); Setting the character set
cout<< "Conn ok!" <<endl;
return 0;
}
Close Database
int Disconndb ()
{
Mysql_close (MySQL);
cout<< "Disconn ok!" <<endl;
return 0;
}
Create a table
int create_table ()
{
Mysql_set_character_set (MySQL, "gb2312");
sprintf (Szsqltext, \
"CREATE TABLE mytable \
(S0 varchar (100), \
S1 char (6), \
S2 varchar (4), \
S3 varchar (3), S4 int) \
ENGINE=INNODB \
DEFAULT charset=gb2312 ");
if (mysql_query (MySQL, szsqltext))
cout<< "occurred an error:" <<mysql_error (MySQL) <<endl;
return 0;
}
int insert_table ()
{
Mysql_set_character_set (MySQL, "gb2312");
sprintf (Szsqltext,
"INSERT INTO mytable\
VALUES (' 2000-3-10 21:01:30 ', \
' Test ', \
' Qing-Wind sword ', \
' Years of love ', \
2500) ");
if (mysql_query (MySQL, szsqltext))
cout<< "occurred an error:" <<mysql_error (MySQL) <<endl;
return 0;
}
int select_table ()
{
Mysql_set_character_set (MySQL, "gb2312");
sprintf (Szsqltext, "select * from MyTable");
if (mysql_query (MySQL, szsqltext))
{
cout<< "occurred an error:" <<mysql_error (MySQL) <<endl;
Mysql_close (MySQL);
return FALSE;
}
res = Mysql_store_result (mysql);
i = (int) mysql_num_rows (res);
cout<< "Query:" <<szSqlText<< "\ n" <<i<< "records found:" <<endl;
for (i = 0; fd = Mysql_fetch_field (res); i++)
cout<<fd->name<< "T";
cout<<endl;
while (row = mysql_fetch_row (res))
cout<<row[0]<< "\ t" <<row[1]<< "\ T" <<row[2]<< "\ T" <<row[3]<< "T" <<row[4]<<endl;
Mysql_free_result (RES);
cout<< "Select ok!" <<endl;
return 0;
}
Running results on my machine: