本章节我们为大家介绍 Java 如何使用 使用 JDBC 连接 MySQL 数据库。
Java 连接 MySQL 需要驱动包,最新版下载地址为:http://dev.mysql.com/downloads/connector/j/,解压后得到jar库文件,然后在对应的项目中导入该库文件。
你可以下载本站提供的 jar 包:mysql-connector-java-5.1.39-bin.jar
加载驱动
1. 在工程目录中创建lib文件夹,将下载好的JDBC放到该文件夹下。
2. 右键工程名,在java build path中的Libraries分页中选择Add JARs...,选择刚才添加的JDBC
首先我们先创建一个数据库
CREATE TABLE `byc` (
`id` int(11) not null auto_increment,//自增
`name` char(20) not null default '' comment '出现错误',
//出现空值的情况 comment备注
primary key (`id`)//设置主键id
)engine=InnoDB default charset=utf8;
并且向里面添加5组数值
insert into `byc` values ('1','byc'),('2','zyz'),('3','wj'),('4','lxg'),('5','xjh');
JDBC驱动以及数据库的路径 URL
jdbc:mysql://固定写法
localhost(本地服务器)可以根据服务器的具体地址而定,比如云服务器的ip地址
3306连接服务器的端口,也可以自己设置更改
test数据库名称
// JDBC 驱动名及数据库 URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/test";
设置连接数据库的用户名和密码
// 数据库的用户名与密码,需要根据自己的设置
static final String USER = "root";
static final String PASS = "root";
// 注册 JDBC 驱动
Class.forName("com.mysql.jdbc.Driver")
//声明Connection对象
Connection con;
//驱动程序名
String driver = "com.mysql.jdbc.Driver";
//加载驱动程序
Class.forName(JDBC_DRIVER);
//1.getConnection()方法,连接MySQL数据库!!
con = DriverManager.getConnection(DB_URL,USER,PASS);
创建statement类对象,用来执行SQL语句!!
//2.创建statement类对象,用来执行SQL语句!!
Statement statement = con.createStatement();
String sql用于选择数据库中的数据表websites
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, url FROM websites";
ResultSet类,用来存放获取的结果集!! ResultSet rs = statement.executeQuery(sql);
/展开结果集数据库
// 展开结果集数据库
while(rs.next()){
// 通过字段检索
int id = rs.getInt("id");
String name = rs.getString("name");
String url = rs.getString("url");
// 输出数据
System.out.print("ID: " + id);
System.out.print(", 站点名称: " + name);
System.out.print(", 站点 URL: " + url);
System.out.print("\n");
}
// 完成后关闭
rs.close();
stmt.close();
conn.close();
数据库驱动类异常处理
catch(ClassNotFoundException e) {
//数据库驱动类异常处理
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
}
catch(SQLException e) {
//数据库连接失败异常处理
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println("数据库数据成功获取!!");
}
注意数据库的操作在try{}--catch{}中进行
完整的代码输出
import java.sql.*;
public class Main {
// JDBC 驱动名及数据库 URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/test";
// 数据库的用户名与密码,需要根据自己的设置
static final String USER = "root";
static final String PASS = "root";
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection conn = null;
Statement stmt = null;
try{
// 注册 JDBC 驱动
Class.forName("com.mysql.jdbc.Driver");
// 打开链接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 执行查询
System.out.println(" 实例化Statement对象...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, url FROM websites";
ResultSet rs = stmt.executeQuery(sql);
// 展开结果集数据库
while(rs.next()){
// 通过字段检索
int id = rs.getInt("id");
String name = rs.getString("name");
String url = rs.getString("url");
// 输出数据
System.out.print("ID: " + id);
System.out.print(", 站点名称: " + name);
System.out.print(", 站点 URL: " + url);
System.out.print("\n");
}
// 完成后关闭
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
// 处理 JDBC 错误
se.printStackTrace();
}catch(Exception e){
// 处理 Class.forName 错误
e.printStackTrace();
}finally{
// 关闭资源
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}// 什么都不做
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("数据输出完成");
}
}