Posts Tagged ‘MySQL’

Easy JDBC using Spring

29 August 2009

Spring has a well-written module for JDBC. We’ll use it to produce clean code for our application in 10 minutes.

Click here to read more…

JDBC σε 10 λεπτά

8 January 2009

Ας αποθηκεύσουμε άτομα στην βάση. Για κάθε άτομο μας ενδιαφέρει το όνομα, η ηλικία και ένας μοναδικός αριθμός (κλειδί).

Για τον σκοπό αυτό θα φτιάξουμε ακριβώς τρεις κλάσεις: Την Connector η οποία διαχειρίζεται τις συνδέσεις με την βάση, την Person που απεικονίζει ένα άτομο και την PersonHandler η οποία διαχειρίζεται τα άτομα ως προς την βάση (εισάγει, διαγράφει κλπ).

Το μοντέλο

Πρόκειται για ένα απλό javabean που περιέχει τις πληροφορίες που μας ενδιαφέρουν.

public class Person {
    private String name;
    private int age;
    private int id;

    // getters and setters
}

Η βάση δεδομένων

Για να φτιάξεις τη βάση στην MySQL γράψε διαδοχικά.

create database hello;
use hello;
CREATE TABLE persons (name VARCHAR(255),
age SMALLINT, id BIGINT AUTO_INCREMENT, primary key (id));

Για περισσότερες πληροφορίες μπορείς να δεις εδώ.

Κατέβασε τον JDBC driver της MySQL από το mysql.com > downloads > Connectors > Connector/J > Source and Binaries (zip) > Pick a mirror > No thanks, just take me to the downloads > Greece [National Technical University of Athens] HTTP > mysql-connector-java-5.1.7.zip. Μέσα στο zip υπάρχει το mysql-connector-java-5.1.7-bin.jar, το οποίο θα μπει στο classpath του project.

Xρειαζόμαστε μια βολική κλάση η οποία θα μπορεί να συνδέεται και αποσυνδέεται. Να λοιπόν πώς συνδεόμαστε,

/**
 * Επιστρέφει μια σύνδεση με την βάση.
 * Φορτώνουμε τον JDBC driver, του δίνουμε
 * το username και password, καθώς και το url
 * της βάσης δεδομένων.
 */
public static Connection getConnection() throws Exception {
    Connection result = null;
    Class.forName("com.mysql.jdbc.Driver");
    String user = "nikos";
    String pass = "12345";
    String url = "jdbc:mysql://127.0.0.1/hello";
    result = DriverManager.getConnection(url, user, pass);
    result.setAutoCommit(false);
    return result;
}

και να πώς αποσυνδεόμαστε.

/**
 * Αποσυνδέεται από τη βάση.
 */
public static void disconnect(PreparedStatement statement,
    ResultSet set, Connection connection) throws Exception {
    if (statement != null) {
        statement.close();
    }
    if (set != null) {
        set.close();
    }
    if (connection != null) {
        connection.close();
    }
}

Αυτές λοιπόν οι δύο μέθοδοι ανήκουν στην κλάση Connector.

Εισαγωγή (insert)

Για να βάλουμε δεδομένα στη βάση, συνδεόμαστε καταρχήν μαζί της. Έπειτα προετοιμάζουμε την πρόταση SQL και την γεμίζουμε με τις τιμές από το javabean. Αφού εκτελέσουμε και πάρουμε το αποτέλεσμα, κλείνουμε την σύνδεση.

public boolean insert(Person person) throws Exception {
    boolean result = false;
    Connection connection = null;
    PreparedStatement statement = null;
    String sql = "INSERT INTO persons(name, age) VALUES(?, ?)";
    try {
        // Σύνδεση
        connection = Connector.getConnection();
        // Προετοιμασία
        statement = connection.prepareStatement(sql);
        statement.setString(1, person.getName());
        statement.setInt(2, person.getAge());
        // Εκτέλεση
        if (statement.executeUpdate() == 1) {
            result = true;
            connection.commit();
        }
    } catch (Exception e) {
        connection.rollback();
        throw e;
    } finally {
        // Αποσύνδεση
        Connector.disconnect(statement, null, connection);
    }
    return result;
}

Προσέξτε την πρόταση SQL, η οποία περιέχει ερωτηματικά: “INSERT INTO persons(name, age) VALUES(?, ?)”. Πρόκειται για ένα PreparedStatement.

Επιλογή (select)

public Person select(int id) throws Exception {
    Person person = null;
    ResultSet set = null;
    Connection connection = null;
    PreparedStatement statement = null;
    String sql = "SELECT * FROM persons WHERE id = ?";
    try {
        // Σύνδεση
        connection = Connector.getConnection();
        // Προετοιμασία
        statement = connection.prepareStatement(sql);
        statement.setInt(1, id);
        // Εκτέλεση
        set = statement.executeQuery();
        if (set.next()) {
            person = new Person();
            person.setName(set.getString("name"));
            person.setAge(set.getInt("age"));
            person.setId(set.getInt("id"));
        }
    } finally {
        // Αποσύνδεση
        Connector.disconnect(statement, set, connection);
    }
    return person;
}

Αλλαγή (update)

public boolean update(Person person) throws Exception {
    boolean result = false;
    Connection connection = null;
    PreparedStatement statement = null;
    String sql = "UPDATE persons SET name = ?, age = ? WHERE id = ?";
    try {
        // Σύνδεση
        connection = Connector.getConnection();
        // Προετοιμασία
        statement = connection.prepareStatement(sql);
        statement.setString(1, person.getName());
        statement.setInt(2, person.getAge());
        statement.setInt(3, person.getId());
        // Εκτέλεση
        if (statement.executeUpdate() == 1) {
            result = true;
            connection.commit();
        }
    } catch (Exception e) {
        connection.rollback();
        throw e;
    } finally {
        // Αποσύνδεση
        Connector.disconnect(statement, null, connection);
    }
    return result;
}

Διαγραφή (delete)

public boolean delete(int id) throws Exception {
    boolean result = false;
    Connection connection = null;
    PreparedStatement statement = null;
    String sql = "DELETE FROM persons WHERE id = ?";
    try {
        // Σύνδεση
        connection = Connector.getConnection();
        // Προετοιμασία
        statement = connection.prepareStatement(sql);
        statement.setInt(1, id);
        // Εκτέλεση
        if (statement.executeUpdate() == 1) {
            result = true;
            connection.commit();
        }
    } catch (Exception e) {
        connection.rollback();
        throw e;
    } finally {
        // Αποσύνδεση
        Connector.disconnect(statement, null, connection);
    }
    return result;
}

Επανάληψη

Το JDBC είναι στρωτό:

  1. Σύνδεση.
  2. Προετοιμασία πρότασης SQL.
  3. Εκτέλεση και επιστροφή του αποτελέσματος.
  4. Αποσύνδεση.

Uses of mysqladmin with a remote server

6 January 2009

This is how you can use the mysqladmin tool with a remote MySQL server.

Assume MySQL is installed on 172.22.128.25, and user remote with password 12345 on your current host has been granted the necessary rights.

Ping

mysqladmin -h 172.22.128.25 ping --user=remote --password=12345

Get status

mysqladmin -h 172.22.128.25 status --user=remote --password=12345

Get version

mysqladmin -h 172.22.128.25 version --user=remote --password=12345

Create a database

mysqladmin -h 172.22.128.25 create logdb --user=remote --password=12345

Drop a database

mysqladmin -h 172.22.128.25 drop logdb --user=remote --password=12345

MySQL commands for a developer

4 January 2009

This is a reference of some common MySQL commands useful to a developer.

Start the server

MySQL should be installed as a service. However, if it’s set to manual you may start it with:

mysqld-nt --console

Stop the server

mysqladmin -u root -p shutdown

Login

Just use the entry in the Start menu.

Start → Programs → MySQL → MySQL server 5.0 → MySQL Command Line Client

Even better, if the bin folder of the MySQL installation is in the path you may simply type

mysql -u root -p

List database schemas

show databases;

Add a schema

CREATE DATABASE fcom;

Delete a schema

DROP DATABASE fcom;

Select the current schema

USE fcom;

List available tables

show tables;

Add a table

INSERT TABLE clients (c_id INT AUTO_INCREMENT, c_name VARCHAR(50),
    c_address VARCHAR(200), c_tel VARCHAR(20), PRIMARY KEY(c_id));

Delete a table

DROP TABLE clients;

Add an account

GRANT ALL PRIVILEGES ON fcom.* TO 'george'@'localhost'
IDENTIFIED BY 'mypass' WITH GRANT OPTION;

Where fcom is the database schema this user may access, george is the username and mypass is the password. Note that the username is explicitly associated with a host. This command grants privileges to george, only when he logins from the same computer as the MySQL instance.

Show privileges of an account

SHOW GRANTS FOR 'george'@'localhost';

Delete an account

DROP USER 'george'@'localhost';

References

Copy a database to another MySQL instance

11 November 2008

We want to copy a whole database along with its tables and data to another MySQL instance.

The database is called bank_development.

In the source machine

mysqldump -u root -p bank_development > ayo.sql

Take the file ayo.sql to the target machine.

In the target machine

Start the MySQL client from the same folder with ayo.sql.

mysql -u root -p

Create the database schema,

CREATE DATABASE bank_development;

use it,

use bank_development;

and make the actual migration.

source ./ayo.sql

That’s it!

Review

This is a comfortable way for a developer to move/copy/backup his database.