首页 > 数据库技术 > 详细

JDBC basic

时间:2015-09-27 06:24:08      阅读:197      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!