Java基础-JDBC连接测试

来源:互联网 发布:depthmap软件计算 编辑:程序博客网 时间:2024/05/20 02:28

Demo地址

test_JDBC

创建数据库

DROP TABLE IF EXISTS `role`;CREATE TABLE `role` (  `id` int(11) NOT NULL,  `rolename` varchar(20) default NULL,  `note` varchar(100) default NULL,  PRIMARY KEY  (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;insert  into `role`(`id`,`rolename`,`note`) values (1,'超级管理员','admin'),(2,'管理员','yw'),(4,'管理员','yt'),(5,'管理员','zrh'),(6,'管理员','yp'),(8,'管理员','yyr');

Maven依赖

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

Java类:JDBCExample

//STEP 1. Import required packagesimport java.sql.*;public class JDBCExample {    // JDBC driver and database URL    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";    static final String JDBC_URL = "jdbc:mysql://localhost/mysql";    // database credentials    static final String USER = "root";    static final String PASS = "mysql";    public static void main(String[] args) {        Connection conn = null;        Statement stmt = null;        try {            // STEP 2: Register JDBC driver            Class.forName(JDBC_DRIVER);            // STEP 3: Open a connection            System.out.println("Connecting to database...");            conn = DriverManager.getConnection(JDBC_URL, USER, PASS);            System.out.println("Success!");            // STEP 4: Execute a query            System.out.println("Creating statement...");            stmt = conn.createStatement();            System.out.println("Success!");            String sql;            sql = "select * from role";            ResultSet rs = stmt.executeQuery(sql);            // STEP 5: Extract data from result set            System.out.println("Handling datas...");            while (rs.next()) {                int id = rs.getInt("ID");                String roleName = rs.getString("roleName");                String note = rs.getString("note");                System.out.println("id:" + id);                System.out.println("name:" + roleName);                System.out.println("remark:" + note);            }            System.out.println("Success!");            // STEP 6: Clean-up environment            rs.close();            stmt.close();            conn.close();        } catch (Exception e) {            e.printStackTrace();        } finally {            // STEP 7:Close resources            try {                if (stmt != null) {                    stmt.close();                }                if (conn != null) {                    conn.close();                }            } catch (Exception e2) {                e2.printStackTrace();            }        }    }}

测试结果

这里写图片描述

0 0
原创粉丝点击