开发者

Database queries in Java

How can I connect to MySQL db and execute queries 开发者_StackOverflow社区?


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

}


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


jdbc-mysql


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜