Access Mysql Data using C language-connection and error handling

Source: Internet
Author: User

Wcdj

 

 

MySQL can be accessed through many different programming languages, such as C, C ++, Java, Perl, Python, TCL and PHP. This article mainly summarizes how to access Mysql Data Using the C language interface.

(1) connection routine
(2) handle errors

(1) connection routine

Connect to the MySQL database using C languageTwo steps:
(1) initialize a connection handle structure. UseMysql_initTo initialize the connection handle.
(2) actually connect. UseMysql_real_connectTo provide parameters for a connection.

Other steps:
(3) UseMysql_closeClose the connection.
(4)Mysql_optionsUsed to set options.Note:: It can only be called between mysql_init and mysql_real_connect. Only one option can be set for mysql_options at a time, so you have to call it once every time you set an option.

The specific process is as follows:

Log on to MySQL
$ Mysql-u root-P
Enter Password
Create a local user wcdj
Mysql> grant all on *. * To wcdj @ localhost identified by 'secretpassword ';(Note:: The last semicolon)
Exit Root User
Mysql>/Q
Bye
Log on to the newly created user wcdj
$ Mysql-u wcdj -- Password = secretpassword
Create a new database newdatabase
Mysql> Create Database newdatabase;
Log out of the wcdj user
Mysql>/Q

WriteCreate_children. SQLFile, used to create tables and add data.

--
-- Create the table children
--

Create Table Children (
Childno int (11) not null auto_increment,
Fname varchar (30 ),
Age int (11 ),
Primary Key (childno)
);

--
-- Populate the table 'children'
--
Insert into children (childno, fname, age) values (1, 'wcdj', 21 );
Insert into children (childno, fname, age) values (2, 'gerry', 22 );
Insert into children (childno, fname, age) values (3, 'echo ', 23 );

Log on to MySQL
$ Mysql-u wcdj -- Password = secretpassword newdatabase (note that the following newdatabase is used to specify the database to be used)
Create a table children in the new database newdatabase and add data:
Mysql>/. create_children. SQL
View newly added data:
Select * from children;

1 wcdj 21
2 Gerry 22
3 Echo 23

Connect1.c

 

# Include <stdlib. h> <br/> # include <stdio. h> <br/> # include "MySQL. H "<br/> int main () <br/> {<br/> MySQL * conn_ptr; <br/> conn_ptr = mysql_init (null ); <br/> If (! Conn_ptr) <br/>{< br/> fprintf (stderr, "mysql_init failed/N"); <br/> return exit_failure; <br/>}< br/> conn_ptr = mysql_real_connect (conn_ptr, "localhost", "wcdj", "123", "newdatabase", 0, null, 0 ); <br/> If (conn_ptr) <br/> {<br/> printf ("connection success/N "); <br/>}< br/> else <br/> {<br/> printf ("Connection Failed/N "); <br/>}< br/> mysql_close (conn_ptr); <br/> return exit_success; <br/>}< br/>

Compile the program:
$ Gcc-I/usr/include/MySQL connect1.c-L/usr/lib/MySQL-lmysqlclient-O connet1

Test:
$./Connect1
Connection success
$

 

(2) handle errors

(1) unsigned intMysql_errno(MySQL * connection); (error code)
(2) char *Mysql_error(MySQL * connection); (Text error message)
You can call mysql_errno and pass the connection structure to obtain the error code, which is usually not 0. If no error code is set, it returns 0.
Note:: Because the error code is updated every time you call the database, you can only get the error code of the last command. However, the two error check routines listed above are exceptions and will not cause updates to the error codes.
You can also call mysql_error to provide meaningful text information instead of monotonous error codes. This information is written into some internal static memory space, so if you want to save the error text, you need to copy it to another place.
Note:: A problem occurs when mysql_real_connect is called, because it returns a null pointer in case of failure and does not provide an error code. However, if you use the connection handle as a variable, you can still process it even if mysql_real_connect fails.

Connect2.c
Use a non-dynamically allocated Connection Structure and write some basic error handling code.

# Include <stdlib. h> <br/> # include <stdio. h> <br/> # include "MySQL. H "<br/> int main () <br/> {<br/> MySQL my_connection; <br/> mysql_init (& my_connection ); </P> <p> If (mysql_real_connect (& my_connection, "localhost", "wcdj", "123", "newdatabase", 0, null, 0 )) <br/>{< br/> printf ("connection success/N"); <br/> mysql_close (& my_connection ); <br/>}< br/> else <br/> {<br/> fprintf (stderr, "Connection Failed/N "); <br/> If (mysql_errno (& my_connection) <br/>{< br/> fprintf (stderr, "connection error % d: % s/n ", mysql_errno (& my_connection), <br/> mysql_error (& my_connection); <br/>}< br/> return exit_success; <br/>}< br/>

Compile the program:
$ Gcc-I/usr/include/MySQL connect2.c-L/usr/lib/MySQL-lmysqlclient-O connet2

If no newdatabase is created, the following error message is displayed when connect2 is run:
Test:
$./Connect2
Connection Failed
Connection error 1049: Unknown database 'newdatabase'
Log on to MySQL
$ Mysql-u wcdj -- Password = 123
Create a new database newdatabase
Mysql> Create Database newdatabase;
Log out of the wcdj user
Mysql>/Q

Test connect2 again:
Connection success

Change Password 123 in connect2.c to an incorrect password. The following error message is displayed after the test:
Connection Failed
Connection error 1045: Access denied for user 'wcdj' @ 'localhost' (Usig password: Yes)

 

 

Reference:

Linux programming (version 4th) Chapter 8th p.283

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.