You Are Here Home > February 2009

February 2009

Another great TED talk: David Bolinsky: Fantastic voyage inside a cell

Another great TED talk: David Bolinsky: Fantastic voyage inside a cell
Comments (0)   Filed under: Fun, Science   Posted by: Codehead

A Tiny MySQL++ Tutorial; C++ and MySQL; MySQL++ Example

I wrote a post about how to install MySQL++ and I thought I will write a quick tutorial on how to use it too.

This is a very basic MySQL++ program and it’s very self explanatory:

#include <mysql++.h>
#include <stdlib.h>
 
using namespace std;
using namespace mysqlpp;
 
int main() {
    try {
        Connection conn(false);
        conn.connect("DB NAME", "DB HOST probably localhost", "DB USER", "DB PASS");
        Query query = conn.query();
    } catch (BadQuery er) { // handle any connection or
        // query errors that may come up
        cerr << "Error: " << er.what() << endl;
        return -1;
    } catch (const BadConversion& er) {
        // Handle bad conversions
        cerr << "Conversion error: " << er.what() << endl <<
                "\tretrieved data size: " << er.retrieved <<
                ", actual size: " << er.actual_size << endl;
        return -1;
    } catch (const Exception& er) {
        // Catch-all for any other MySQL++ exceptions
        cerr << "Error: " << er.what() << endl;
        return -1;
    }
 
    return (EXIT_SUCCESS);
}

This will connect to your database and creates a query object ready to go. Save this as test.cpp

To compile this, you will have to create a Makefile in the same folder, so create a file and name it “Makefile” (no quotes) and add these to it:

CXX := g++
CXXFLAGS := -I/usr/include/mysql -I/usr/local/include/mysql++
LDFLAGS := -L/usr/local/lib -lmysqlpp -lmysqlclient -lnsl -lz -lm
EXECUTABLE := main
 
all: test
 
clean:
	rm -f $(EXECUTABLE) *.o

If you get funny errors, make sure there are no extra spaces in this file, and there is only one “tab” behind the line: rm -f $(EXECUTABLE) *.o

Now, you can make and run this by doing:
make
./test

Now, I’m going to show you how to execute some queries and you can go ahead and experiment on your own tables.

Here is a INSERT query followed by a SELECT; this will hopefully cover a lot, because INSERT is a type of query that doesn’t return anything and you need to escape values in order to INSERT.
SELECT on the other hand returns rows, although there are 3 ways that they can be done but here is a simple way that works for me.

#include <mysql++.h>
#include <stdlib.h>
 
using namespace std;
using namespace mysqlpp;
 
int main() {
    try {
        Connection conn(false);
        conn.connect("DB NAME", "DB HOST probably localhost", "DB USER", "DB PASS");
        Query query = conn.query();
 
        /* To insert stuff with escaping */
        query << "INSERT INTO some_table " <<
                     "VALUES (" <<
                     "'', " << /* This is left empty because the column is AUTO_INCREMENT */
                     "\"" << escape << some_var_that_contains_some_value << "\"" <<
                     ");";
        query.execute();
        /* That's it for INSERT */
 
        /* Now SELECT */
        query << "SELECT * FROM biz LIMIT 10";
        StoreQueryResult ares = query.store();
        for (size_t i = 0; i < ares.num_rows(); i++)
           cout << "Name: " << ares[i]["name"] << " - Address: " << ares[i]["address"] << endl;
 
        /* Let's get a count of something */
        query << "SELECT COUNT(*) AS row_count FROM biz";
        StoreQueryResult bres = query.store();
        cout << "Total rows: " << bres[0]["row_count"];
 
    } catch (BadQuery er) { // handle any connection or
        // query errors that may come up
        cerr << "Error: " << er.what() << endl;
        return -1;
    } catch (const BadConversion& er) {
        // Handle bad conversions
        cerr << "Conversion error: " << er.what() << endl <<
                "\tretrieved data size: " << er.retrieved <<
                ", actual size: " << er.actual_size << endl;
        return -1;
    } catch (const Exception& er) {
        // Catch-all for any other MySQL++ exceptions
        cerr << "Error: " << er.what() << endl;
        return -1;
    }
 
    return (EXIT_SUCCESS);
}

Again, whenever you want to run your code do:
make
./test

I wrote this because something like this would help myself a lot.

Good Luck :)

Update

query.reset();

Will reset the query object; this is useful when you are (in your program) generating a MySQL query but must discard it and generate another query (based on some condition).

A Tiny MySQL++ Tutorial; C++ and MySQL; MySQL++ Example
Comments (15)   Filed under: C/C++, MySQL, Programming   Posted by: Codehead

Installing MySQL++; How to install MySQL++ on Linux-CentOS

There is a lack of documentation on how to do this, I guess they assume that you must know a lot IF you are trying to use this library.

But here are step by step instructions on how to do it.

What you need
Root access to your server.
An SSH client, like putty, it’s free.

Let’s do it
1 – Run your SSH client and connect to your server using root.

2 – Do:

cd /

Note: I always make a folder like this

mkdir Tools
cd Tools

Note: This is version 3.0.9 obviously, it’s best if you check this web page and download the latest source code: http://www.tangentsoft.net/mysql++/

wget http://www.tangentsoft.net/mysql++/releases/mysql++-3.0.9.tar.gz
tar xvfz mysql++-3.0.9.tar.gz
cd mysql++-3.0.9
./configure
make
make install

3 – Now, in order for:

#include <mysql++.h>

To work, you will have to add a line to your ld.so.conf; you will find this file (hopefully) in /etc so go to:
/etc
And edit ld.so.conf and add this line to the end of it:
/usr/local/lib

Note: If ld.so.conf is not in /etc you can try “whereis ld.so.conf” (no quotes)

Save it and run:

ldconfig

And you are all set.

Please also note that, this worked on my CentOS and might not work exactly like this on your distribution.

Installing MySQL++; How to install MySQL++ on Linux-CentOS
Comments (4)   Filed under: C/C++, MySQL, Programming   Posted by: Codehead

Slowing down Yahoo! Slurp (Yahoo! Search Bot)

A few weeks ago one of our servers started to crash every few days.

After investigating this issue for a while we found 100s of IP addresses from Yahoo! and Inktomi Corporation which is the company who developed Yahoo! Slurp.

So basically Yahoo! was launching DOS attacks against our server although unintentional but very annoying. It also shows that their technology is not as advanced as Google or other search engines or it’s buggy, Whatever you think, crashing people’s servers with your search bot is not cool at all and shows that you have to work on it a little more…

If you have the same problem here is a simple solution Yahoo! suggest; open your robots.txt (create it if you don’t have it and place it in your root folder) and add these lines to it:

User-agent: Slurp
Crawl-delay: 1

Only Yahoo! will understand the line Crawl-delay: X and Yahoo! suggests that you use a small number between 0.5 and 1.

Slowing down Yahoo! Slurp (Yahoo! Search Bot)
Comments (0)   Filed under: Annoying Stuff, Search Engines, Server   Posted by: Codehead

A little Program For Monitoring Your Websites, With Alarm

I hope someone will find this useful:

###
 #    Hamid Alipour
###
 
###
 # Config
#####################################################
urls = ['http://www.P U T  Y O U R  U R L S  H E R E.com/']
url_timeout = 5
sleep_time = 5 * 60
failed_count_before_alarm = 10
sleep_time_on_failure = 15
#####################################################
 
import urllib2
import winsound
import time
 
class SiteMonitor:
 
    def __init__(self):
        pass
 
    def start(self):
        while True:
            for url in urls:
                if not self.check_url(url):
                    if not self.is_it_live(url):
                        self.alarm()
            self.sleep(sleep_time)
 
    def is_it_live(self, url):
        failed_count = 0
        while failed_count < failed_count_before_alarm:
            if not self.check_url(url):
                failed_count += 1
            else:
                return True
            self.sleep(sleep_time_on_failure)
        return False
 
    def check_url(self, url):
        print 'Checking...' + url + '...',
        try:
            urllib2.urlopen(url, timeout=url_timeout)
        except:
            print 'Failed!'
            return False
        print 'Done it\'s up!'
        return True
 
    def alarm(self):
        print 'Too many failures...'
        while True:
            print 'Alarm...'
            winsound.PlaySound("SystemExit", winsound.SND_ALIAS)
 
    def sleep(self, seconds):
        print 'Sleeping for ' + str(seconds) + ' second(s)...'
        time.sleep(seconds)
        print 'Waking up...'
 
def main():
    SiteMonitor().start()
 
if __name__ == "__main__":
    main()

Save it as sitemonitor.py and run it like:
python sitemonitor.py

Or just double click on the file.

Please note: in order to run this, you will have to install Python:
http://www.python.org/download/

A little Program For Monitoring Your Websites, With Alarm
Comments (1)   Filed under: Python, Server   Posted by: Codehead