After installing MySQL on Linux, create a database and table for testing and insert records. The SQL statement is as follows:
Create Database ta; <br/> Use ta </P> <p> Create Table T1 (<br/> ID integer not null, <br/> Name text not null <br/>); </P> <p> insert into T1 values (1, 'n1 '); <br/> insert into T1 values (2, 'n2 '); <br/> insert into T1 values (3, 'n3'); <br/>
To obtain records in a table, use the following MySQL APIs:
Mysql_init ()
Mysql_real_connect ()
Mysql_real_query ()
Mysql_store_result ()
Mysql_fetch_row ()
Mysql_free_result ()
Mysql_close ()
The three struct defined in MySQL must be used in the operation.
MySQL
Mysql_res
Mysql_row
The general steps are as follows:
1. Call mysql_init () to initialize the MySQL structure. This struct is required for many function execution.
2. Call mysql_real_connect () to connect to the database. The parameters include the database name, database login name, and database password.
3. Call mysql_real_query () to execute a select SQL statement and obtain the select result through the return value of mysql_store_result (). The returned result is a pointer of the mysql_res structure.
4. Call mysql_fetch_row () to obtain a record. The return value of the function is the mysql_row object, which is a two-dimensional char array. After obtaining a record, mysql_fetch_row will automatically move the cursor down a record.
5. Call mysql_free_result () to release the result resource and call mysql_close to close the connection.
SimpleCodeAs follows (no failure judgment is made ):
# Include <MySQL/MySQL. h> <br/> # include <stdio. h> <br/> # include <stdlib. h> <br/> # include <string. h> </P> <p> int main () <br/>{< br/> MySQL; <br/> mysql_init (& MySQL ); <br/> mysql_real_connect (& MySQL, null, "root", "123", "ta", 0, null, 0); <br/> mysql_real_query (& MySQL, "select * from T1", 16); </P> <p> mysql_res * res = mysql_store_result (& MySQL); <br/> int num_fields = mysql_num_fields (RES ); </P> <p> mysql_ro W row; <br/> while (ROW = mysql_fetch_row (RES) <br/>{< br/> int I; <br/> for (I = 0; I <num_fields; I ++) <br/>{< br/> char Buf [100]; <br/> sprintf (BUF, "[% s]", row [I]? Row [I]: "null"); <br/> fprintf (stdout, Buf); <br/>}< br/> fprintf (stdout, "/N "); <br/>}</P> <p> mysql_free_result (RES); <br/> mysql_close (& MySQL); </P> <p> exit (0 ); <br/>}< br/>