Archive for the ‘DBI’ Category

  1. Hello, DB API(Python) World!

    Posted on 9月 24th, 2012 by cx20

    DB API

    Python DB API は Python 向けの Database Interface(API)である。
    各データベースドライバを介することで、様々な DBMS への接続が可能となっている。

    ソースコード(Python + DB API + MySQL)

    import MySQLdb
     
    cn = MySQLdb.connect(db="test", host="127.0.0.1", port=3306, user="root", passwd="P@ssW0rd")
    cur = cn.cursor()
    cur.execute("SELECT 'Hello, DB API World!' AS Message")
    rows = cur.fetchall()
     
    for row in rows:
        print "Message"
        print "-------------------"
        print row[0]
     
    cur.close()
    cn.close()

    実行方法(Windows)

    C:¥> python hello.py

    実行結果

    Message
    -----------------
    Hello, DB API World!
  2. Hello, DBI(Ruby) World!

    Posted on 9月 21st, 2012 by cx20

    DBI

    DBI は Ruby 向けの Database Interface(API)である。
    各データベースドライバを介することで、様々な DBMS への接続が可能となっている。

    ソースコード(Perl + DBI + MySQL)

    require "dbi"
    dbh = DBI.connect("dbi:Mysql:test:localhost", "root", "P@ssW0rd")
    sth = dbh.prepare("SELECT 'Hello, DBI World' AS Message")
    sth.execute()
    while row = sth.fetch do
        print "Message", "n";
        print "-------------------n";
        print row[0]
    end
    sth.finish
    dbh.disconnect

    ライブラリ導入方法

    C:¥> gem install dbi
    C:¥> gem install dbd-mysql

    実行方法(Windows)

    C:¥> ruby hello.rb

    実行結果

    Message
    -----------------
    Hello, DBI World!
  3. Hello, DBI(Perl) World!

    Posted on 9月 18th, 2012 by cx20

    DBI

    DBI は Perl 向けの Database Interface(API)である。
    各データベースドライバを介することで、様々な DBMS への接続が可能となっている。

    ソースコード(Perl + DBI + ODBC + SQL Server)

    use strict;
    use DBI;
     
    my $dbh = DBI->connect('dbi:ODBC:Driver={SQL Server};Server=(local)', 'sa', 'P@ssW0rd');
    my $sth = $dbh->prepare("SELECT 'Hello, DBI World' AS Message");
    $sth->execute();
     
    while (my $row = $sth->fetchrow_array) {
        print "Message", "n";
        print "-------------------n";
        print $row, "n";
    }
    $sth->finish();
    $dbh->disconnect();

    ソースコード(Perl + DBI + MySQL)

    use strict;
    use DBI;
     
    my $dbh = DBI->connect('dbi:mysql:test', 'root', 'P@ssW0rd');
    my $sth = $dbh->prepare("SELECT 'Hello, DBI World' AS Message");
    $sth->execute();
     
    while (my $row = $sth->fetchrow_array) {
        print "Message", "n";
        print "-------------------n";
        print $row, "n";
    }
    $sth->finish();
    $dbh->disconnect();

    実行方法(Windows)

    C:¥> perl hello.pl

    実行結果

    Message
    -----------------
    Hello, DBI World!