/*************************************************************************
> File Name: mysql1.c
> Author: WuPeng
> Mail: 8264398987@qq.com
> Created Time: 2016年08月25日 星期四 14时29分32秒
************************************************************************/
#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 ) //参数src为要执行的SQL语句
{
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 ); //如果src为有返回数据集的SQL语句,那么调用open_db
}else
{
exec_db( src );//如果src为没有数据返回的SQL语句,那么调用exec_db
}
}
void work( const char *userid, const char *password )
{
init_db(); // 初始化数据库
if( conn_db( "localhost", userid, password, NULL ) != 0 )
{
return ; //连接数据库失败
}
char buf[1024];
while(1)
{
write( STDOUT_FILENO, "mysqlWP>", strlen( "mysqlWP>" ) );//屏幕输出命令提示符mysqlWP>
memset( buf, 0, sizeof(buf) );
read( STDIN_FILENO, buf, sizeof(buf) );
if( strncmp(buf, "quit", 4 ) == 0 )
break; // 用户输入quit,循环break掉
sqldb( buf );
}
disconn_db(); //断开数据库连接
}
struct termios oldterm;
void setstty()
{
struct termios term;
if( tcgetattr(STDIN_FILENO, &term ) == -1 ) //得到系统的termio的设置
{
printf( "tcgetattr error: %s\n", strerror(errno) );
}
oldterm = term; //保留当前termio的设置,以便程序退出的时候可以恢复termios
term.c_cc[VERASE] = '\b';
if( tcsetattr(STDIN_FILENO, TCSANOW, &term ) == -1 )
{
printf( "tcsetattr error: %s\n", strerror(errno) );
}
return ;
}
void returnstty()
{
if( tcsetattr(STDIN_FILENO, TCSAFLUSH, &oldterm) == -1 )
{
printf( "tcsetattr error: %s\n", strerror(errno) );
}
return ;
}
int main( int argc, char *argv[] )
{
if( argc < 4 )
{
printf( "参数较少\n" );
exit(-1);
}
if( strncmp( argv[1], "-u", 2) != 0 )//如果第二个参数不是-u,main函数退出
{
printf( "第二个参数应该是-u\n" );
exit(-1);
}
if( strncmp( argv[3], "-p", 2) != 0 )//如果第四个参数不是-p,main函数退出
{
printf( "第四个参数应该为:-p" );
exit(-1);
}
const char *passwd = getpass( "please input password:" );//输入密码,不回显
setstty();
work( argv[2], passwd );
returnstty();
return 0;
}