Makefile
.suffixes:. C. oCC=gccSRCs=mysql1.c MYDB.CObjs=$(SRCs:. c=.o)EXEC=mysql1All : $(Objs)$(CC)-O$(EXEC)$(Objs)-lmysqlclient@echo '-------------OK--------------'. C.o: $(CC) -Wall-g-o[email protected]-C$< Clean :Rm-f$(Objs) Rm-f core*
Mydb.h
#ifndef mydb_h_ #define MYDB_H_ void init_db (); int conn_db (const char *hostname, const char *username, const char *password, const char *dbname); void disconn_db (); int open_db (const char *sql); int exec_db (const char *sql); #endif/* Mydb_h_ */
Mydb.c
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <mysql/mysql.h>#include "mydb.h"MYSQL *connection = NULL; MySQL MySQL;voidinit_db () {mysql_init (&mysql);//Initialize MySQL}intconn_db (Const Char*hostname,Const Char*username,Const Char*password,Const Char*dbname) {if(connection) mysql_close (connection); Connection = Mysql_real_connect (&MYSQL, hostname, username, password, dbname,0,0,0);//Connect to MySQL if(Connection = = NULL) {printf("%s\n", Mysql_error (&mysql));return-1;//Connection failed, return-1}printf("Success Connect to mysql\n");return 0;}voiddisconn_db ()//Disconnecting database connections{if(connection) {mysql_close (connection); connection = NULL; }}intopen_db (Const Char*sql)//Execute SQL statement with return data set{intstate = mysql_query (connection, SQL);//Execute SQL statement if(state! =0) {printf("%s\n", mysql_error (connection));return-1;//Execution failed, return-1} mysql_res *result = Mysql_store_result (connection);//Get query Results if(Result = = (Mysql_res *) NULL) {printf("%s\n", mysql_error (connection));return-1;//Execution failed, return-1}Else{Mysql_field *sqlfield;intIfieldcount =0; while(1)//Loop through all fields{Sqlfield = Mysql_fetch_field (result);if(Sqlfield = = NULL) Break;printf("%s\t", sqlfield->name);//Print field names to screenifieldcount++; }printf("\ n");//print a \ n character at the end of each lineMysql_row Sqlrow; while(1)//loop to each row{Sqlrow = mysql_fetch_row (result);if(Sqlrow = = NULL) Break;intI for(i =0; i < Ifieldcount; i++)//loop to get each field in each row{if(Sqlrow[i] = = NULL)printf("Null\t");//If the value is null, the screen prints "null" Else printf("%s\t", (Const Char*) sqlrow[i]);//Screen printing as field contents}printf("\ n");//print a \ n character at the end of each line}printf("Query is OK,%u rows affected\n", (unsigned int) Mysql_affected_rows (connection)); Mysql_free_result (result); }return 0;}intexec_db (Const Char*sql)//Execute SQL statement with no return data set{intstate = mysql_query (connection, SQL);//Execute SQL statement if(state! =0) {printf("%s\n", mysql_error (connection));return-1; }printf("Query is OK,%u rows affected\n", (unsigned int) Mysql_affected_rows (connection));return 0;}
mysql1.c
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <string.h>#include <sys/types.h>#include <errno.h>#include <termios.h>#include "mydb.h"voidSqldbConst Char*SRC)//Parameter SRC is the SQL statement to execute{if((strncmp(SRC,"SELECT",6) ==0) || (strncmp(SRC,"SELECT",6) ==0) || (strncmp(SRC,"Show",4) ==0) || (strncmp(SRC,"SHOW",4) ==0) || (strncmp(SRC,"desc",4) ==0) || (strncmp(SRC,"DESC",4) ==0) {open_db (SRC);//If SRC is a return dataset SQL statement, then call the open_db function}Else{exec_db (SRC);//If SRC is not a return dataset SQL statement, then call the exec_db function}}voidWorkConst Char*userid,Const Char*password) {init_db ();if(Conn_db ("localhost", UserID, Password,"Test") !=0)//Connect to database{return;//Connection database failed, function exited}Charbuf[2048]; while(1)//loop read from keyboard{Write (Stdout_fileno,"Mysql1>",strlen("Mysql1>"));//Screen output command prompt mysql1> memset(BUF,0,sizeof(BUF)); Read (Stdin_fileno, buf,sizeof(BUF));//wait for the user to enter from the keyboard if(strncmp(BUF,"Quit",4) ==0) Break;//user input quit, loop break;Sqldb (BUF); } disconn_db ();//Disconnecting database connections}structTermios Oldterm;voidSetstty ()//Set input backspace key, do not echo{//system ("Stty erase ^h");//execute Shell command, can also be used to set the reading user keyboard input, backspace key does not Echo structTermios term;if(Tcgetattr (Stdin_fileno, &term) = =-1)//Get the system Termion settings{printf("Tcgetattr error is%s\n", Strerror (errno));return; } oldterm = term;//Keep current Termios settings so that the program can be restored when exiting Termios /* Term.c_lflag &= ~icanon;//cancel icanon option (nonstandard input) Term.c_lflag |= icanon;//set icanon option (canonical input) term.c_cc field to set Specific special input characters, such as c_cc[verase] for backspace key, term.c_cc[verase] = ' \b '; meaning to change the backspace key to ' \b ' verase means to erase a character forward, vintr to send CTRL + C interrupt signal, CTRL + C The ASCII code is 3 for example: term.c_cc[vintr] = ' \ t '; the second parameter indicates that the TAB key is set to Terminal signal tcsetattr, Tcsaflush: The change takes effect after all output has been sent, and when the change occurs, All unread input data is deleted Tcsanow: change takes effect immediately tcsadrain: The change occurs after all output has been sent, and should be used if you change the output parameter */Term.c_cc[verase] =' \b ';//' \b ' is the backspace ASCII code if(Tcsetattr (Stdin_fileno, Tcsanow, &term) = =-1)//Set system Termion{printf("Tcsetattr error is%s\n", Strerror (errno)); }return;}voidReturnstty ()//Termios settings for recovery system{if(Tcsetattr (Stdin_fileno, Tcsaflush, &oldterm) = =-1)//Set system Termion{printf("Tcsetattr error is%s\n", Strerror (errno)); }return;}intMainintArgChar*args[]) {if(Arg <4)//If there are no arguments, the main function exits{returnExit_failure; }if(strncmp(args[1],"-U",2) !=0)//If the second parameter is not a-u,main function exits{returnExit_failure; }if(strncmp(args[3],"-P",2) !=0)//If the fourth parameter is not a-p,main function exits{returnExit_failure; }Const Char*PASSWD = Getpass ("Please input password:");//Enter password, screen does not EchoSetstty ();//Set input backspace key, do not echoWork (args[2], passwd); Returnstty ();//Termios settings for recovery system returnexit_success;}
MySQL database programming--c language programming implementation MySQL Client