c++简单实现对mysql数据库操作

1、连接数据库

#include <mysql.h> 
#include <iostream>
#include<string>
#include<vector>
using namespace std;

const char user[] = "root";         //username
const char pswd[] = "*********";         //password
const char host[] = "localhost";    //or"127.0.0.1"
const char table[] = "industry";        //database
unsigned int port = 3306;
MYSQL mysql;

bool connection() {
    mysql_init(&mysql);
    if (mysql_real_connect(&mysql, host, user, pswd, table, port, NULL, 0)){
        cout << "connect success!" << endl;
        return true;
    }
    else{
        cout << "connect failed!" << endl;
        return false;
    }
}

2、向表中增加记录

       char que[200];
	sprintf_s(que, "insert into table2 values(%s,%s)", "(3, 4)", "(6, 7)");
	if (mysql_query(&mysql, que) == 0) {
		cout << "insert success." << endl;
	}

3、查找表中记录

const char* query = "select * from new_table";
if (mysql_query(&mysql, query) == 0) {
		cout << "query success." << endl;
		result2 = mysql_store_result(&mysql);
		while ((row = mysql_fetch_row(result2)) != NULL) {
			cout << row[0] << "," << row[1] << "  " << row[2] << "," << row[3] << endl;
		}
		mysql_free_result(result2);
	}

猜你喜欢

转载自www.cnblogs.com/gaoyixue/p/10452779.html