MySQL创建表与删除表

MySQL创建表与删除表

CREATE TABLE IF NOT EXISTS `表名称` (

`列名称1` 数据类型 关键字列表 默认值

...

)ENGINE=InnoDB DEFAULT CHARSET=utf8;

关键字和含义如下:

AUTO_INCREMENT 自动增加,只能用于整数类型列

NOT NULL 列不能为空

NULL 列可以为空

PRIMARY KEY 主键 表中主键的值是唯一的,可以用于标记和查找数据

UNSIGNED 无符号的数,只能修饰整数类型列

DEFAULT 默认值 用于指定列的默认值

UNIQUE 唯一 该列的要么为NULL要么就必须是唯一的,不可重复

ZEROFILL 0值填充,如果没有指定该列的值,则会填入0

以下为删除MySQL数据表的通用语法:

DROP TABLE `表名称` ;

主键的数据类型,它不能是可变长度的类型

例如:TEXT、BLOB

表名需要使用``符号来包围,千万不能使用单引号

实操代码:

MYSQL* mysql = new MYSQL();

//MYSQL mysql;//占用的是栈上的内存

MYSQL* pDB = mysql_init(mysql);

if (pDB == NULL) {

std::cout << "mysql_init failed!" << std::endl;

return -1;

}

pDB = mysql_real_connect(pDB, "localhost", "root", "FengPan12#$56", "mysql", 3306, NULL, 0);

std::cout << pDB << std::endl;

if (pDB) {

std::string sql = "CREATE DATABASE hello";

int ret = mysql_real_query(pDB, sql.c_str(), (unsigned long)sql.size());

if (ret != 0) {

std::cout << "mysql error:" << mysql_error(pDB) << std::endl;

}

MYSQL_RES* result = mysql_use_result(mysql);

if (result != NULL) {

show_result(result);

std::cout << "===================================================" << std::endl;

mysql_free_result(result);

}

//授予权限

sql = "GRANT ALL ON hello.* TO 'hello'@'localhost';";

ret = mysql_real_query(pDB, sql.c_str(), (unsigned long)sql.size());

if (ret != 0) {

std::cout << "mysql error:" << mysql_error(pDB) << std::endl;

return -1;

}

result = mysql_use_result(mysql);

if (result != NULL) {

show_result(result);

std::cout << "===================================================" << std::endl;

mysql_free_result(result);

}

sql = "USE hello;";

ret = mysql_real_query(pDB, sql.c_str(), (unsigned long)sql.size());

if (ret != 0) {

std::cout << "mysql error:" << mysql_error(pDB) << std::endl;

return -1;

}

result = mysql_use_result(mysql);

if (result != NULL) {

show_result(result);

std::cout << "===================================================" << std::endl;

mysql_free_result(result);

}

sql = "CREATE TABLE IF NOT EXISTS `hello` (`编号` NVARCHAR(16) PRIMARY KEY)ENGINE=InnoDB DEFAULT CHARSET=utf8;";

ret = mysql_real_query(pDB, sql.c_str(), (unsigned long)sql.size());

if (ret != 0) {

std::cout << "mysql error:" << mysql_error(pDB) << std::endl;

return -1;

}

sql = "DROP TABLE `hello`;";

ret = mysql_real_query(pDB, sql.c_str(), (unsigned long)sql.size());

if (ret != 0) {

std::cout << "mysql error:" << mysql_error(pDB) << std::endl;

return -1;

}

sql = "DROP DATABASE hello;";

ret = mysql_real_query(pDB, sql.c_str(), (unsigned long)sql.size());

if (ret != 0) {

std::cout << "mysql error:" << mysql_error(pDB) << std::endl;

return -1;

}

mysql_close(pDB);

}

delete mysql;

return 0;

posted @ 2022-10-21 21:43  Athenavi  阅读(80)  评论(0)    收藏  举报