步骤

  • 安装MySQL数据库
  • 项目属性页->C/C++->常规->附加包含目录:xxx\mysql Server 5.6\include
  • 项目属性页->链接器->常规->附加库目录:xxx\MySQL Server 5.6\lib
  • 项目属性页->链接器->输入->附加依赖项:
  • libmysql.lib 将libmysql.dll拷贝到项目中
  • 引入头文件:#include<Windows.h> #include <mysql.h>
  • 另外需要注意的是 Mysql版本是32位还是64位,如果是64位请将VS2013设置为 x64,具体设置为:右键项目->属性->在右上角有 “配置管理器” ->点击 修改为 x64

命名行操作数据库

  • Mysql命令大全
数据库部分

   1)开启 MYSQL数据库,在CMD下,输入: net start mysql    启动数据库

   2   再将当前路径转到:C:\Program Files (x86)\MySQL\MySQL Server 5.5\bin  下,输入   mysql -uroot  -p     然后让输入密码,这时输入当时安装mysql时的root密码。这时就进入了mysql下。

   3:建立一个数据库:   输入 create  database  message;     则生成一个数据库message,接下来我们就要用VS2013中的程序连接这个message数据库。
  • 现在操作始终有问题:
  • centos系统mysql附加数据库_mysql

  • 连接mysql可以成功
  • centos系统mysql附加数据库_数据库_02

C++连接MySql

  • 操作成功的示例
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql.h> 
#include <iostream>
using namespace std;

//#pragma comment(lib,"libmysql.lib")

int main()
{
    const char user[] = "root";         //username
    const char pswd[] = "ranjiewen";         //password
    const char host[] = "localhost";    //or"127.0.0.1"
    const char table[] = "world";        //database   //有相应的数据库
    unsigned int port = 3306;           //server port        
    MYSQL myCont;
    MYSQL_RES *result;
    MYSQL_ROW sql_row;
    MYSQL_FIELD *fd;
    char column[32][32];
    int res;
    mysql_init(&myCont);
    //auto ret = mysql_real_connect(&myCont, host, user, pswd, table, port, NULL, 0);
    if (mysql_real_connect(&myCont, host, user, pswd, table, port, NULL, 0))
    {
        cout << "connect succeed!" << endl;
        mysql_query(&myCont, "SET NAMES GBK"); //设置编码格式,否则在cmd下无法显示中文
        res = mysql_query(&myCont, "select * from city");//查询    //database下有相应的表才能成功
        if (!res)
        {
            result = mysql_store_result(&myCont);//保存查询到的数据到result
            if (result)
            {
                int i, j;
                cout << "number of result: " << (unsigned long)mysql_num_rows(result) << endl;
                for (i = 0; fd = mysql_fetch_field(result); i++)//获取列名
                {
                    strcpy(column[i], fd->name);
                }
                j = mysql_num_fields(result);
                for (i = 0; i < j; i++)
                {
                    printf("%s\t", column[i]);
                }
                printf("\n");
                while (sql_row = mysql_fetch_row(result))//获取具体的数据
                {
                    for (i = 0; i < j; i++)
                    {
                        printf("%s\n", sql_row[i]);
                    }
                    printf("\n");
                }
            }
        }
        else
        {
            cout << "query sql failed!" << endl;
        }
    }
    else
    {
        cout << "connect failed!" << endl;
    }
    if (result != NULL) mysql_free_result(result);//释放结果资源
    mysql_close(&myCont);//断开连接
    return 0;
}
  • 创建数据库失败的案例,待解决
#include<iostream>
#include<Windows.h>
#include <mysql.h>
#include<string>


using namespace std;


int main()
{

    //必备的一个数据结构
    MYSQL mydata;

    //初始化数据库
    if (0 == mysql_library_init(0, NULL, NULL)) {
        cout << "mysql_library_init() succeed" << endl;
    }
    else {
        cout << "mysql_library_init() failed" << endl;
        return -1;
    }

    //初始化数据结构
    if (NULL != mysql_init(&mydata)) {
        cout << "mysql_init() succeed" << endl;
    }
    else {
        cout << "mysql_init() failed" << endl;
        return -1;
    }

    //在连接数据库之前,设置额外的连接选项
    //可以设置的选项很多,这里设置字符集,否则无法处理中文
    if (0 == mysql_options(&mydata, MYSQL_SET_CHARSET_NAME, "gbk")) {
        cout << "mysql_options() succeed" << endl;
    }
    else {
        cout << "mysql_options() failed" << endl;
        return -1;
    }

    //连接数据库
    if (NULL
        != mysql_real_connect(&mydata, "127.0.0.1", "root", "ranjiewen", "world",
        3306, NULL, 0))
        //这里的地址,用户名,密码,端口可以根据自己本地的情况更改
    {
        cout << "mysql_real_connect() succeed" << endl;
    }
    else {
        cout << "mysql_real_connect() failed" << endl;
        return -1;
    }

    //sql字符串
    string sqlstr;

    //创建一个表
    sqlstr = "CREATE TABLE IF NOT EXISTS `new_paper` (";
    sqlstr += " `NewID` int(11) NOT NULL AUTO_INCREMENT,";

    sqlstr += " `NewCaption` varchar(40) NOT NULL,";

    sqlstr += " `NewContent` text,";

    sqlstr += " `NewTime` datetime DEFAULT NULL,";

    sqlstr += " PRIMARY KEY(`NewID`)";

    sqlstr += " ) ENGINE = InnoDB DEFAULT CHARSET = utf8";


    if (0 == mysql_query(&mydata, sqlstr.c_str())) {
        cout << "mysql_query() create table succeed" << endl;
    }
    else {
        cout << "mysql_query() create table failed" << endl;
        mysql_close(&mydata);
        return -1;
    }


    //向表中插入数据
    for (int i = 0; i < 100; i++)
    {
        sqlstr =
            "INSERT INTO `test`.`new_paper` (`NewID`, `NewCaption`, `NewContent`, `NewTime`) ";
        //sqlstr += "VALUES (default, '组织者', '方提出更换存放骨灰存放', '2015-09-01 14:29:51');";
        sqlstr += "VALUES (default, 'zhuzuzhe', 'fangtichu', '2015-09-01 14:29:51');";   

        if (0 == mysql_query(&mydata, sqlstr.c_str())) {                      //这里有问题,失败待解决!!!!!!!!!!!!
            cout << "mysql_query() insert data succeed" << endl;
        }
        else {
            cout << "mysql_query() insert data failed" << endl;
            mysql_close(&mydata);
            return -1;
        }
    }

    //显示刚才插入的数据
    sqlstr = "SELECT `NewID`,`NewCaption`,`NewContent`,`NewTime` FROM `test`.`new_paper`";
    MYSQL_RES *result = NULL;
    if (0 == mysql_query(&mydata, sqlstr.c_str())) {
        cout << "mysql_query() select data succeed" << endl;

        //一次性取得数据集
        result = mysql_store_result(&mydata);
        //取得并打印行数
        int rowcount = mysql_num_rows(result);
        cout << "row count: " << rowcount << endl;

        //取得并打印各字段的名称
        unsigned int fieldcount = mysql_num_fields(result); MYSQL_FIELD *field = NULL; for (unsigned int i = 0; i < fieldcount; i++) {
            field = mysql_fetch_field_direct(result, i);
            cout << field->name << "\t\t";
        }
        cout << endl;

        //打印各行
        MYSQL_ROW row = NULL;
        row = mysql_fetch_row(result);
        while (NULL != row) {
            for (int i = 0; i < fieldcount; i++) {
                cout << row[i] << "\t\t";
            }
            cout << endl;
            row = mysql_fetch_row(result);
        }

    }
    else {
        cout << "mysql_query() select data failed" << endl;
        mysql_close(&mydata);
        return -1;
    }


    //删除刚才建的表
    sqlstr = "DROP TABLE `test`.`new_paper`";
    if (0 == mysql_query(&mydata, sqlstr.c_str())) {
        cout << "mysql_query() drop table succeed" << endl;
    }
    else {
        cout << "mysql_query() drop table failed" << endl;
        mysql_close(&mydata);
        return -1;
    }
    mysql_free_result(result);
    mysql_close(&mydata);
    mysql_server_end();

    system("pause");
    return 0;
}

C++操作MySql成功,増删查

#pragma once
#include <stdio.h>
#include <string>
//#include <afxsock.h>
#include "mysql.h"
using   namespace   std;
class VspdCToMySQL
{
public:

    //变量
    MYSQL mysql;

    /*
    构造函数和稀构函数
    */
    VspdCToMySQL();
    ~VspdCToMySQL();

    /*
    主要的功能:
    初始化数据库
    连接数据库
    设置字符集

    入口参数:
    host :MYSQL服务器IP
    port:数据库端口
    Db:数据库名称
    user:数据库用户
    passwd:数据库用户的密码
    charset:希望使用的字符集
    Msg:返回的消息,包括错误消息

    出口参数:
    int :0表示成功;1表示失败
    */
    int ConnMySQL(char *host, char * port, char * Db, char * user, char* passwd, char * charset, char * Msg);

    /*
    主要的功能:
    查询数据

    入口参数:
    SQL:查询的SQL语句
    Cnum:查询的列数
    Msg:返回的消息,包括错误消息

    出口参数:
    string 准备放置返回的数据,多条记录则用0x06隔开,多个栏位用0x05隔开
    如果 返回的长度= 0,责表示舞结果
    */
    string SelectData(char * SQL, int Cnum, char * Msg);

    /*
    主要功能:
    插入数据

    入口参数
    SQL:查询的SQL语句
    Msg:返回的消息,包括错误消息

    出口参数:
    int :0表示成功;1表示失败
    */
    int InsertData(char * SQL, char * Msg);

    /*
    主要功能:
    不存在相同记录,插入数据
    存在相同记录,更新数据

    入口参数
    SQL:查询的SQL语句
    Msg:返回的消息,包括错误消息

    出口参数:
    int :0表示成功;1表示失败
    */
    int ReplaceData(char * SQL, char * Msg);

    /*
    主要功能:
    修改数据

    入口参数
    SQL:查询的SQL语句
    Msg:返回的消息,包括错误消息

    出口参数:
    int :0表示成功;1表示失败
    */
    int UpdateData(char * SQL, char * Msg);

    /*
    主要功能:
    调用数据库存储过程
    */

    int CallProcedure(char * SQL, char * Msg);

    /*
    主要功能:
    删除数据

    入口参数
    SQL:查询的SQL语句
    Msg:返回的消息,包括错误消息

    出口参数:
    int :0表示成功;1表示失败
    */
    int DeleteData(char * SQL, char * Msg);

    /*
    主要功能:
    关闭数据库连接
    */
    void CloseMySQLConn();

};


//#include "stdafx.h"
#include "DBMySQL.h"

VspdCToMySQL::VspdCToMySQL()
{
}

VspdCToMySQL::~VspdCToMySQL()
{
}

//初始化数据
int VspdCToMySQL::ConnMySQL(char *host, char * port, char * Db, char * user, char* passwd, char * charset, char * Msg)
{
    if (mysql_init(&mysql) == NULL)
    {
        Msg = "inital mysql handle error";
        return 1;
    }

    if (mysql_real_connect(&mysql, host, user, passwd, Db, 0, NULL, 0) == NULL)
    {
        Msg = "Failed to connect to database: Error";
        return 1;
    }

    if (mysql_set_character_set(&mysql, charset) != 0)
    {
        Msg = "mysql_set_character_set Error";
        return 1;
    }
    return 0;
}

//查询数据
string VspdCToMySQL::SelectData(char * SQL, int Cnum, char * Msg)
{
    MYSQL_ROW m_row;
    MYSQL_RES *m_res;
    char sql[2048];
    sprintf(sql, SQL);
    int rnum = 0;
    char rg = 0x06;//行隔开
    //char rg='\r';
    char cg = 0x05;//字段隔开
    if (mysql_query(&mysql, sql) != 0)
    {
        Msg = "select ps_info Error";
        return "";
    }
    m_res = mysql_store_result(&mysql);

    if (m_res == NULL)
    {
        Msg = "select username Error";
        return "";
    }
    string str("");
    while (m_row = mysql_fetch_row(m_res))
    {
        for (int i = 0; i < Cnum; i++)
        {
            str += m_row[i];
            str += cg;
        }
        str += rg;
        rnum++;
    }

    mysql_free_result(m_res);

    return str;
}

//插入数据
int VspdCToMySQL::InsertData(char * SQL, char * Msg)
{
    char sql[2048];
    sprintf(sql, SQL);
    if (mysql_query(&mysql, sql) != 0)
    {
        Msg = "Insert Data Error";
        return 1;
    }
    return 0;
}

//更换数据
int VspdCToMySQL::ReplaceData(char * SQL, char * Msg)
{
    char sql[2048];
    sprintf(sql, SQL);
    if (mysql_query(&mysql, sql) != 0)
    {
        Msg = "Replace Data Error";
        return 1;
    }
    return 0;
}

//更新数据
int VspdCToMySQL::UpdateData(char * SQL, char * Msg)
{
    char sql[2048];
    sprintf(sql, SQL);
    if (mysql_query(&mysql, sql) != 0)
    {
        Msg = "Update Data Error";
        return 1;
    }
    return 0;
}

//删除数据
int VspdCToMySQL::DeleteData(char * SQL, char * Msg)
{
    char sql[2048];
    sprintf(sql, SQL);
    if (mysql_query(&mysql, sql) != 0)
    {
        Msg = "Delete Data error";
        return 1;
    }
    return 0;
}

//调用数据库存储过程
int VspdCToMySQL::CallProcedure(char * SQL, char * Msg)
{
    char sql[2048];
    sprintf(sql, SQL);
    if (mysql_query(&mysql, sql) != 0)
    {
        Msg = "Call Procedure error";
        return 1;
    }
    return 0;
}
//关闭数据库连接
void VspdCToMySQL::CloseMySQLConn()
{
    mysql_close(&mysql);
    printf("断开数据库\n");
}



#include "DBMySQL.h"
int main(int argc, char* argv[])   //修改数据库名称,在本地数据库服务器已经存在了
{
    char* host = "127.0.0.1";
    char* user = "root";
    char* port = "3306";
    char* passwd = "ranjiewen";
    char* dbname = "world";
    char* charset = "GBK";//支持中文
    char* Msg = "";//消息变量
    //初始化
    VspdCToMySQL * vspdctomysql = new VspdCToMySQL;
    if (vspdctomysql->ConnMySQL(host, port, dbname, user, passwd, charset, Msg) == 0)
        printf("连接成功/r/n");
    else
        printf(Msg);

    //查询
    char * SQL = "SELECT ids,username,passwd,address FROM vcaccesstest";
    string str = vspdctomysql->SelectData(SQL, 4, Msg);
    if (str.length() > 0)
    {
        printf("查询成功/r/n");
        printf(str.data());
        printf("/r/n");
    }
    else
    {
        printf(Msg);
    }
    //插入
    SQL = "insert into vcaccesstest(ids,username,passwd,address) values(4,'我的','123210','测试地址')";
    if (vspdctomysql->InsertData(SQL, Msg) == 0)
        printf("插入成功/r/n");
    //更新
    SQL = "update vcaccesstest set username = '修改了',passwd='2345' where ids = 3 ";
    if (vspdctomysql->UpdateData(SQL, Msg) == 0)
        printf("更新成功/r/n");
    //删除
    SQL = "delete from vcaccesstest where ids = 3 ";
    if (vspdctomysql->DeleteData(SQL, Msg) == 0)
        printf("删除成功/r/n");

    vspdctomysql->CloseMySQLConn();

    return 0;
}
  • 接下来主要是做SQL基本语法进行系统学习

操作workbench

  • 先不能连接locahost,后面可了连接成功。
  • 基本的操作,可以用,查看什么应用程序操作了什么数据库
  • centos系统mysql附加数据库_c/c++_03