您的位置:首页 > 编程语言 > Java开发

Java基础-JDBC连接测试

2017-01-13 17:30 537 查看

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


测试结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java