- 这篇文章主要记录JDBC和MySQL的连接过程,包含完整代码,其余涉及到的内容略过。如果你有什么问题,欢迎留言。谢谢。
你应该测试Java环境和MySQL
假设你已经在Windows上搭建好Java开发环境和MySQL服务,没有问题(略过)
首先,Java连接MySQL需要驱动包
- https://dev.mysql.com/downloads/connector/j/
- 选择相应的Operating System后点击Download→然后No thanks, just start my download直接下载
- 解压后,文件夹mysql-connector-java-8.0.11内容如下(只会用到.jar包)
- 如果你使用了IDE,只需导入jar包
如果你使用文本编辑器,你需要将jar包的完整路径添加到系统环境变量CLASSPATH中(如D:\mysql-connector-java-8.0.11\ mysql-connector-java-8.0.11.jar)
创建数据库和数据表
create database test;
use test;
CREATE TABLE `websites` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` char(20) NOT NULL DEFAULT '' COMMENT '站点名称',
`url` varchar(255) NOT NULL DEFAULT '',
`alexa` int(11) NOT NULL DEFAULT '0' COMMENT 'Alexa 排名',
`country` char(10) NOT NULL DEFAULT '' COMMENT '国家',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
- 添加测试数据
INSERT INTO `websites` VALUES ('1', 'Google', 'https://www.google.cm/', '1', 'USA'), ('2', '淘宝', 'https://www.taobao.com/', '13', 'CN');
- 查看插入结果
JDBC 连接 MySQL 数据库的完整代码
- 数据库、用户名、密码记得自己修改!
- MySQLDemo.java(文件名必须和类名一致)
import java.sql.*;
public class MySQLDemo {
// JDBC Driver Name and Database URL
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/test?useSSL=false&useUncode=true&characterEncoding=utf8&serverTimezone=UTC";
// The database username and password need to be set according to their own
static final String USER = "root";
static final String PASS = "123456";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
// Registration JDBC Driver
Class.forName(JDBC_DRIVER);
// Open the link
System.out.println("Connect to the database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// Execute the query
System.out.println("Instantiate the Statement object...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, url FROM websites";
ResultSet rs = stmt.executeQuery(sql);
// Expand Result Set Database
while(rs.next()){
// Search through fields
int id = rs.getInt("id");
String name = rs.getString("name");
String url = rs.getString("url");
// Output Data
System.out.print("ID: " + id);
System.out.print(", Site name: " + name);
System.out.print(", Site URL: " + url);
System.out.print("\n");
}
// Close after completion
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
// Handle JDBC errors
se.printStackTrace();
}catch(Exception e){
// Handle Class.forName errors
e.printStackTrace();
}finally{
// Close resource
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}// nothing to do
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
- 编译运行
javac MySQLDemo.java
javac MySQLDemo
- 最后结果
如果有什么突然出现的问题,欢迎留言提问。谢谢。
报错和解决
- 编码GBK的不可映射字符
- 记事本打开java源文件,另存为时选择ANSI编码(发现本来的汉字都成了乱码,不过编译通过了)
- 也可以将中文全部改成英文,提高英语读写能力哈