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
import java.sql.*;
public class JDBCExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String JDBC_URL = "jdbc:mysql://localhost/mysql";
static final String USER = "root";
static final String PASS = "mysql";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName(JDBC_DRIVER);
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(JDBC_URL, USER, PASS);
System.out.println("Success!");
System.out.println("Creating statement...");
stmt = conn.createStatement();
System.out.println("Success!");
String sql;
sql = "select * from role";
ResultSet rs = stmt.executeQuery(sql);
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!");
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
测试结果