JDBC连接数据库

数据库驱动:如声卡、显卡一样,安装后需要驱动。Java连接数据库时候需要下载驱动
1、驱动jar包下载
链接:https://pan.baidu.com/s/1vZNwxkKipaUvOJ_Hn4j2fQ
提取码:zwzs

2、导入jar包
在这里插入图片描述
目录名为:lib
在这里插入图片描述
导入包
在这里插入图片描述
接下来创建数据库:
在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
最后编写Java代码连接:

package JDBC;

import java.sql.*;

public class Demo1 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        //加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //用户信息和URL
        String url="jdbc:mysql://localhost:3306/jdbcstudent?useUnicode=true&useSSL=true&characterEncoding=utf8&serverTimezone=GMT%2B8";
        String username="root";
        String password="123456";
        //连接成功,数据库对象
        Connection connection=DriverManager.getConnection(url,username,password);
        //执行sql对象
        Statement statement=connection.createStatement();
        String sql="select * from users";
        ResultSet resultSet=statement.executeQuery(sql);
        while (resultSet.next()){
            System.out.println("id="+resultSet.getObject("id"));
            System.out.println("name="+resultSet.getObject("name"));
            System.out.println("password="+resultSet.getObject("password"));
            System.out.println("birthday="+resultSet.getObject("birthday"));
        }
        //释放连接
        resultSet.close();
        statement.close();
        connection.close();
    }
}

注意: 1、若是版本低的MySQL文件安装版本高的驱动程序:需要加 .cj

//加载驱动
        Class.forName("com.mysql.cj.jdbc.Driver");

2、若是运行出现这个错误:

Exception in thread "main" java.sql.SQLException: The server time zone value '�й���׼ʱ��' is unrecognized 
or represents more than one time zone. You must configure either the server or JDBC driver (via the 'serverTimezone'
 configuration property) to use a more specific time zone value if you want to utilize time zone support.

只需要: 在URL中加入 &serverTimezone=GMT%2B8

运行结果如下:

id=1
name=zhangsan
password=123456
birthday=1980-12-04
id=2
name=lisi
password=123456
birthday=1981-12-04
id=3
name=wangwu
password=123456
birthday=1979-12-04
  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我菜就爱学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值