码迷,mamicode.com
首页 > 数据库 > 详细

JDBC basic

时间:2015-09-27 06:25:26      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:

http://www.tutorialspoint.com/jdbc/jdbc-sample-code.htm

maven

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>

example code

public class DBUtil {
    public static Connection getConnection() throws ClassNotFoundException,
            SQLException {
        // JDBC driver name and database URL
        final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
        final String DB_URL = "jdbc:mysql://127.0.0.1:3309/lily";

        // Database credentials
        final String USER = "root";
        final String PASS = "123";

        // Register JDBC driver
        // no need for JDBC 4+
        // Class.forName(JDBC_DRIVER);

        // Open a connection
        System.out.println("Connecting to database...");
        Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
        return conn;
    }

    public static void executeSelect(Connection conn) throws SQLException {
        System.out.println("Creating statement...");
        Statement stmt = conn.createStatement();
        String sql;
        sql = "SELECT id, username FROM users";
        ResultSet rs = stmt.executeQuery(sql);
        // Extract data from result set
        while (rs.next()) {
            // Retrieve by column name
            int id = rs.getInt("id");
            String username = rs.getString("username");

            // Display values
            System.out.print("ID: " + id);
            System.out.print(" username: " + username);
            System.out.println();
        }
        // Clean-up environment
        rs.close();
        stmt.close();
    }

    public static void main(String[] args) throws ClassNotFoundException,
            SQLException {
        Connection conn = getConnection();
        executeSelect(conn);

    }
}

 

JDBC basic

标签:

原文地址:http://www.cnblogs.com/phoenix13suns/p/4841755.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!