oneat
oneat

Reputation: 10994

Connect to MySQL and run database queries in Java

How can I connect to a MySQL DB and execute queries?

Upvotes: 0

Views: 2503

Answers (4)

S1LENT WARRIOR
S1LENT WARRIOR

Reputation: 12214

You can try MySQL JDBC Utilities API for MySQL connectivity in java.

Upvotes: 0

rsilva4
rsilva4

Reputation: 1955

...if you really are going to use java to query a MySql server you should look further and read some about JDBC, ORM, transactions and how this concepts will help you using a database.

You can use JDBC to query an Mysql database, and virtually any other DBMS who have an JDBC driver implemented.

An ORM system provides the programmer with a layer between Objects and Database and makes all the hard work for you (in theory).

Even with the previous point you really need to have some basic knowledge about transactions, that encapsulates your actions in one atomic unit that only executes completely or does not execute at all.

Upvotes: 1

Adam Morris
Adam Morris

Reputation: 8545

First get your JDBC driver, such as mysql's Connector/J - add the jar to your project. Then, you can access a database like:

public class mysqlTest {

public static void main(String[] args) {
    String driver = "com.mysql.jdbc.Driver";
    String protocol = "jdbc:mysql://localhost/";
    String database = "database";
    String username = "mysqlUsername";
    String password = "mysqlPassword";

    Properties props = new Properties();
    props.put("user", username);
    props.put("password", password);

    Connection conn;
    Statement s;
    ResultSet rs;

    String createTableStatment = "CREATE TABLE test ( `id` INTEGER NOT NULL)";
    String insertStatment = "INSERT INTO test VALUES(1)";
    String selectQuery = "SELECT * FROM test";

    try {
        Class.forName(driver).newInstance();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    try {
        conn = DriverManager.getConnection(protocol + database,props);
        conn.setAutoCommit(true);
        s = conn.createStatement();
        s.execute(createTableStatment);
        s.execute(insertStatment);
        rs = s.executeQuery(selectQuery);
        while (rs.next()){
            System.out.println("id = "+rs.getString("id"));
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

}

Upvotes: 5

Vishal
Vishal

Reputation: 20627

jdbc-mysql

Upvotes: 1

Related Questions