步驟
-
安裝MySQL數據庫
-
項目屬性頁->C/C++->常規->附加包含目錄:xxx\mysql Server 5.6\include
-
項目屬性頁->鏈接器->常規->附加庫目錄:xxx\MySQL Server 5.6\lib
-
項目屬性頁->鏈接器->輸入->附加依賴項:
-
libmysql.lib 將libmysql.dll拷貝到項目中
-
引入頭文件:#include<Windows.h> #include <mysql.h>
-
另外需要注意的是 Mysql版本是32位還是64位,如果是64位請將VS2013設置為 x64,具體設置為:右鍵項目->屬性->在右上角有 “配置管理器” ->點擊 修改為 x64
命名行操作數據庫
數據庫部分
1)開啟 MYSQL數據庫,在CMD下,輸入: net start mysql 啟動數據庫
2 再將當前路徑轉到:C:\Program Files (x86)\MySQL\MySQL Server 5.5\bin 下,輸入 mysql -uroot -p 然后讓輸入密碼,這時輸入當時安裝mysql時的root密碼。這時就進入了mysql下。
3:建立一個數據庫: 輸入 create database message; 則生成一個數據庫message,接下來我們就要用VS2013中的程序連接這個message數據庫。
-
現在操作始終有問題:
-
連接mysql可以成功
C++連接MySql
- 操作成功的示例
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <mysql.h>
#include <iostream>
using namespace std;
//#pragma comment(lib,"libmysql.lib")
int main()
{
const char user[] = "root"; //username
const char pswd[] = "ranjiewen"; //password
const char host[] = "localhost"; //or"127.0.0.1"
const char table[] = "world"; //database //有相應的數據庫
unsigned int port = 3306; //server port
MYSQL myCont;
MYSQL_RES *result;
MYSQL_ROW sql_row;
MYSQL_FIELD *fd;
char column[32][32];
int res;
mysql_init(&myCont);
//auto ret = mysql_real_connect(&myCont, host, user, pswd, table, port, NULL, 0);
if (mysql_real_connect(&myCont, host, user, pswd, table, port, NULL, 0))
{
cout << "connect succeed!" << endl;
mysql_query(&myCont, "SET NAMES GBK"); //設置編碼格式,否則在cmd下無法顯示中文
res = mysql_query(&myCont, "select * from city");//查詢 //database下有相應的表才能成功
if (!res)
{
result = mysql_store_result(&myCont);//保存查詢到的數據到result
if (result)
{
int i, j;
cout << "number of result: " << (unsigned long)mysql_num_rows(result) << endl;
for (i = 0; fd = mysql_fetch_field(result); i++)//獲取列名
{
strcpy(column[i], fd->name);
}
j = mysql_num_fields(result);
for (i = 0; i < j; i++)
{
printf("%s\t", column[i]);
}
printf("\n");
while (sql_row = mysql_fetch_row(result))//獲取具體的數據
{
for (i = 0; i < j; i++)
{
printf("%s\n", sql_row[i]);
}
printf("\n");
}
}
}
else
{
cout << "query sql failed!" << endl;
}
}
else
{
cout << "connect failed!" << endl;
}
if (result != NULL) mysql_free_result(result);//釋放結果資源
mysql_close(&myCont);//斷開連接
return 0;
}
- 創建數據庫失敗的案例,待解決
#include<iostream>
#include<Windows.h>
#include <mysql.h>
#include<string>
using namespace std;
int main()
{
//必備的一個數據結構
MYSQL mydata;
//初始化數據庫
if (0 == mysql_library_init(0, NULL, NULL)) {
cout << "mysql_library_init() succeed" << endl;
}
else {
cout << "mysql_library_init() failed" << endl;
return -1;
}
//初始化數據結構
if (NULL != mysql_init(&mydata)) {
cout << "mysql_init() succeed" << endl;
}
else {
cout << "mysql_init() failed" << endl;
return -1;
}
//在連接數據庫之前,設置額外的連接選項
//可以設置的選項很多,這里設置字符集,否則無法處理中文
if (0 == mysql_options(&mydata, MYSQL_SET_CHARSET_NAME, "gbk")) {
cout << "mysql_options() succeed" << endl;
}
else {
cout << "mysql_options() failed" << endl;
return -1;
}
//連接數據庫
if (NULL
!= mysql_real_connect(&mydata, "127.0.0.1", "root", "ranjiewen", "world",
3306, NULL, 0))
//這里的地址,用戶名,密碼,端口可以根據自己本地的情況更改
{
cout << "mysql_real_connect() succeed" << endl;
}
else {
cout << "mysql_real_connect() failed" << endl;
return -1;
}
//sql字符串
string sqlstr;
//創建一個表
sqlstr = "CREATE TABLE IF NOT EXISTS `new_paper` (";
sqlstr += " `NewID` int(11) NOT NULL AUTO_INCREMENT,";
sqlstr += " `NewCaption` varchar(40) NOT NULL,";
sqlstr += " `NewContent` text,";
sqlstr += " `NewTime` datetime DEFAULT NULL,";
sqlstr += " PRIMARY KEY(`NewID`)";
sqlstr += " ) ENGINE = InnoDB DEFAULT CHARSET = utf8";
if (0 == mysql_query(&mydata, sqlstr.c_str())) {
cout << "mysql_query() create table succeed" << endl;
}
else {
cout << "mysql_query() create table failed" << endl;
mysql_close(&mydata);
return -1;
}
//向表中插入數據
for (int i = 0; i < 100; i++)
{
sqlstr =
"INSERT INTO `test`.`new_paper` (`NewID`, `NewCaption`, `NewContent`, `NewTime`) ";
//sqlstr += "VALUES (default, '組織者', '方提出更換存放骨灰存放', '2015-09-01 14:29:51');";
sqlstr += "VALUES (default, 'zhuzuzhe', 'fangtichu', '2015-09-01 14:29:51');";
if (0 == mysql_query(&mydata, sqlstr.c_str())) { //這里有問題,失敗待解決!!!!!!!!!!!!
cout << "mysql_query() insert data succeed" << endl;
}
else {
cout << "mysql_query() insert data failed" << endl;
mysql_close(&mydata);
return -1;
}
}
//顯示剛才插入的數據
sqlstr = "SELECT `NewID`,`NewCaption`,`NewContent`,`NewTime` FROM `test`.`new_paper`";
MYSQL_RES *result = NULL;
if (0 == mysql_query(&mydata, sqlstr.c_str())) {
cout << "mysql_query() select data succeed" << endl;
//一次性取得數據集
result = mysql_store_result(&mydata);
//取得並打印行數
int rowcount = mysql_num_rows(result);
cout << "row count: " << 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 (NULL != row) {
for (int i = 0; i < fieldcount; i++) {
cout << row[i] << "\t\t";
}
cout << endl;
row = mysql_fetch_row(result);
}
}
else {
cout << "mysql_query() select data failed" << endl;
mysql_close(&mydata);
return -1;
}
//刪除剛才建的表
sqlstr = "DROP TABLE `test`.`new_paper`";
if (0 == mysql_query(&mydata, sqlstr.c_str())) {
cout << "mysql_query() drop table succeed" << endl;
}
else {
cout << "mysql_query() drop table failed" << endl;
mysql_close(&mydata);
return -1;
}
mysql_free_result(result);
mysql_close(&mydata);
mysql_server_end();
system("pause");
return 0;
}
C++操作MySql成功,増刪查
#pragma once
#include <stdio.h>
#include <string>
//#include <afxsock.h>
#include "mysql.h"
using namespace std;
class VspdCToMySQL
{
public:
//變量
MYSQL mysql;
/*
構造函數和稀構函數
*/
VspdCToMySQL();
~VspdCToMySQL();
/*
主要的功能:
初始化數據庫
連接數據庫
設置字符集
入口參數:
host :MYSQL服務器IP
port:數據庫端口
Db:數據庫名稱
user:數據庫用戶
passwd:數據庫用戶的密碼
charset:希望使用的字符集
Msg:返回的消息,包括錯誤消息
出口參數:
int :0表示成功;1表示失敗
*/
int ConnMySQL(char *host, char * port, char * Db, char * user, char* passwd, char * charset, char * Msg);
/*
主要的功能:
查詢數據
入口參數:
SQL:查詢的SQL語句
Cnum:查詢的列數
Msg:返回的消息,包括錯誤消息
出口參數:
string 准備放置返回的數據,多條記錄則用0x06隔開,多個欄位用0x05隔開
如果 返回的長度= 0,責表示舞結果
*/
string SelectData(char * SQL, int Cnum, char * Msg);
/*
主要功能:
插入數據
入口參數
SQL:查詢的SQL語句
Msg:返回的消息,包括錯誤消息
出口參數:
int :0表示成功;1表示失敗
*/
int InsertData(char * SQL, char * Msg);
/*
主要功能:
不存在相同記錄,插入數據
存在相同記錄,更新數據
入口參數
SQL:查詢的SQL語句
Msg:返回的消息,包括錯誤消息
出口參數:
int :0表示成功;1表示失敗
*/
int ReplaceData(char * SQL, char * Msg);
/*
主要功能:
修改數據
入口參數
SQL:查詢的SQL語句
Msg:返回的消息,包括錯誤消息
出口參數:
int :0表示成功;1表示失敗
*/
int UpdateData(char * SQL, char * Msg);
/*
主要功能:
調用數據庫存儲過程
*/
int CallProcedure(char * SQL, char * Msg);
/*
主要功能:
刪除數據
入口參數
SQL:查詢的SQL語句
Msg:返回的消息,包括錯誤消息
出口參數:
int :0表示成功;1表示失敗
*/
int DeleteData(char * SQL, char * Msg);
/*
主要功能:
關閉數據庫連接
*/
void CloseMySQLConn();
};
//#include "stdafx.h"
#include "DBMySQL.h"
VspdCToMySQL::VspdCToMySQL()
{
}
VspdCToMySQL::~VspdCToMySQL()
{
}
//初始化數據
int VspdCToMySQL::ConnMySQL(char *host, char * port, char * Db, char * user, char* passwd, char * charset, char * Msg)
{
if (mysql_init(&mysql) == NULL)
{
Msg = "inital mysql handle error";
return 1;
}
if (mysql_real_connect(&mysql, host, user, passwd, Db, 0, NULL, 0) == NULL)
{
Msg = "Failed to connect to database: Error";
return 1;
}
if (mysql_set_character_set(&mysql, charset) != 0)
{
Msg = "mysql_set_character_set Error";
return 1;
}
return 0;
}
//查詢數據
string VspdCToMySQL::SelectData(char * SQL, int Cnum, char * Msg)
{
MYSQL_ROW m_row;
MYSQL_RES *m_res;
char sql[2048];
sprintf(sql, SQL);
int rnum = 0;
char rg = 0x06;//行隔開
//char rg='\r';
char cg = 0x05;//字段隔開
if (mysql_query(&mysql, sql) != 0)
{
Msg = "select ps_info Error";
return "";
}
m_res = mysql_store_result(&mysql);
if (m_res == NULL)
{
Msg = "select username Error";
return "";
}
string str("");
while (m_row = mysql_fetch_row(m_res))
{
for (int i = 0; i < Cnum; i++)
{
str += m_row[i];
str += cg;
}
str += rg;
rnum++;
}
mysql_free_result(m_res);
return str;
}
//插入數據
int VspdCToMySQL::InsertData(char * SQL, char * Msg)
{
char sql[2048];
sprintf(sql, SQL);
if (mysql_query(&mysql, sql) != 0)
{
Msg = "Insert Data Error";
return 1;
}
return 0;
}
//更換數據
int VspdCToMySQL::ReplaceData(char * SQL, char * Msg)
{
char sql[2048];
sprintf(sql, SQL);
if (mysql_query(&mysql, sql) != 0)
{
Msg = "Replace Data Error";
return 1;
}
return 0;
}
//更新數據
int VspdCToMySQL::UpdateData(char * SQL, char * Msg)
{
char sql[2048];
sprintf(sql, SQL);
if (mysql_query(&mysql, sql) != 0)
{
Msg = "Update Data Error";
return 1;
}
return 0;
}
//刪除數據
int VspdCToMySQL::DeleteData(char * SQL, char * Msg)
{
char sql[2048];
sprintf(sql, SQL);
if (mysql_query(&mysql, sql) != 0)
{
Msg = "Delete Data error";
return 1;
}
return 0;
}
//調用數據庫存儲過程
int VspdCToMySQL::CallProcedure(char * SQL, char * Msg)
{
char sql[2048];
sprintf(sql, SQL);
if (mysql_query(&mysql, sql) != 0)
{
Msg = "Call Procedure error";
return 1;
}
return 0;
}
//關閉數據庫連接
void VspdCToMySQL::CloseMySQLConn()
{
mysql_close(&mysql);
printf("斷開數據庫\n");
}
#include "DBMySQL.h"
int main(int argc, char* argv[]) //修改數據庫名稱,在本地數據庫服務器已經存在了
{
char* host = "127.0.0.1";
char* user = "root";
char* port = "3306";
char* passwd = "ranjiewen";
char* dbname = "world";
char* charset = "GBK";//支持中文
char* Msg = "";//消息變量
//初始化
VspdCToMySQL * vspdctomysql = new VspdCToMySQL;
if (vspdctomysql->ConnMySQL(host, port, dbname, user, passwd, charset, Msg) == 0)
printf("連接成功/r/n");
else
printf(Msg);
//查詢
char * SQL = "SELECT ids,username,passwd,address FROM vcaccesstest";
string str = vspdctomysql->SelectData(SQL, 4, Msg);
if (str.length() > 0)
{
printf("查詢成功/r/n");
printf(str.data());
printf("/r/n");
}
else
{
printf(Msg);
}
//插入
SQL = "insert into vcaccesstest(ids,username,passwd,address) values(4,'我的','123210','測試地址')";
if (vspdctomysql->InsertData(SQL, Msg) == 0)
printf("插入成功/r/n");
//更新
SQL = "update vcaccesstest set username = '修改了',passwd='2345' where ids = 3 ";
if (vspdctomysql->UpdateData(SQL, Msg) == 0)
printf("更新成功/r/n");
//刪除
SQL = "delete from vcaccesstest where ids = 3 ";
if (vspdctomysql->DeleteData(SQL, Msg) == 0)
printf("刪除成功/r/n");
vspdctomysql->CloseMySQLConn();
return 0;
}
- 接下來主要是做SQL基本語法進行系統學習
操作workbench
-
先不能連接locahost,后面可了連接成功。
-
基本的操作,可以用,查看什么應用程序操作了什么數據庫