EnderUnix Software Development Team

FreeBSD'de Mysql Icin C++ API'si ne Giris...(Mysql++)
(Turkish Version)

 

Giris

17 Mart 2001

Bu dokumanda, mysql'e c++ ile erisimi mumkun kilan bir c++ kutuphanesi olan Mysql++ 1.7 'nin FreeBSD makinaniza kurulumu anlatilacak, ve ardindan uc ufak ornekle Mysql ve C++ 'in nasil kullanilacagi anlatilmaya calisilacaktir.
Genel Notlar
Bu dokumanin en guncel hali; http://www.enderunix.org/documents/mysql++.html adresindedir.

Aksi belirtilmedigi takdirde bu gibi dokumanlarin haklari kendilerini yazan yazarlarda saklidir. Bu dokuman da, parca parca ya da tamamen herhangi bir sekilde, yazarinin izni dahilinde dagitilabilir.

Yazar, bu dokumani okuyanlarin ugrayacaklari herhangi bir zarardan oturu sorumluluk kabul etmez. Use at your own risk!

Eger, herhangi bir konuda yardima ihtiyaciniz olursa, murat@enderunix.org ya da roots@enderunix.org adresine mail atabilirsiniz.!

-- Murat Balaban
   murat@enderunix.org
   17 Mart, 2001

Mysql++-1.7 kurulumu
 

Baslamadan once hemen belirtmekte fayda var ki, bu api, mysql'in client library'lerinin kurulmus oldugunu varsayar.. libmysqlclient yuklu degilse, once onu yukleyin, sonra mysql++ 'in kurulumuna devam edin efendim... Ama, eger normal FreeBSD mysql-version-client kullaniyorsaniz, zaten bu kutuphane sizin icin kuruludur.

API'mizi port'larimizdan kuracagiz.

[root@pathfinder examples]# cd /usr/ports/databases/mysql++
[root@pathfinder mysql++]# make install

dedigimizde, FreeBSD mysql++'i onceden balirlenmis sitelerden bulabildigi birisinden indirecek, derleyecek ve kuracaktir.

Kurulum, header dosyalarini /usr/local/include altina, libsqlplus.{a|so|so.1} library'lerini de /usr/local/lib altina koyacaktir.
Fakat, FreeBSD'deki port biraz yanlis duzenlenmis. Bizim icin gerekli iki header dosyasi eksik kopyalaniyor. Bunlari da biz elimizle kopyalalim:

[root@pathfinder mysql++]# cp /usr/ports/databases/mysql++/work/mysql++-1.7/sqlplusint/define_short /usr/local/include/
[root@pathfinder mysql++]# cp /usr/ports/databases/mysql++/work/mysql++-1.7/sqlplusint/defs /usr/local/include/

Ornek 1: create_table.cpp
Evet, simdi mysql++'la kod yazip mysql'e erisebilmek icin herseyimiz hazir. Simdi su ornegimize bakalim:
(Bunu ve diger ornekleri, http://www.enderunix.org/documents/mysql++-samples.tgz adresinden alabilirsiniz...

 

 

Figure #1 ( create_table.cpp )

//------------------------------------starts here-----------------------------------

#include <iostream>
#include <sqlplus.hh> // API'miz icin bu header dosyayi ekliyoruz.
#define HOST "localhost" // mysql server'iniz nerde?
#define DB "enderunix" // database isminiz?
#define USERNAME "root" // yukaridaki database'e erisimi olan bir user
#define PASSWORD "" // buraya o kullanicinin sifresini yazin. Benim sifrem yoktu onun icin yazmadim.

int main () { //iste basliyoruz.

Connection connection (use_exceptions); // Connection class'indan bir obje oluturuyoruz.

// Obje'miz exception handle edebiliyor.

try { // butun main() koskoca bir try blogundan ibaret aslinda.

connection.connect("", HOST, USERNAME, PASSWORD); // iste baglaniyoruz.

try { // database'i secme'yi deniyoruz, hata donerse, olusturmak icin.

connection.select_db(DB); // database'i sec

} catch (BadQuery er ) { // exception throw edildiyse, yakala (catch)

connection.create_db(DB); // ve once database'i olustur, sonra sec.

connection.select_db(DB);

}

Query query = connection.query(); // Query class'indan bir obje, ama connection objesine bagli.

// Asagidakide query'miz. Ne kadar kolay degil mi? <<'i overload etmisler.

query << "CREATE TABLE fihrist (id INT not null auto_increment, name TEXT not null , surname TEXT not null , phone TEXT not null , email TEXT not null , web TEXT not null , PRIMARY KEY (id), INDEX (id), UNIQUE (id))";

try {

query.execute(); // execute et.

} catch (BadQuery er) { // exception'u yakala

cerr << "Error: " << er.error << endl; // hata'yi ekrana basiyoruz.

return -1;

}

} catch (BadQuery er) { // hata'yi ekrana basiyoruz.

cerr << "Error: " << er.error << endl;

return -1;

}

 

return 0;

}

//------------------------------------------------ends here-------------------------------------------------------------------------

 Peki nasil derliycegiz?

[root@pathfinder examples]# c++ -D_FIX_FOR_BSD_ -I/usr/local/include/mysql -L/usr/local/lib -lsqlplus create_table.cpp -o create_table
/usr/local/lib/mysql/libmysqlclient.so.6: warning: tempnam() possibly used unsafely; consider using mkstemp()
[root@pathfinder examples]#

 Burada, -I flag'i ile, /usr/local/include/mysql dizinini PATH'imize aliyoruz, -L flag'i ile kutuphanelerimizin yerini belirliyoruz, ve de -lsqlplus 'i da linkliyoruz. Ortaya create_table diye bir binary cikiyor. Bunu calistirdigimizda,

[root@pathfinder examples]# ./create_table
[root@pathfinder examples]#

Hatasiz database'imizi ve fihrist isimli table'imiz olusuyor. Kontrol edelim:

[root@pathfinder examples]# mysql

Welcome to the MySQL monitor. Commands end with ; or \g.

Your MySQL connection id is 33 to server version: 3.22.32

Type 'help' for help.

mysql> show databases;

+-----------+

| Database |

+-----------+

| enderunix |

| murat |

| mysql |

| test |

+-----------+

4 rows in set (0.01 sec)

mysql> use enderunix;

Reading table information for completion of table and column names

You can turn off this feature to get a quicker startup with -A

Database changed

mysql> describe fihrist;

+---------+---------+------+-----+---------+----------------+

| Field | Type | Null | Key | Default | Extra |

+---------+---------+------+-----+---------+----------------+

| id | int(11) | | PRI | 0 | auto_increment |

| name | text | | | NULL | |

| surname | text | | | NULL | |

| phone | text | | | NULL | |

| email | text | | | NULL | |

| web | text | | | NULL | |

+---------+---------+------+-----+---------+----------------+

6 rows in set (0.01 sec)

mysql>

Evet, gordugumuz uzere, database'imiz ve table'imiz cok dogru olusturulmus.

Simdi, de bu table'a veri girecek bir programcik yazalim:

Ornek #2: insert_data.cpp
 

 

Figure #2 ( insert_data.cpp )

//--------------------------------------------------------starts here---------------------------------------------------------------
#include <iostream>
#include <sqlplus.hh>
#include <string>
#define HOST "localhost" // mysql server'iniz nerde?
#define DB "enderunix" // database isminiz?
#define USERNAME "root" // yukaridaki database'e erisimi olan bir user
#define PASSWORD "" // buraya o kullanicinin sifre

int main () {

struct Person { // gereksiz belki, ama programi ilerletme olasiligina karsi kullandim bunu.

int id;

string name;

string surname;

string phone;

string email;

string web;

};

Person person;

 

cout << "Please enter name\n"; // evet, bilgileri kullanicidan aliyoruz...

cin >> person.name;

cout << "Please enter surname\n";

cin >> person.surname;

cout << "Please enter phone number\n";

cin >> person.phone;

cout << "Please enter email address\n";

cin >> person.email;

cout << "Please enter web address\n";

cin >> person.web;

 

 

Connection connection (use_exceptions);

try {

connection.connect("", HOST, USERNAME, PASSWORD);

connection.select_db(DB);

Query query = connection.query();

// Birinci ornekten tek farki query. Bu defa insert yapiyoruz....

 

query << "INSERT INTO fihrist " << "(id, name, surname, phone, email, web) VALUES (\"\",\"" << person.name << "\", \""

<< person.surname << "\", \"" << person.phone << "\", \"" << person.email << "\", \"" << person.web << "\" )";

try {

query.execute();

} catch (BadQuery er) {

cerr << "Error: " << er.error << endl;

return -1;

}

} catch (BadQuery er) {

cerr << "Error: " << er.error << endl;

return -1;

}

 

return 0;

}

//--------------------------------------------------------------ends here------------------------------------------------------------

Simdi bunu da derleyelim:

[root@pathfinder examples]# c++ -D_FIX_FOR_BSD_ -I/usr/local/include/mysql -L/usr/local/lib -lsqlplus insert_data.cpp -o insert_data
/usr/local/lib/mysql/libmysqlclient.so.6: warning: tempnam() possibly used unsafely; consider using mkstemp()
[root@pathfinder examples]#

Calistiralim:

[root@pathfinder examples]# ./insert_data
Please enter name
Murat
Please enter surname
Balaban
Please enter phone number
+905325566557
Please enter email address
murat@enderunix.org
Please enter web address
http://www.enderunix.org
[root@pathfinder examples]# ./insert_data
Please enter name
Ismail
Please enter surname
Yenigul
Please enter phone number
+905552545511
Please enter email address
ismail@enderunix.org
Please enter web address
http://www.enderunix.org/~yenigul/
[root@pathfinder examples]#

Evet, bilgilerimizi basaiyla database'imize yerlestirdik, simdi kontrol edelim:

[root@pathfinder examples]# mysql

Welcome to the MySQL monitor. Commands end with ; or \g.

Your MySQL connection id is 36 to server version: 3.22.32

Type 'help' for help.

mysql> use enderunix

Reading table information for completion of table and column names

You can turn off this feature to get a quicker startup with -A

Database changed

mysql> select * from fihrist;

+----+--------+---------+---------------+----------------------+------------------------------------+

| id | name | surname | phone | email | web |

+----+--------+---------+---------------+----------------------+------------------------------------+

| 1 | Murat | Balaban | +905325566557 | murat@enderunix.org | http://www.enderunix.org |

| 2 | Ismail | Yenigul | +905552545511 | ismail@enderunix.org | http://www.enderunix.org/~yenigul/ |

+----+--------+---------+---------------+----------------------+------------------------------------+

2 rows in set (0.00 sec)

mysql>

Gordugumuz gibi girdigimiz bilgiler basariyla mysql veritabanimiza yerlestirilmis.

Simdi de, Girdigimiz bilgileri sorgulayan bir arabirim yazalim:

Ornek #3: select_data.cpp
 

Figure #3 ( select_data.cpp )

//------------------------------------------------starts here-----------------------------------------------------------------------------
#include <iostream>
#include <sqlplus.hh>
#include <iomanip>
#include <string>
#define HOST "localhost" // mysql server'iniz nerde?
#define DB "enderunix" // database isminiz?
#define USERNAME "root" // yukaridaki database'e erisimi olan bir user
#define PASSWORD "" // buraya o kullanicinin sifresi yaziliyor...

 int main () {

 struct Person {

int id;

string name;

string surname;

string phone;

string email;

string web;

};

Person person;

 

cout << "Please enter name\n"; // sorgulanacak ismi aliyoruz.

cin >> person.name;

 

 

Connection connection (use_exceptions);

try {

connection.connect("", HOST, USERNAME, PASSWORD);

connection.select_db(DB);

Query query = connection.query();

// Querymiz yapiliyor:

 

query << "SELECT * FROM fihrist WHERE name = \"" << person.name << "\"";

 

try {

Result result = query.store(); // query.store() query'i execute edip sakliyor,

// Biz de query objesine bagli Result class'indan result objesi olusturuyoruz.

Row row; // Row'umuz icin bu da.

Result::iterator i;

int count = 0;

for ( i = result.begin(); i != result.end() ; i++ ) { // result'imiz bitene kadar bir dongu.

row = *i;

cout << "\nRecord #" << ++count << "\tID: " << row["id"] << endl;

cout.setf(ios::left);

cout << setw(10) << "Name" << row["name"] << "\n"

<< setw(10) << "Surname" << row["surname"] << "\n"

<< setw(10) << "E-Mail" << row["email"] << "\n"

<< setw(10) << "Phone" << row["phone"] << "\n"

<< setw(10) << "Web" << row["web"] << "\n";

}

cout << "\nTotally, " << result.size() << " records listed.\n\n";

} catch (BadQuery er) {

cerr << "Error: " << er.error << endl;

return -1;

}

} catch (BadQuery er) {

cerr << "Error: " << er.error << endl;

return -1;

}

 

 

catch (BadConversion er) {

cerr << "Error: Tried to convert \"" << er.data << "\" to a \""

<< er.type_name << "\"." << endl;

return -1;

}

return 0;

}

//------------------------------------------------------------------ends here-------------------------------------------------------------

Simdi de derleyip calistiralim:

[root@pathfinder examples]# c++ -D_FIX_FOR_BSD_ -I/usr/local/include/mysql -L/usr/local/lib -lsqlplus select_data.cpp -o select_data
/usr/local/lib/mysql/libmysqlclient.so.6: warning: tempnam() possibly used unsafely; consider using mkstemp()
[root@pathfinder examples]#
[root@pathfinder examples]# ./select_data
Please enter name
murat

Record #1 ID: 1
Name Murat
Surname Balaban
E-Mail murat@enderunix.org
Phone +905325566557
Web http://www.enderunix.org

Totally, 1 records listed.

[root@pathfinder examples]#

 Kolay gelsin...

Kaynaklar:
Mysql Manual:
http://www.mysql.com/documentation/index.html

Mysql++ Manual:
http://www.mysql.com/documentation/mysql++/index.html