提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- 一、mysql的安装
- 二、设计表
- 三、jdbc的运行
一、mysql的安装
下载安装包:
下载网址:
MySQL :: MySQL Community Downloads
二、设计表
在Navicat中设计
三、jdbc的运行
1.安装JDK及IDEA
(1)本文采用的工具为IDEA2019.2版本,JDK1.8版本,Mysql8.0.26版本
2.mysql下载安装及预处理
Mysql官网 https://dev.mysql.com/downloads/
从官网选择合适版本进行安装。
3.JDBC驱动下载
下载地址:https://static.runoob.com/download/mysql-connector-java-8.0.16.jar
文件名:mysql-connector-java-8.0.16.jar
4.链接数据库代码如下
package haonc;
import java.sql.*;
public class asdfkj {
static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/sys?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
// 数据库的用户名与密码,需要根据自己的设置
static final String USER = "root";
static final String PASS = "111111";
public static void main(String[] args){
Connection conn=null;
Statement stmt=null;
try{
//注册JDBC驱动
Class.forName(JDBC_DRIVER);
//打开链接
System.out.println("连接数据库...");
conn=DriverManager.getConnection(DB_URL,USER,PASS);
//执行查询
System.out.println("实例化Statement对象...");
stmt=conn.createStatement();
String sql;
sql="SELECT * FROM student";//数据库中的表名
ResultSet rs=stmt.executeQuery(sql);
//展开结果集数据库
while(rs.next()){
//通过字段检索
int no=rs.getInt("no");
String name=rs.getString("name");
String age=rs.getString("age");
String sex=rs.getString("sex");
//输出数据
System.out.print("no:"+no);
System.out.print(",姓名:"+name);
System.out.print(",年龄:"+age);
System.out.print("性别: "+sex);
System.out.print("\n");
}
//完成后关闭
rs.close();
stmt.close();
conn.close();
} catch (SQLException | ClassNotFoundException se) {
//处理前面JDBC错误和Class.forName 错误
se.printStackTrace();
}finally {
//关闭资源
try{
if (stmt!=null) stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try{
if(conn!=null)conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
System.out.println("连接数据库结束");
}
}