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 application 应用程序 使用JDBC proxool 两种方式连接数据库 测试程序代码
- java基础视频下载(三) jdbc_java连接数据库[天一时代
- Java_jdbc 基础笔记之四 数据库连接 (通用更新方法)
- Java_jdbc 基础笔记之十四 数据库连接(元数据)
- Java_jdbc 基础笔记之八 数据库连接(写一个查询Student对象的方法)
- java application应用程序 使用JDBC和proxool两种方式连接数据库 的测试程序代码
- 关于java基础--SQL驱动及JDBC连接
- Java_jdbc 基础笔记之五 数据库连接 (ResultSet)
- Java_jdbc 基础笔记之一 数据库连接
- Java_jdbc 基础笔记之十二 数据库连接 (beanutils )
- Java基础代码库:JDBC连接MySQL
- MyEclipse使用Java 通过JDBC连接MySQL数据库的基本测试
- MyEclipse使用Java 通过JDBC连接MySQL数据库的基本测试
- Java_jdbc 基础笔记之六 数据库连接 (PreparedStatement)
- java.lang.ClassNotFoundException: com.microsoft.jdbc.sqlserver.SQLServerDriver Eclipse3.1 数据库连接测试程序(SQL Server 2000 Driver for JDBC Service Pack 3 安装测试)
- java学习:weblogic下JNDI及JDBC连接测试(weblogic环境)
- JDBC-----基础--Java如何连接oracle
- java连接SQL server 2005(jdbc)(已测试成功)
- Java_jdbc 基础笔记之九 数据库连接 (查询Customer对象的方法)
- Java_jdbc 基础笔记之七 数据库连接(方法升级)