Makefile
. Suffixes:. C. occ=gccsrcs=mysql1.cmydb.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;void init_db () {mysql_init (&mysql);//Initialize Mysql}int conn_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 mysqlif (connection = = NULL) {printf ("%s\n", Mysql_error (& MySQL); return-1;//connection failed, return -1}printf ("Success Connect to mysql\n"); return 0;} void disconn_db ()//Disconnect database connection {if (connection) {mysql_close (connection); connection = NULL;}} int open_db (const char *sql)//executes the SQL statement with the return dataset {int state = 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 result if ( result = = (Mysql_res *) NULL) {printf ("%s\n", mysql_error (Connection)), return-1;//execution failed, return-1} Else{mysQl_field *sqlfield;int ifieldcount = 0;while (1)//loop through all fields {Sqlfield = Mysql_fetch_field (result); if (Sqlfield = = NULL) break;printf ("%s\t", sqlfield->name);//print field name ifieldcount++ to screen;} printf ("\ n");//The end of each line prints a \ n character mysql_row sqlrow;while (1)//loop to each line {Sqlrow = mysql_fetch_row (result); if (Sqlrow = = NULL) Break;int i;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 "N ULL "elseprintf ("%s\t ", (const char *) sqlrow[i]);//The screen is printed as a field content}printf (" \ n ");//a \ n character is printed 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;} int exec_db (const char *sql)//executes an SQL statement that does not return a dataset {int state = 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" void sqldb (const char *SRC)// The 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, call the exec_db function}}void Work (const char *userid, const char *password) {init_db (); if (conn_db ("localhost", userid, Password, "Test")! = 0)//Connect to Database {return;//Connection database failed, function exits}char buf[2048];while (1)//loop reads 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 the IF (strncmp, "buf" from the keyboard); Quit ", 4) = = 0) break;//user input quit, loop break;sqldb (BUF);} disconn_db ();//Disconnect database connection}struct Termios OldteRm;void Setstty ()//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 struct Termios term; if (Tcgetattr (Stdin_fileno, &term) = =-1)//Get system Termion Settings {printf ("Tcgetattr error is%s\n", Strerror (errno)); return;} Oldterm = term;//retains the current Termios setting so that the program can resume Termios/*term.c_lflag &= ~icanon;//cancel icanon option (nonstandard input) Term.c_lflag |= icanon;//Set the Icanon option (Spec input) term.c_cc field to set the specific input character, such as c_cc[verase] for backspace key, term.c_cc[verase] = ' \b '; meaning to change the backspace key to ' \ The B ' Verase represents a forward-erase character, and the VINTR represents a CTRL + C interrupt signal, and the ASCII code for CTRL + C is 3 For example: term.c_cc[vintr] = ' \ t ', meaning that the TAB key is set to the terminal signal tcsetattr, The second parameter shows that Tcsaflush: All output is sent after the change takes effect, and when the change occurs, all input data that is not read is deleted Tcsanow: The change takes effect immediately tcsadrain: The change takes place after all output has been sent, and should be used if you change the output parameter */ Term.c_cc[verase] = ' \b ';//' \b ' for backspace key ASCII if (Tcsetattr (Stdin_fileno, Tcsanow, &term) = =-1)//Set System termion{printf ( "Tcsetattr error is%s\n", Strerror (errno)); return;} void Returnstty ()//Termios setting of the recovery system {if (Tcsetattr (Stdin_fileno, Tcsaflush, &oldterm) = =-1)//Set system termion{printf (" Tcsetattr error is%s\n ", strerror (errNO));} return;} int main (int arg, char *args[]) {if (ARG < 4)///If there are no arguments, the main function exits {return exit_failure;} if (strncmp (args[1], "-U", 2) = 0)//If the second parameter is not a-u,main function exit {return exit_failure;} if (strncmp (args[3], "-P", 2)! = 0)//If the fourth parameter is not-p,main function exit {return exit_failure;} const char *PASSWD = getpass ("Please input password:");//input password, screen does not echo setstty ();//Set Input backspace key, do not echo work (args[2], passwd); Returnstty ();//Recovery System Termios set return exit_success;}
MySQL database programming--c language programming implementation MySQL Client