mysql-connetor-c 自动创建数据库、数据库表的命令

1.首先连接MySQL默认的数据库mysql

// 参数说明:
// strIP: MySQL数据库的IP地址
// nPort: MySQL数据库的端口号
// strDBName: 要连接的数据库(mysql)
// strUserName: 连接MySQL数据库的用户名
// strPassword: 连接MySQL数据库的密码
bool Connect( const std::string& strIP, int nPort, const std::string& strDBName, 
    const std::string& strUserName, const std::string& strPassword )
{
    if ( nullptr == (m_hMysql = mysql_init(nullptr)) )
    {
        printf("mysql_init() failed!");
        return false;
    }

    if( nullptr == mysql_real_connect( m_hMysql, strIP.c_str(), strUserName.c_str(), 
        strPassword.c_str(), strDBName.c_str(), nPort, nullptr, 0) )
    {
        printf("mysql_real_connect() failed!");
        return false;
    }
return true;
}

调用示例:

    bool ret = Connect("127.0.0.1", 3306, "mysql", "test", "test"); // 注意:"mysql"是MySQL自己的数据库
    if (!ret)
    {
        printf("connect mysql failed\n");  
    }

 

2.创建自己的数据库test

bool CreateDatabase(const std::string& strSQL)
{
    if (nullptr == m_hMysql || strSQL.empty())
    {
        return false;
    }

    if (MYSQL_OK != mysql_query(m_hMysql, strSQL.c_str()))
    {
        printf("mysql_query failed, sql:%s\n", strSQL.c_str());
        return false;
    }
    return true;
}

调用示例:

bool ret = CreateDatabase("CREATE DATABASE IF NOT EXISTS test DEFAULT CHARSET utf8 COLLATE utf8_general_ci");
if (!ret)
{
  printf("CreateDatabase failed\n");  
}

 

3.切换到自己的数据库test

bool ChangeDatabase(const std::string& strSQL)
{
    if (nullptr == m_hMysql || strSQL.empty())
    {
        return false;
    }

    if (MYSQL_OK != mysql_query(m_hMysql, strSQL.c_str()))
    {
        printf("mysql_query failed, sql:%s\n", strSQL.c_str());
        return false;
    }
    return true;
}

调用示例:

bool ret = ChangeDatabase("USE test");
if (!ret)
{
  printf("ChangeDatabase failed\n");  
}

 

4.创建数据库表t_data

bool CreateTable(const std::string& strSQL)
{
    if (nullptr == m_hMysql || strSQL.empty())
    {
        return false;
    }

    if (MYSQL_OK != mysql_query(m_hMysql, strSQL.c_str()))
    {
        printf("mysql_query failed, sql:%s\n", strSQL.c_str());
        return false;
    }
    return true;
}

调用示例:

bool ret = CreateTable("CREATE TABLE IF NOT EXISTS t_data ( Id BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '自增ID', DATA VARCHAR(256) NOT NULL COMMENT '数据位置', PRIMARY KEY (Id) ) ENGINE=INNODB DEFAULT CHARSET=utf8");
if (!ret)
{
    printf("create table failed\n");
}

 

posted @ 2018-10-25 15:04  晴天224  阅读(1437)  评论(0编辑  收藏  举报