Linux C language Mysql operations and Character Set settings, linuxmysql
I. C language Mysql operation II. Creating databases and tables
mysql> use TemWetDatabase changedmysql> create table monitor -> ( -> Id int not null, -> monitor_name varchar(50), -> monitor_com varchar(50), -> primary key(Id) -> );Query OK, 0 rows affected (0.10 sec)
C program testing
Example code of c connection operation database:
# Include <mysql/mysql. h> # include <stdio. h> # include <stdlib. h> # include <string. h> static char * server_groups [] = {"embedded", "server", "this_program_server", (char *) NULL}; int main () {MYSQL mysql; MYSQL_RES * res; MYSQL_ROW row; char sqlcmd [200]; int t, r; mysql_init (& mysql); // initialize the MYSQL identifier for connecting to if (! Mysql_real_connect (& mysql, "localhost", "root", "root", "sensers", 0, NULL, 0) {fprintf (stderr, "unable to connect to the database, error cause: % s/n ", mysql_error (& mysql);} else {puts (" database connection successful "); // insert a record to the database first // sprintf (sqlcmd, "% s", "insert into friends (name, telephone) Values ('XX', 'xx ') "); // mysql_query (& mysql, sqlcmd); sprintf (sqlcmd," % s "," set names utf8; "); t = mysql_real_query (& mysql, sqlcmd, (unsigned int) strlen (sqlcmd); sprintf (sqlcmd, "% s", "select * from senser;"); t = mysql_real_query (& mysql, sqlcmd, (unsigned int) strlen (sqlcmd); if (t) {printf ("failed to query database % s/n", mysql_error (& mysql ));} else {res = mysql_store_result (& mysql); // return all query result sets while (row = mysql_fetch_row (res )) {// mysql_fetch_row obtain the next row of the result set for (t = 0; t <mysql_num_fields (res); t ++) {// Number of result set columns printf ("% s \ t", row [t]);} printf ("\ n "); int wet = atoi (row [2]); printf ("% d \ n", wet);} mysql_free_result (res); // The operation is complete, query Result set} mysql_close (& mysql); // closes the database connection} mysql_library_end (); // closes the MySQL database return EXIT_SUCCESS ;}
Compile the c file:
# gcc sqltest.c -o sqltest -lmysqlclient
Compiled successfully and executed successfully.
Iv. Character Set settings
A piece of data with Chinese characters is inserted, but Chinese characters are garbled. This should be the character encoding problem of the database.
Solution:
Modify the MySQL configuration file/etc/mysql/my. cnf
Save and restart the mysql service.
View the character set of the database:mysql> show variables like 'character_set_%';
Delete the previous database data table, create a new data table, and insert the data. It supports Chinese characters perfectly.