前言:java、maven等已安装好。
1、在maven的pom.xml文件中添加依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
1.1添加后会自动下载jar包,如果不自动下载,设置eclipse--window--show view --other 如下图
1.2 添加索引
1.3 右键项目,选maven--add dependency 就可以直接下载想要的jar到maven项目了。
2、java jdbc连接 mysql 测试
2.1数据库建表:
CREATE TABLE t_student
(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
age INT(11) NOT NULL
);
INSERT INTO t_student VALUES(NULL,'大宇',22),(NULL,'小宇',20),(NULL,'小黄',30);
2.2 代码
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcUtil {
public static void main(String[] args) {
// 声明Connection对象
Connection con;
// 驱动程序名
String driver = "com.mysql.cj.jdbc.Driver";
// URL指向要访问的数据库名 test
String url = "jdbc:mysql://localhost:3306/mysql?useUnicode=true&characterEncoding=utf8"
+ "&useSSL=false&serverTimezone=Hongkong";
// MySQL配置时的用户名
String user = "root";
// MySQL配置时的密码
String password = "root";
// 遍历查询结果集
try {
// 加载驱动程序
Class.forName(driver);
System.out.println("driver success");
// 1.getConnection()方法,连接MySQL数据库!!
con = DriverManager.getConnection(url, user, password);
if (!con.isClosed())
System.out.println("\n\t\t成功以 " + user + " 身份连接到数据库!!!");
// 2.创建statement类对象,用来执行SQL语句!!
Statement statement = con.createStatement();
// 要执行的SQL语句
String sql = "select * from t_student";
// 3.ResultSet类,用来存放获取的结果集!!
ResultSet rs = statement.executeQuery(sql);
System.out.println("\n\t\t执行结果如下所示:");
System.out.println("\t\t-----------------------------------------------------------------");
System.out.println("\t\t|\t" + "ID" + "\t" + "姓名" + "\t" + "年龄");
System.out.println("\t\t-----------------------------------------------------------------");
int ID = 0;
String Name = null;
String Sex = null;
int Age = 0;
String Phone = null;
String Address = null;
while (rs.next()) {
// 获取 ID 这列数据
ID = rs.getInt("ID");
// 获取 Name 这列数据
Name = rs.getString("Name");
// 获取 Age 这列数据
Age = rs.getInt("Age");
// 输出结果
System.out.println("\t\t|\t" + ID + "\t" + Name + "\t" + Age +"\t|\t\t");
}
System.out.println("\t\t-----------------------------------------------------------------");
rs.close();
con.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("\t\t\t\t\t\t\t\t获取数据库数据完毕!!!");
}
}
}