Java基础-JDBC连接测试

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

测试结果

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值