数据库操作
基本命令 数据库/表增删
create database 数据库名
drop database 数据库名
create table 表名 (字段)
drop table 表名
基本命令 修改表
alter table 表名 drop column 列名
alter table 表名 add column 列名 类型
alter table 表名 change 列名 新列名 类型
基本命令 数据增删改查
insert into 表名(.., ..., ...) values(..., ..., ...)
delete from 表名 where elemX=...
update 表名 set elemY=... where elemX=...
select [列名, ...] from 表名 (where elemX=...)
数据库授权访问
grant [select,...], on 数据库名.表名 to 用户名@”%” identified by “密码”
flush privileges
1: 数据库名, 表名 可以用 *.* , 数据库.*
2: @localhost 只允许从本地登陆操作
3: grant all privileges on ... 给予所有权限
数据库收回授权
revoke [delete, ...] on 数据库名.表名 from 用户名
#include <mysql/mysql.h> #include <stdio.h> #include <stdlib.h> #define HOST "localhost" #define USER "root" #define PASS "rowe" #define DBNAME "linux" void Usage() { printf("Usage: "); printf(" add:insert data to table "); printf(" delete:delete data from table "); printf(" update:modify data in table "); printf(" select:show datas in table "); printf(" "); } void TestMysql() { int iRet; MYSQL conn; //step1:init conn mysql_init(&conn); //step2:connect to mysql server if (!mysql_real_connect(&conn, HOST, USER, PASS, DBNAME, 0, NULL, 0)) { printf("connect database failed:%s ", mysql_error(&conn)); return; } Usage(); char szCmd[100]; char sql[1000]; char args[3][40]; while (1) { fprintf(stderr, "->"); scanf("%s", szCmd); if (!strcmp(szCmd, "add")) { fprintf(stderr, "input[name,sex,mobaile]:"); scanf("%s%s%s", args[0], args[1], args[2]); //construct sql string sprintf(sql, "insert into student(name ,sex,mobile) value('%s','%s','%s')", args[0], args[1], args[2]); } else if (!strcmp(szCmd, "delete")) { fprintf(stderr, "input[name]:"); scanf("%s", args[0]); //construct sql string sprintf(sql, "delete from student where='%s'", args[0]); } else if (!strcmp(szCmd, "update")) { fprintf(stderr, "input[name,column_name,column_value]:"); scanf("%s%s%s", args[0], args[1], args[2]); //construct sql string sprintf(sql, "update student set %s='%s' where name='%s'", args[1], args[2]); } else if (!strcmp(szCmd, "select")) { fprintf(stderr, "input[name]:"); scanf("%s", args[0]); // construct sql string if (!strcmp(args[0], "*")) { sprintf(sql, "select * from student"); } else { sprintf(sql, "select * from student where name='%s'", args[0]); } } else if (!strcmp(szCmd, "exit")) { break; } else { printf("Command not found "); Usage(); continue; } iRet = mysql_real_query(&conn, sql, strlen(sql)); if (iRet) { printf("sql:%s ", sql); printf("Failed:%s ", mysql_error(&conn)); continue; } printf("Excute sucess! "); //printf select result if (!strcmp(szCmd, "select")) { char fmt[] = "%4s %8s %8s %8s "; printf("============================= "); printf(fmt,"id", "name", "sex", "mobile"); printf("------------------------- "); MYSQL_RES *res = mysql_use_result(&conn); MYSQL_ROW row;//char ** while ((row = mysql_fetch_row(res)) != NULL) { printf(fmt, row[0], row[1], row[2], row[3]); } printf("============================= "); } mysql_close(&conn); } } int main() { TestMysql(); return 0; }