创建表:
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
删除表:
DROP TABLE `表名称` ;
主键的数据类型,它不能是可变长度的类型,比如TEXT、BLOB,表名需要使用``符号来包围,千万不能使用单引号
代码范例:
MYSQL* mysql = new 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", "root", "mysql", 3306, NULL, 0);
if (pDB) {
std::string sql = "CREATE DATABASE hello"; // SQL语句可替换为自己实际需要执行的语句
// 创建数据库
int ret = mysql_real_query(mysql, sql.c_str(), (unsigned long)sql.size());
if (ret != 0) {
std::cout << "mysql error: " << mysql_error(pDB) << std::endl;
return -1;
}
// 授予权限
sql = "GRANT ALL ON hello.* TO 'hello'@'localhost';";
ret = mysql_real_query(mysql, sql.c_str(), (unsigned long)sql.size());
if (ret != 0) {
std::cout << "mysql error: " << mysql_error(pDB) << std::endl;
return -1;
}
// 指定数据库
sql = "USE hello";
ret = mysql_real_query(mysql, sql.c_str(), (unsigned long)sql.size());
if (ret != 0) {
std::cout << "mysql error: " << mysql_error(pDB) << std::endl;
return -1;
}
// 创建表
sql = "CREATE TABLE IF NOT EXISTS `hello` (`id` NVARCHAR(16) PRIMARY KEY)ENGINE=InnoDB DEFAULT CHARSET=utf8;";
ret = mysql_real_query(mysql, 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(mysql, 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(mysql, sql.c_str(), (unsigned long)sql.size());
if (ret != 0) {
std::cout << "mysql error: " << mysql_error(pDB) << std::endl;
return -1;
}
mysql_close(pDB);
std::cout << pDB << std::endl;
delete mysql;
}
mysql = nullptr;
return 0;