0% found this document useful (0 votes)
113 views

Database Language Bindings: Java (Mysql)

This document provides code examples for connecting to and querying databases using various programming languages and databases. It includes examples using Java with MySQL and Firebird, TCL with MySQL and Firebird via ODBC, PHP with MySQL, Python with MySQL, Ruby with MySQL, and C# Mono with MySQL. For each language and database combination, it provides the code to connect, execute a sample query, and close the connection. It also provides links to documentation for connecting to databases from each language.

Uploaded by

Brian LeGrand
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
113 views

Database Language Bindings: Java (Mysql)

This document provides code examples for connecting to and querying databases using various programming languages and databases. It includes examples using Java with MySQL and Firebird, TCL with MySQL and Firebird via ODBC, PHP with MySQL, Python with MySQL, Ruby with MySQL, and C# Mono with MySQL. For each language and database combination, it provides the code to connect, execute a sample query, and close the connection. It also provides links to documentation for connecting to databases from each language.

Uploaded by

Brian LeGrand
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Java (MySQL)

Database Language
Bindings
Slides prepared by Mike Rogers

importjava.sql.*;
publicclassJavaEx {
publicstaticvoidmain(String args[]){
try{
Statement stmt; ResultSet rs;
//Register the JDBC driver for MySQL.
Class.forName("com.mysql.jdbc.Driver");
//Define URL of database server
String url = "jdbc:mysql://localhost:3306/mytestdb";
//Get a connection to the database
Connection con = DriverManager.getConnection(url,"user", "password");
//Get a Statement object
stmt = con.createStatement();
rs = stmt.executeQuery("select customers.lname, customers.fname, "+
"books.title from customers, books, orders "+

"where customers.id = orders.custId and "+

"books.id = orders.bookId");
//Use the methods of class ResultSet in a loop to display all of the data in the
// database.
System.out.println("Display all results:");
while(rs.next()){

String lname = rs.getString("customers.lname");

String fname = rs.getString("customers.fname");

String btitle = rs.getString("books.title");

System.out.println("\t"+ fname + "\t"+ lname + "\t"+ btitle);


}
con.close();
} catch(Exception ex){
System.out.println(ex.getMessage());
}
}
}

Java Connector/J
Documentation

Compile with:

javac -cp /path_to/mysql-connector-java.jar:./ JavaEx.java


On your VM:

Run with:

java -cp /path_to/mysql-connector-java.jar:./ JavaEx


On your VM:

javac -cp ./:/usr/share/java/mysql.jar JavaEx.java

java -cp ./:/usr/share/java/mysql.jar JavaEx

Docs are found Here:

http://dev.mysql.com/doc/refman/5.0/en/connector-j.html

Java (Firebird)
public class EmployeeExample {
public static void main (String args[]) throws Exception {
String databaseURL = "jdbc:firebirdsql:localhost:/var/lib/firebird/2.5/data/employee.fdb?sql_dialect=3";
String user = "SYSDBA";
String password = "mypassword";
String driverName = "org.firebirdsql.jdbc.FBDriver";
java.sql.Driver d = null;
java.sql.Connection c = null;
java.sql.Statement s = null;
java.sql.ResultSet rs = null;
try {
Class.forName ("org.firebirdsql.jdbc.FBDriver");
} catch (java.lang.ClassNotFoundException e) {
System.out.println ("Firebird JCA-JDBC driver not found in class path");
System.out.println (e.getMessage ());
return;
}
try {
c = java.sql.DriverManager.getConnection (databaseURL, user, password);
s = c.createStatement ();
rs = s.executeQuery("SELECT first_name, last_name FROM employee ORDER BY last_name");
while (rs.next ()) {
System.out.println (rs.getString ("first_name") + " " + rs.getString ("first_name"));
}
rs.close (); s.close (); c.close ();
} catch (java.sql.SQLException e) {
System.out.println ("Unable to step thru results of query");
e.printStackTrace();
return;
}
}
}

Java Jaybird Documentation

Compile with:

java -cp ./:path_to_jaybird/jaybird-full-2.1.6.jar EmployeeExample

Docs are found here:

INSERT, DELETE, UPDATE or any DDL

Run with:

javac -cp ./:path_to_jaybird/jaybird-full-2.1.6.jar EmployeeExample.java

Java an Updating SQL

execute(Stringsql)

true if the first result is a ResultSet object; false if it is an update count


or there are no results

Can be used for SELECT queries also

http://www.firebirdsql.org/index.php?op=devel&sub=jdbc

TCL (MySQL)
if {[catch {
# load mysqltcl library
package require mysqltcl
# connect to the database
set m [mysql::connect -user username -db mytestdb -password password]
# Submit the query and iterate over the results
foreach res [
mysql::sel $m {
select customers.lname,customers.fname, books.title from
customers, books, orders where customers.id = orders.custId
and books.id = orders.bookId} -flatlist] {
puts "$res"
}
# Close the connection
mysql::close $m
} res]} {
puts $res
}

Tcl (MySQL)

INSERT, DELETE, UPDATE or any DDL

mysql::exec

handle sql-statement

returns the number of affected rows fir DELETE and UPDATE.


In case of multiple statements, mysql::exec returns a list of number
of affected rows.

MySQLTcl
Documentation

Tcl and TDBC

TDBC is an abstraction layer like JDBC

Run with:

tclsh tclEx.tcl

Docs are found Here:

http://www.xdobry.de/mysqltcl/mysqltcl.html

Database independent
MySQL Example:

package require tdbc::mysql


tdbc::mysql::connection create db1 -database accident_db -user root -password coursework
# Without preparing a statement:
db1 allrows {insert into person (driver_id, name) values ('ccvv44', 'Tommy')}
# Using a prepared statement
set stmt [db1 prepare { select * from person}]
set results [$stmt allrows]
foreach row $results {
foreach {col_name col_val} $row {
puts -nonewline [format "%-30s" "$col_name: $col_val"]
}
puts ""
}
# Delete the rows that I added
db1 allrows {delete from person where driver_id = 'ccvv44'}
db1 close

Tcl (Firebird via ODBC)

TclODBC

Need the following .odbc.ini file:


[employeedb]
Description =
Driver
=
Dbname
=
User
=
ReadOnly
=
NoWait
=
Dialect
=

package require tclodbc


database connect db {DSN=employeedb;user=SYSDBA;password=mypassword}
set a [db "select first_name, last_name from employee"]
foreach i $a {
puts [format "|%-20s | %-20s|" [lindex $i 0] [lindex $i 1]]
}

Run with:
tclsh tclfb.tcl

Employee Database
Firebird ODBC
localhost:/var/lib/firebird/2.5/data/employee.fdb
SYSDBA
No
No
3

Docs are found here (on Debian/Ubuntu machines):


/usr/share/doc/tclodbc

Tcl TDBC Example (MySQL)

Tcl8.6 only, which is not on your VM!

package require tdbc::mysql


tdbc::mysql::connection create db phonebook
set statement [db prepare {
select phone_num from directory
where first_name = :firstname and last_name = :lastname
}]
set firstname Fred
set lastname Flintstone
$statement foreach row {
puts [dict get $row phone_num]
}
$statement close
db close

PHP MySQL
Documentation

To run it:

Copy phpEx.php to WWW directory


point browser to

Docs are found Here:

http://csc.tntech.edu/~user/phpEx.php

http://php.net/mysql

PHP has firebird drivers, but I do not include examples. Docs are here:

http://php.net/manual/en/book.ibase.php

PHP (MySQL)
<?php
// Connecting, selecting database
$con = mysql_connect('host', 'user', 'password')
or die('Could not connect: ' . mysql_error());
echo 'Connected successfully';
mysql_select_db('mytestdb') or die('Could not select database');
// Performing SQL query
$query = 'select customers.lname, customers.fname, books.title ' .
'from customers, books, orders ' .
'where customers.id = orders.custId and books.id = ' .
'orders.bookId';
$result = mysql_query($query) or die('Query failed: ' .
mysql_error());
// Printing results in HTML
echo "<table border=\"1\">\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
mysql_free_result($result);
// Closing connection
mysql_close($con);
?>

PHP ADO Example


from w3schools.com
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="Site.css">
</head>
<body>
<div id="main">
<h1>Customers</h1>
<?php
//create an ADO connection and open the
// database
$conn = new COM("ADODB.Connection");
$conn->open("PROVIDER=Microsoft.Jet.OLEDB."
. "4.0;Data Source=C:\WebData\Northwind.mdb");
//execute an SQL statement and return
// a recordset
$rs = $conn->execute("SELECT CompanyName, City,
. " Country FROM Customers");
$num_columns = $rs->Fields->Count();

while (!$rs->EOF) //looping through the


// recordset (until End Of File)
{
"
echo "<tr>";
"
for ($i=0; $i < $num_columns; $i++) {
"
"
echo "<td>" . $rs->Fields($i)->value
. "</td>";
"
}
"
echo "</tr>";
"
$rs->MoveNext();
}
echo "</table>";
//close the recordset and the database
// connection
$rs->Close();
$rs = null;
$conn->Close();
$conn = null;
?>
<?php include("Footer.php"); ?>

echo "<table border='1'>";


echo "<tr><th>Name</th><th>City</th>
. "<th>Country</th></tr>";

</div>
</body>
</html>

Python MySQL
Documentation

Python (MySQL)
import sys
import MySQLdb
try:
conn = MySQLdb.connect (host = "localhost", user = "username",
passwd = "password", db = "mytestdb")
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit (1)
cursor = conn.cursor ()
cursor.execute ("select customers.lname, customers.fname, " +
"books.title from customers, books, orders where customers.id = " +
"orders.custId and books.id = orders.bookId")
while (1):
row = cursor.fetchone()
if row == None:
break
print "%s, %s, %s" % (row[0], row[1], row[2])

Run with:

Docs are found Here:

python pythonEx.py

http://mysql-python.sourceforge.net

Kinterbase for Firebird in Ubuntu repo does not work for Firebird 2.5, so
no examples.

MySQL/Ruby
Documentation

Ruby (MySQL)
require "mysql"
begin
dbh = Mysql.real_connect("localhost", "user",
"password", "mytestdb")
res = dbh.query("select customers.lname, customers.fname, " +
"books.title from customers, books, orders " +
"where customers.id = orders.custId and " +
"books.id = orders.bookId")
while row = res.fetch_row do
printf "%s, %s\n", row[0], row[1]
end
res.free
ensure
dbh.close if dbh
end

Run with:

Docs are found here:

ruby rubyEx.rb

http://www.tmtm.org/en/mysql/ruby/

Ruby Firebird drivers dont have a 64 bit version yet.

MySQL Connector/NET
Documentation

C# Mono Example (MySQL)


usingSystem;
usingSystem.Data;
usingMySql.Data.MySqlClient;
publicclassTest {
publicstaticvoidMain(string[] args) {
stringconnectionString = "Server=localhost;"+
"Database=mytestdb;"+ "User ID=userid;"+
"Password=mypassword;"+ "Pooling=false";
IDbConnection dbcon = newMySqlConnection(connectionString);
dbcon.Open();
IDbCommand dbcmd = dbcon.CreateCommand();
stringsql = "select customers.lname, customers.fname, "+
"books.title from customers, books, orders "+
"where customers.id = orders.custId and "+
"books.id = orders.bookId";
dbcmd.CommandText = sql;
IDataReader reader = dbcmd.ExecuteReader();
while(reader.Read()) {
stringFirstName = (string) reader["fname"];
stringLastName = (string) reader["lname"];
stringTitle = (string) reader["title"];
Console.WriteLine(FirstName + " "+ LastName + " "+ Title);
}
// clean up
reader.Close();
dbcmd.Dispose();
dbcon.Close();
}
}

Compile with:

Run with:

mono csharpEx.exe

Docs are found here:

dmcs csharpex.cs -r:System.Data.dll -r:/usr/lib/cli/MySql.Data-6.4/MySql.Data.dll

http://dev.mysql.com/doc/refman/5.0/en/connector-net.html

Firebird example left as an exercise for the reader :-)

C++ MySQL
#include <stdlib.h>
#include <iostream>
#include <mysql.h>
#include <stdio.h>
#define SERVER "localhost"
#define USER "root"
#define PASSWORD "coursework"
#define DATABASE "accident_db"
int main() {
MYSQL *connect;
connect=mysql_init(NULL);
if (!connect) {
std::cout<<"MySQL Initialization failed";
return 1;
}
connect=mysql_real_connect(connect, SERVER, USER, PASSWORD,
DATABASE ,0,NULL,0);
if (connect) {
std::cout<<"connection Succeeded\n";
} else {
std::cout<<"connection failed\n";
exit(1);
}
MYSQL_RES *res_set;
MYSQL_ROW row;
mysql_query (connect,"select * from person;");
unsigned int i =0;
res_set = mysql_store_result(connect);
unsigned int numrows = mysql_num_rows(res_set);
while ((row= mysql_fetch_row(res_set)) != NULL ) {
std::cout << row[i] << "\t";
std::cout << row[i+1] << std::endl;
}
mysql_close (connect);
return 0;
}

C++ MySQL

Compile it:

g++ -lmysqlclient -o tst -I/usr/include/mysql tst.cpp

Run it: ./tst


Documentation: http://dev.mysql.com/doc/refman/5.6/en/c-api.html
Good tutorial: http://zetcode.com/db/mysqlc/

C++ (Firebird)
#include <iostream>
#include <iomanip>
#include <ibpp.h>
int main() {
try {
IBPP::Database db = IBPP::DatabaseFactory("fritz", "employee", "userid", "password");
db->Connect();
IBPP::Transaction tr = IBPP::TransactionFactory(db);
tr->Start();
std::string fn, ln;
IBPP::Statement st = IBPP::StatementFactory(db, tr);
st->Execute("SELECT first_name, last_name FROM employee ORDER BY last_name");
while (st->Fetch()) {
st->Get(1, fn);
st->Get(2, ln);
std::cout << "|" << std::left << std::setw(20) << fn.c_str() << " | " <<
std::left << std::setw(20) << ln.c_str() << "|" << std::endl;
}
tr->Commit();
db->Disconnect();
} catch (IBPP::Exception& e) {
std::cout << e.ErrorMessage();
}
return 0;
}

IBPP Documentation

Compile with:

g++ -D<osflag> -libpp -o ex2 ex2.cpp


where <osflag> is IBPP_WINDOWS, IBPP_LINUX, or IBPP_DARWIN
On your VM, it looks like:

Run with:

./ex2

Docs are found here:

g++ -DIBPP_LINUX -o ex2 -lfbclient -libpp ex2.cpp

http://www.ibpp.org/reference

See the following for C++ MySQL examples:

http://dev.mysql.com/tech-resources/articles/mysql-connector-cpp.html

You might also like