C++訪問MYSQL數據庫

#include <Windows.h>
#include <mysql.h>
#include <string>
#include <iostream>
#include<iomanip>

// SDK   software development kit
//簡易版本的服務器
using namespace std;
//#pragma comment(lib,"D:\\Program Files\\MySQL\\MySQL Server 5.6\\lib\\libmysql.lib") 
int main()
{
	const char user[] = "root";
	const char pswd[] = "12345678";
	const char host[] = "localhost";
	const char mysql[] = "myfirstsql";
	unsigned int port = 3306;
	MYSQL myCont;//句柄 數據庫變量
	MYSQL_RES *result;
	MYSQL_ROW sql_row;
	int res;
	mysql_init(&myCont);
	if (mysql_real_connect(&myCont, host, user, pswd, mysql, port, NULL, 0))
	{
		mysql_query(&myCont, "SET NAMES GBK"); //設置編碼格式
		res = mysql_query(&myCont, "select * from mytable");//查詢、執行命令 返回0爲成功
	//    res = mysql_query(&myCont, "insert into mytable(id,name,sex) values(NULL,'hang','男')");//插入
		//res = mysql_query(&myCont, "delete from students where name = Li'");//刪除
		//res = mysql_query(&myCont, "update  students set tel = '1423636' where name = 'He'");//更新
		if (!res)
		{
			result = mysql_store_result(&myCont);
			if (result)
			{
				cout <<left<<setw(3)<< "id"<<setw(8) << "name" << setw(2)<<"sex" << endl;
				while (sql_row = mysql_fetch_row(result))//獲取具體的數據
				{
						cout << left <<setw(2)<<sql_row[0] << " ";
						cout << left <<setw(8) << sql_row[1] << " ";
						cout << left <<setw(2) << sql_row[2] << " ";
				}
			}
		}
		else
		{
			cout << "query sql failed!" << endl;
		}
	}
	else
	{
		cout << "connect failed!" << endl;
	}
	if (result != NULL)
		mysql_free_result(result);
	mysql_close(&myCont);
	system("pause");
	return 0;

}




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