C++ 连接mysql和连接菜刀access数据库查询
C++连接MysqlDemo:
#include "StdAfx.h"
#include "winsock.h"
#include <iostream>
#include "mysql.h"
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "libmysql.lib")
using namespace std;
void getConnecetion(){
MYSQL mydata;
mysql_library_init(0,NULL,NULL);//初始化MySQL C API库
mysql_init(&mydata);//初始化mydata的数据结构,mydata是MYSQL对象
mysql_options(&mydata,MYSQL_SET_CHARSET_NAME,"gbk");//连接选项:添加GBK字符集支持
//连接函数
if(mysql_real_connect(&mydata,"localhost","root","caonimei","test",3306,0,0) != NULL){
cout<<"database connection OK!"<<endl;
system("pause");
}
}
void main()
{
//getConnecetion();
}
C++连接菜刀数据库查询Demo:
#include "stdafx.h"
#include<iostream>
using namespace std;
#include <stdio.h>
#import "c:\program files\common files\system\ado\msado15.dll" no_namespace rename ("EOF", "adoEOF")
int main(int argc, char *argv[]){
char sql[100];
char *pwd = "\x0A\xC3\xDC\x0D\x09\x0A\xC2\xEB\x02";
char *db = "db.mdb";
if(argc == 2) {
db = argv[1];
}
sprintf(sql, "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;Jet OLEDB:Database Password=%s", db, pwd);
_ConnectionPtr m_pConnection;
CoInitialize(NULL);
m_pConnection.CreateInstance(__uuidof(Connection));
try {
m_pConnection->Open(sql, "", "", adModeUnknown);
} catch (_com_error e) {
cout<<e.Description()<<endl;
return 0;
}
_RecordsetPtr m_pRecordset;
m_pRecordset.CreateInstance(__uuidof(Recordset));
/**
获取所有表名
m_pRecordset = m_pConnection->OpenSchema(adSchemaTables);
while(!(m_pRecordset->adoEOF))
{
_bstr_t table_name = m_pRecordset->Fields->GetItem("TABLE_NAME")->Value;
_bstr_t table_type = m_pRecordset->Fields->GetItem("TABLE_TYPE")->Value;
cout<<table_name<<endl;
m_pRecordset->MoveNext();
}
m_pRecordset->Close();
return 0;
*
**/
const _variant_t vtSql = "SELECT * FROM SITE"; //存放的表名为SITE
try{
m_pRecordset->Open(vtSql, m_pConnection.GetInterfacePtr(), adOpenDynamic, adLockOptimistic, adCmdText);
}
catch(_com_error e)
{
cout<<e.Description()<<endl;
}
/**
获取字段名
Fields* fields=NULL;
m_pRecordset->get_Fields(&fields);
long count = fields->Count;
BSTR *bstr = new BSTR[count];
for(long j=0; j<count; j++)
{
fields->Item[j]->get_Name(&bstr[j]);
char *name = _com_util::ConvertBSTRToString(bstr[j]);
cout<<name<<" ";
}
*得到shell地址字段名为SiteUrl
**/
_variant_t var;
char *value;
try{
if(!m_pRecordset->BOF) {
m_pRecordset->MoveFirst();
} else {
cout<<"表内数据为空"<<endl;
return 1;
}
while(!m_pRecordset->adoEOF) {
var = m_pRecordset->GetCollect("SiteUrl");
if(var.vt != VT_NULL)
value= _com_util::ConvertBSTRToString((_bstr_t)var);
cout<<value<<endl;
m_pRecordset->MoveNext();
}
}
catch(_com_error e)
{
cout<<e.Description()<<endl;
}
m_pRecordset->Close();
m_pRecordset = NULL;
if(m_pConnection->State)
m_pConnection->Close();
m_pConnection= NULL;
system("pause");
return 0;
}