1. 程式人生 > >c++簡單實現對mysql數據庫操作

c++簡單實現對mysql數據庫操作

cti ace failed select localhost username iostream %s fetch

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

c++簡單實現對mysql數據庫操作