int main ( int argc, char *argv[] ) { //初始化mysql的句柄conn conn = mysql_init ( NULL ); //连接mysql数据库 mysql_real_connect ( conn, /* pointer to connection handler */ "localhost", /* host to connect to */ "user_name", /* user name */ "password", /* password */ "test", /* database to use */ 0, /* port (default 3306) */ NULL, /* socket or /var/lib/mysql.sock */ 0 ); /* flags (none) */
//关闭数据库,句柄 mysql_close ( conn ); return0; } compilation: gcc -Wall connect_simplest.c -lmysqlclient If mysql.h is not in a standard place: -I/path/to/the/mysql. If libmysqlclient.so or libmysqlclient.a is not in a standard place: -L/path/to/the/mysqlclient/library. (match better use Makefile)
For more secure connection you should use structoption from
MYSQL *conn; MYSQL_RES *res; MYSQL_ROW row; constchar* groups[] = {"client",NULL}; struct option long_options[] = { {"host",required_argument,NULL,'h'}, {"user",required_argument,NULL,'u'}, {"password",optional_argument,NULL,'p'}, {"port",required_argument,NULL,'P'}, {"socket",required_argument,NULL,'S'}, {0,0,0,0} };
} //---------------------------------------------------------- unsignedlong how_rows (void) //---------------------------------------------------------- { return (unsignedlong) mysql_num_rows(res); } //---------------------------------------------------------- void print_error(char* msg) //---------------------------------------------------------- { fprintf(stderr,"%s\n",msg); if ( conn != NULL ) { fprintf(stderr,"Error: %u%s\n",mysql_errno(conn), mysql_error(conn)); } } OUTPUT: // There are 16 databases // ===================== // School // Student // TransAct // ana // bank // billing // helpfile // helpfile1 // mysql // phone // sales_analis // samp_db // student // studentdb // test // user1
Of course, you have to hide your password from the direct viewing. I usually use <> that I created for similar purposes. #include #include
MYSQL *conn; MYSQL_RES *res; MYSQL_ROW row;
int main () { conn = mysql_init ( NULL ); mysql_real_connect ( conn,"localhost","ana", password(),"bank",0,NULL,0);
mysql_query(conn,"show tables"); res = mysql_store_result(conn);
mysql_field_seek(res,0); for ( i = 0; i < mysql_num_fields(res); i++ ) { field = mysql_fetch_field(res); column_length = strlen(field->name); if ( column_length < field->max_length ) column_length = field->max_length; if ( column_length < 4 && !IS_NOT_NULL(field->flags) ) column_length = 4; field->max_length = column_length; } print_line(); fputc('\n',stdstdout mysql_field_seek(res,0); for ( i = 0; i < mysql_num_fields(res); i++ ) { field = mysql_fetch_field(res); fprintf(stdout," %-*s ",field->max_length,field->name); } fputc('\n',stdstdout print_line(); fputc('\n',stdstdout while ((row = mysql_fetch_row(res)) != NULL) { mysql_field_seek(res,0);
for ( i = 0; i < mysql_num_fields(res); i++ ) { field = mysql_fetch_field(res); if ( row[i] == NULL ) fprintf(stdout," %-*s ",field->max_length,"NULL"); else if ( IS_NUM(field->type) ) fprintf(stdout," %*s ",field->max_length,row[i]); else fprintf(stdout," %-*s ",field->max_length,row[i]); } fputc('\n',stdstdout } fputc('\n',stdstdout mysql_free_result(res); } //---------------------------------------------------------- void print_line (void) //---------------------------------------------------------- { MYSQL_FIELD *field; unsignedint i, j;
mysql_field_seek(res,0); for ( i = 0; i < mysql_num_fields(res); i++ ) { field = mysql_fetch_field(res); for ( j = 0; j < field->max_length + 2; j++ ) fputc('=',ststdout } } OUTPUT: There are 16 databases ===================== School Student TransAct ana bank billing helpfile helpfile1 mysql phone sales_analis samp_db student studentdb test user1
The database SCHOOL consists tables: ========================================== school_student
The database STUDENT consists tables: ========================================== students
The database TRANSACT consists tables: ========================================== destination purpose test transkepper
The database ANA consists tables: ========================================== addition_info cases student_info student_records teacher teacher_room temp temp_student temp_teacher temp_teacher_room
The database BANK consists tables: ========================================== BANK_WORKER BRANCHES CHECKING_ACCT CHECKING_REP CLOSE_CHECK_ACCT CLOSE_CUSTOMERS CLOSE_SAVINGS_ACCT CUSTOMERS LOAN_ACCT SAVINGS_ACCT SAVINGS_REP
The database BILLING consists tables: ==========================================
The database HELPFILE consists tables: ========================================== datafile helpfile
The database HELPFILE1 consists tables: ========================================== datafile
The database PHONE consists tables: ========================================== address phone
The database SALES_ANALIS consists tables: ========================================== departments quote sales
The database SAMP_DB consists tables: ========================================== absence event member president score student
The database STUDENT consists tables: ========================================== student subjects
The database STUDENTDB consists tables: ========================================== student subjects
The database TEST consists tables: ========================================== t t1 test test1 test2
The database USER1 consists tables: ==========================================
What database do you want to use? (0-quit): bank What table do you want to see? (0-quit): BRANCHES ================================================================ BRANCH_NAME BRANCH_NUM BRANCH_ADDRESS ================================================================ BROOKLYN_BRANCH 001718 Ave N, Brooklyn, NY 11234 MANHATTAN_BRANCH 0022915th Ave, New York, NY, 10070
What table do you want to see? (0-quit): BANK_WORKER ============================================================= B_SSN B_FNAME B_LNAME B_ID B_PHONE B_EXT ============================================================= 277-65-8877 John Smith 001718-999-6655313 665-66-4423 Kevin Walters 001718-999-6655444 775-99-7543 Peter Kats 002212-999-8655111 777-65-6654 Anna Katsnelson 001718-999-6655222 765-87-6540 Sam Jefferson 002212-999-8655123
What table do you want to see? (0-quit): 0 What database do you want to use? (0-quit): 0