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