天天看點

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");
}      

轉載于:https://www.cnblogs.com/qingtian224/p/9849896.html