views:

105

answers:

4

How can I connect to MySQL db and execute queries ?

+2  A: 

http://dev.mysql.com/usingmysql/java/

This should probably be migrated to stackoverflow.

skarface
+2  A: 

...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.

rsilva
Stupid answer. You don't add any value, and moreover you think you are funny with it. Questions from StackOverflow are in the first pages in Google searches. The point is to have actually an answer, not another google search. If you don't have anything to answer, then just say nothing. See this question on the meta site for more information: http://meta.stackoverflow.com/questions/8724/how-to-deal-with-google-questions
Gnoupi
ok, i see your point. My apologies. Let's try that again.
rsilva
@rsilva - Much better indeed. Thanks for improving that answer.
Gnoupi
+1  A: 

jdbc-mysql

Vishal
+3  A: 

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();
    }
}

}

Adam