LinuxでC/C++を使用してデータベースにアクセス
Linuxの下でC/C++を使ってデータベースにアクセスする——MySQL編
最近、OAシステムを书くつもりで、データベースの操作を容易にするために、わざわざ一周间を割いてC/C++が各种のデータベースにアクセスする方法を研究して、そしてデータベースの操作クラスをカプセル化するつもりで、今最も简単な一部を捧げます:Linuxの下でMySQLデータベースにアクセスします.
本明細書で使用するMySQL APIコードはC言語であり、C++に興味がある方はmysql++を使用することも考えられます.
一、開発環境の配置
まずMySQLをコンパイル、インストールする必要があります.インストールが完了したら、MySQLディレクトリのlibディレクトリを環境変数に追加します.
新しいC/C++プロジェクトを作成し、$MYSQL_ROOT/includeはコンパイル環境の含むパスの下に追加されます.コンパイルオプションで$MYSQL_を追加ROOT/libディレクトリ.Linkオプションで-lmysqlclient(libディレクトリをシステム環境変数に追加した)を追加するか、libmysqlclient.soファイルを直接参照します.
二、プログラムコード
あまり言わないで、直接コードをつけて、注釈はすべてとても詳しいです.
三、修正提案
本人は今後の完備でrunSQLCommand(char*sql)関数を2つまたは3つの関数に分解し、selectやinsertなどの文をそれぞれ実行するつもりです.
プログラムでは、パラメータがconstであることを強制していません.セキュリティの問題が発生する可能性があります.
本文はただレンガを投げて玉を引く役割を果たして、達人が私のプログラムの中の問題を指摘することができることを望んでいます.
上一篇文章:Linux下使用C/C++アクセスデータベース——SQL Server篇
一例
最近、OAシステムを书くつもりで、データベースの操作を容易にするために、わざわざ一周间を割いてC/C++が各种のデータベースにアクセスする方法を研究して、そしてデータベースの操作クラスをカプセル化するつもりで、今最も简単な一部を捧げます:Linuxの下でMySQLデータベースにアクセスします.
本明細書で使用するMySQL APIコードはC言語であり、C++に興味がある方はmysql++を使用することも考えられます.
一、開発環境の配置
まずMySQLをコンパイル、インストールする必要があります.インストールが完了したら、MySQLディレクトリのlibディレクトリを環境変数に追加します.
新しいC/C++プロジェクトを作成し、$MYSQL_ROOT/includeはコンパイル環境の含むパスの下に追加されます.コンパイルオプションで$MYSQL_を追加ROOT/libディレクトリ.Linkオプションで-lmysqlclient(libディレクトリをシステム環境変数に追加した)を追加するか、libmysqlclient.soファイルを直接参照します.
二、プログラムコード
あまり言わないで、直接コードをつけて、注釈はすべてとても詳しいです.
/*
* MySQLManager.h
*
* Created on: Feb 18, 2009
* Author: Steven Wee
*/
#ifndef MYSQLMANAGER_H_
#define MYSQLMANAGER_H_
#include "../Common/CheckStringTools.h"
#include <mysql.h>
#include <string>
#include <iostream>
#include <vector>
#include <string.h>
using namespace std;
class MySQLManager
{
public:
/*
* Init MySQL
* @param hosts: Host IP address
* @param userName: Login UserName
* @param password: Login Password
* @param dbName: Database Name
* @param port: Host listen port number
*/
MySQLManager(std::string hosts, std::string userName, std::string password, std::string dbName, unsigned int port);
~MySQLManager();
void initConnection();
/*
* Making query from database
* @param mysql: MySQL Object
* @param sql: Running SQL command
*/
bool runSQLCommand(std::string sql);
/**
* Destroy MySQL object
* @param mysql MySQL object
*/
void destroyConnection();
bool getConnectionStatus();
vector< vector<string> > getResult();
protected:
void setUserName(std::string userName);
void setHosts(std::string hosts);
void setPassword(std::string password);
void setDBName(std::string dbName);
void setPort(unsigned int port);
private:
bool IsConnected;
vector< vector<string> > resultList;
MYSQL mySQLClient;
unsigned int DEFAULTPORT;
char * HOSTS;
char * USERNAME;
char * PASSWORD;
char * DBNAME;
};
#endif /* MYSQLMANAGER_H_ */
/*
* MySQLManager.cpp
*
* Created on: Feb 18, 2009
* Author: Steven Wee
*/
#include "MySQLManager.h"
MySQLManager::MySQLManager(string hosts, string userName, string password, string dbName, unsigned int port)
{
IsConnected = false;
this ->setHosts(hosts); // IP
this ->setUserName(userName); //
this ->setPassword(password); //
this ->setDBName(dbName); //
this ->setPort(port); //
}
MySQLManager::~MySQLManager()
{
this ->destroyConnection();
}
void MySQLManager::setDBName(string dbName)
{
if ( dbName.empty() )
{//
std::cout << "DBName is null! Used default value: mysql" << std::endl;
this ->DBNAME = new char[5];
strcpy(this ->DBNAME, "mysql");
}
else
{
this ->DBNAME = new char[dbName.length()];
strcpy(this ->DBNAME, dbName.c_str());
}
}
void MySQLManager::setHosts(string hosts)
{
if ( hosts.empty() )
{// IP
std::cout << "Hosts is null! Used default value: localhost" << std::endl;
this ->HOSTS = new char[9];
strcpy(this ->HOSTS, "localhost");
}
else
{
this ->HOSTS = new char[hosts.length()];
strcpy(this ->HOSTS, hosts.c_str());
}
}
void MySQLManager::setPassword(string password)
{//
if ( password.empty() )
{
std::cout << "Password is null! Used default value: " << std::endl;
this ->PASSWORD = new char[1];
strcpy(this ->PASSWORD, "");
}
else
{
this ->PASSWORD = new char[password.length()];
strcpy(this ->PASSWORD, password.c_str());
}
}
void MySQLManager::setPort(unsigned int port)
{// ,
if ( port )
{
std::cout << "Port number is null! Used default value: 0" << std::endl;
this ->DEFAULTPORT = 0;
}
else
{
this ->DEFAULTPORT = port;
}
}
void MySQLManager::setUserName(string userName)
{//
if ( userName.empty() )
{
std::cout << "UserName is null! Used default value: root" << std::endl;
this ->USERNAME = new char[4];
strcpy(this ->USERNAME, "root");
}
else
{
this ->USERNAME = new char[userName.length()];
strcpy(this ->USERNAME, userName.c_str());
}
}
void MySQLManager::initConnection()
{
if ( IsConnected )
{//
std::cout << "Is connected to server!" <<std::endl;
return;
}
mysql_init(&mySQLClient);//
if ( !mysql_real_connect( &mySQLClient, HOSTS, USERNAME, PASSWORD, DBNAME, DEFAULTPORT, NULL, 0) )
{//
std::cout << "Error connection to database: %s
" << mysql_error(&mySQLClient) << std::endl;
}
IsConnected = true;//
}
bool MySQLManager::runSQLCommand(string sql)
{
if ( !IsConnected )
{//
std::cout << "Not connect to database!" << std::endl;
return false;
}
if ( sql.empty() )
{// SQL
std::cout << "SQL is null!" << std::endl;
return false;
}
MYSQL_RES *res;
MYSQL_ROW row;
unsigned int i,j = 0;
StringTools stringTools;
sql = stringTools.filterString(sql);
i = mysql_real_query(&mySQLClient,sql.c_str(),(unsigned int)strlen(sql.c_str()));//
if ( i )
{
std::cout << "Error query from database: %s
" << mysql_error(&mySQLClient) << std::endl;
return false;
}
res = mysql_store_result(&mySQLClient);
vector<string> objectValue;
while( (row = mysql_fetch_row(res)) )
{//
objectValue.clear();
for ( j = 0 ; j < mysql_num_fields(res) ; j++ )
{
objectValue.push_back(row[j]);
}
this ->resultList.push_back(objectValue);
}
mysql_free_result(res); //free result after you get the result
return true;
}
vector< vector<string> > MySQLManager::getResult()
{
return resultList;
}
void MySQLManager::destroyConnection()
{
mysql_close(&mySQLClient);
this ->IsConnected = false;
}
bool MySQLManager::getConnectionStatus()
{
return IsConnected;
}
三、修正提案
本人は今後の完備でrunSQLCommand(char*sql)関数を2つまたは3つの関数に分解し、selectやinsertなどの文をそれぞれ実行するつもりです.
プログラムでは、パラメータがconstであることを強制していません.セキュリティの問題が発生する可能性があります.
本文はただレンガを投げて玉を引く役割を果たして、達人が私のプログラムの中の問題を指摘することができることを望んでいます.
上一篇文章:Linux下使用C/C++アクセスデータベース——SQL Server篇
一例
#include <iostream>
#include <string>
#include <strstream>
using namespace std;
class CBaseX
{
public:
int x;
CBaseX() { x = 10; }
void foo() { printf("CBaseX::foo() x=%d
", x); }
};
class CBaseY
{
public:
int y;
int* py;
CBaseY() { y = 20; py = &y; }
void bar() { printf("CBaseY::bar() y=%d, *py=%d
", y, *py);
}
};
class CDerived : public CBaseX, public CBaseY
{
public:
int z;
CDerived() { z = 10; }
void test() { printf("test z=%d
", z); }
};
int main()
{
int n = 65535;
strstream ss;
strstream ss1;
strstream ss2;
string s;
string s1;
string s2;
ss << n;
ss >> s;
cout << s << endl;
double t_d = 10.6;
float t_i= static_cast<float>(t_d);
// cout<<t_i<endl;
ss1<<t_i;
ss1>>s1;
cout << s1 << endl;
char* c="iloveyou";
char * p = reinterpret_cast<char *>(c);//
ss2<<p;
ss2>>s2;
cout << s2 << endl;
CDerived* pD = new CDerived();
// pD->bar();
printf("CDerived* pD = %x
", (int)pD);
CBaseY* pY = pD; // , pY = pD + 4
// pY->bar();
CBaseY* pD3 = dynamic_cast<CBaseY*>(pD);//
pD3->bar();
CDerived* pD4 = static_cast<CDerived*>(pD3);//
pD4->bar();
CBaseY* pD5 = static_cast<CBaseY*>(pD4);//
pD5->bar();
CDerived* pD6 = reinterpret_cast<CDerived*>(pD4);//
pD6->bar();
printf("CBaseY* pY = %x
", (int)pY);
void* pV1 = pY; // , pV1 = pY
printf("void* pV1 = %x
", (int)pV1);
// pD2 = pY, pD2 = pY - 4
CDerived* pD2 = static_cast<CDerived*>(pV1);
printf("CDerived* pD2 = %x
", (int)pD2);
//
pD2->test();
/*
class B {};
class D: public B {}
void f( B* pb )
{
D* pd1 = dynamic_cast<D*>(pb);
D* pd2 = static_cast<D*>(pb);
}*/
return 0;
}
/*
dynamic_cast:
static_cast : ,
reinterpret_cast:
const_cast:
*/