One - One Code All

Blog Content

C++ 连接MySql

C/C++   2014-05-31 14:42:37

mydb.h

/**
 * file MyDb.h
 */

#ifndef DB_MYDB_H
#define DB_MYDB_H

#include 
#include "mysql.h"

using namespace std;

class MyDb {

public:
    MyDb();
    ~MyDb();

    /**
     * 连接mysql
     *
     * @param host
     * @param user
     * @param pwd
     * @param db_name
     * @param port
     * @return
     */
    bool initDB(string host, string user,string pwd,string db_name, int port);

    /**
     * 执行sql语句
     *
     * @param sql
     * @return
     */
    bool exeSQL(string sql);

private:
    /**
     * 连接mysql句柄指针
     */
    MYSQL *mysql;

    /**
     * 指向查询结果的指针
     */
    MYSQL_RES *result;

    /**
     * 按行返回的查询信息
     */
    MYSQL_ROW row;
};
#endif //DB_MYDB_H


cpp 文件

/**
 * file MyDb.cpp
 */

#include 
#include 
#include "MyDb.h"

using namespace std;

/**
 * 初始化数据库连接变量
 */
MyDb::MyDb()
{
    mysql = mysql_init(NULL);

    if(!mysql) {
        cout<<"Error:"<


main文件

#include 
#include "MyDb.h"

int main() {
    // std::cout << "Hello, World!" << std::endl;

    MyDb db;

    string host = "127.0.0.1";
    string user = "root";
    string passwd = "password";
    string dbName = "test";
    int port = 3307;

    cout<<"start\n";

    //连接数据库
    bool conn = db.initDB(host, user, passwd, dbName, port);

    if (!conn) {
        cout<<"connect fails\n";
    }

    cout<<"ok" <



上一篇:C/C++中main函数接受外部参数的写法,以及如何传参数
下一篇:airflow控制task并发度

The minute you think of giving up, think of the reason why you held on so long.