// I modified it to run normally. The test environment is mysql5.0 and XP.
// The key is to set the character set, set GBK, gb2312 to pass the test, and utf8 to fail.
// Run Program Create a database JJ first, pay attention to the following parameters (modified as your own)
CopyCode The Code is 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;
}
//// // Subfunction
Int conndb () // connect to the 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 the server
Mysql_set_character_set (MySQL, "gb2312"); // sets the character set.
Cout <"conn OK! "<Endl;
Return 0;
}
// Close the 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 ('2017-3-10 21:01:30 ',\
'Test ',\
'Qingfeng cold shange ',\
'Year ',\
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 result on my machine: