JDBC连接数据库
程序员文章站
2022-03-26 19:01:55
数据库驱动:如声卡、显卡一样,安装后需要驱动...
数据库驱动:如声卡、显卡一样,安装后需要驱动。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
本文地址:https://blog.csdn.net/qq_44859533/article/details/110959242