c++ 在eclipse下連接mysql數據庫

將libmysql.dll文件拷貝到C:\Windows\System32文件夾下面,不然程序運行起來會找不到libmysql.dll,eclipse下面運行之後就會出現什麼也沒發生

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

const char *host = "localhost";
const char *user = "root";
const char *passwd = "smartsys";
const char *db = "swadmin";
unsigned int port = 3306;

int main() {
	MYSQL m_mysql;
	//初始化數據庫
	if (mysql_library_init(0, NULL, NULL) == 0) {
		cout << "mysql類庫初始化成功" << endl;
	} else {
		cout << "mysql類庫初始化失敗" << endl;
		return -1;
	}

	mysql_init(&m_mysql);
	mysql_options(&m_mysql, MYSQL_SET_CHARSET_NAME, "gbk");
	//連接數據庫

	if (mysql_real_connect(&m_mysql, host, user, passwd, db, port, NULL,
			0)!=NULL) {
		cout << "數據庫連接成功" << endl;
	} else {
		cout << "數據庫連接失敗" << endl;
		return -1;
	}
	string sql_str = "SELECT * FROM MENU";
	MYSQL_RES *result = NULL;
	if (mysql_query(&m_mysql, sql_str.c_str()) == 0) {
		cout << "數據查詢成功" << endl;
		result = mysql_store_result(&m_mysql);
		int rowcount = mysql_num_rows(result);
		cout << "查詢到的記錄數: " << 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 (row != NULL) {
			for (unsigned int i = 0; i < fieldcount; i++) {
				cout << row[i] << "\t\t";
			}
			cout << endl;
			row = mysql_fetch_row(result);
		}
	} else {
		cout << "查詢數據失敗" << endl;
		mysql_close(&m_mysql);
		return -1;
	}
	mysql_free_result(result);
	mysql_close(&m_mysql);
	mysql_server_end();
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章