Robert Harker Technical Wiki
Thoughts and Ideas About Large Sites

[ Prev ] [ Index ] [ Next ]


newSQL: distributed MySQL in memory

MySQL Python and Java code examples

Python

Python script using the _mysql library to create and populate a database and then select some rows.

import _mysql

conn = _mysql.connect(host='127.0.0.1', user='root')
conn.query('DROP DATABASE IF EXISTS MemSQL_tutorial2')
conn.query('CREATE DATABASE MemSQL_tutorial2')
conn.select_db('MemSQL_tutorial2')
conn.query('CREATE TABLE t(id INT PRIMARY KEY AUTO_INCREMENT, v VARCHAR(10) NOT NULL)')
conn.query('INSERT INTO t (v) VALUES ("hello"), ("goodbye")')
conn.query('SELECT * FROM t')
result = conn.use_result()

row = result.fetch_row()
while row:
print row
row = result.fetch_row()

Assuming the above code is saved to a file called example.py, running the program on Linux would look like this:

$ python example.py
(('1', 'hello'),)
(('2', 'goodbye'),)

This program might take up to a minute to run, as optimized code needs to be generated and compiled for the database and queries to run the first time.

Java

In the following example we write the same code in Java and use the MySQL JDBC driver to connect to MemSQL:

import java.sql.*;

public class JDBCExample {
public static void main(String[] argv) {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return;
}

Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/memsql", "root", "");
Statement stmt = connection.createStatement();
stmt.execute("DROP DATABASE IF EXISTS MemSQL_tutorial2")
stmt.execute("CREATE DATABASE MemSQL_tutorial2");
stmt.execute("use MemSQL_tutorial2");
stmt.execute("CREATE TABLE t(id INT PRIMARY KEY AUTO_INCREMENT, v VARCHAR(10) NOT NULL)");
stmt.execute("INSERT INTO t (v) VALUES ('hello'), ('goodbye')");
ResultSet rs = stmt.executeQuery("SELECT * FROM t");
while (rs.next())
{
System.out.println("(('" + rs.getInt("id") + "', '" + rs.getString("v") + "'),)");
}
} catch (SQLException e) {
System.out.println("Failed to make connection!");
e.printStackTrace();
return;
}
}
}

Assuming the above code is saved to a file called JDBCExample.java, running the program on Linux would look like this:

$ javac JDBCExample.java
$ java JDBCExample
(('1', 'hello'),)
(('2', 'goodbye'),)


Backlinks: Start
Created with Zim desktop wiki