Connect Mysql Data using C language in Linux

Source: Internet
Author: User

 The following content is from beginning Linux Programming

C. Connect to MySQL

1. initialize a connection handle Structure

2. actually connect

# Include <stdlib. h>
# Include <stdio. h>
# Include "mysql. H"
Int main (char arc, char * argv [])
{
MySQL * conn_ptr;

Conn_ptr =Mysql_init(Null );

Conn_ptr =Mysql_real_connect(Conn_ptr, "localhost", "Derrick", "123456 ",
"Foo", 0, null, 0 );

If (conn_ptr)
Printf ("connection success \ n ");
Mysql_close(Conn_ptr );
}

Exit (exit_success );

// Handle errors

# Include <stdlib. h>
# Include <stdio. h>
# Include "mysql. H"
Int main (char arc, char * argv [])
{
MySQL my_connection;
Mysql_init (& my_connection );
If (mysql_real_connect (& my_connection, "localhost", "Rick", "I don't know ",
"Foo", 0, null, 0 ))
{
Printf ("connection success \ n ");
Mysql_close (& my_connection );
}
Else
{
Fprintf (stderr, "Connection Failed \ n ");
If (mysql_errno (& my_connection ))
Fprintf (stderr, "connection error % d: % s \ n", mysql_errno (& my_connection), mysql_error (& my_connection ));
If (mysql_errno (& my_connection ))
Fprintf (stderr, "connection error % d: % s \ n", mysql_errno (& my_connection), mysql_error (& my_connection ));
}
Exit (exit_success );
}
Note: The connection fails because one of the mysql_real_connect Parameters "I don't know' corresponds to an incorrect password.

Output: Connection Failed
Connection error 1045: Access denied for user
'Rick '@ 'localhost' (using password: Yes)

 

Compile command: GCC source file name-I/usr/include/MySQL-L/SUR/lib/MySQL-lmysqlclient-O destination file name

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.