花开堪折直须折,莫待无花空折枝。|

Indullged

园龄:6年粉丝:4关注:14

JDBC Day1

今日一图

image

2022年1月7日

JDBC链接

注意
首先是系统安全性和时区配置的问题,MySQL8.0不同于之前的版本,存在安全检测的问题,所以在设置url的时候需要

jdbc:mysql://localhost:3306/database?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true

之前的版本由于是不收费版本所以没有安全性设置,只需要
jdbc:mysql://localhost:3306/database即可
其次是;jdbc版本原因、
Driver driver =new com.mysql.jdbc.Driver();这样子不太行,会提示版本过低;
改成Driver driver =new com.mysql.cj.jdbc.Driver();

经典方法

静态代码快
public void testConnection() throws ClassNotFoundException, NoSuchMethodException, SQLException, InvocationTargetException, InstantiationException, IllegalAccessException {
//获取实现类对象,获取driver;
Class clazz= Class.forName("com.mysql.cj.jdbc.Driver"); //默认加载了静态代码块,mysql可以省略
//Driver driver = (Driver) clazz.getDeclaredConstructor().newInstance();
// 注册驱动
//DriverManager.registerDriver(driver);
String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true";
Connection conn = DriverManager.getConnection(url,"root","2486");
System.out.println(conn);
}

最终方法:

配置文件:

user=root
password=2486
url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
driver=com.mysql.cj.jdbc.Driver
#获取配置文件
public void testConnection5() throws SQLException, ClassNotFoundException, IOException {
// read the propetries类加载器
InputStream is = Main.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties pros =new Properties();
pros.load(is);
String user=pros.getProperty("user");
String password=pros.getProperty("password");
String url=pros.getProperty("url");
String driver =pros.getProperty("driver");
//加载驱动
Class.forName(driver);
//获取链接
Connection conn = DriverManager.getConnection(url,user,password);
System.out.println(conn);
}

数据库链接基本信息: 驱动,数据库url,用户名密码,基本信息

优点

1‘配置和数据代码分离,提高可移植性,解耦,高内聚低耦合。
2’修改配置信息不需要重新打包程序,(炸包)

Preapare Statement

本文作者:Indullged

本文链接:https://www.cnblogs.com/mcxw/p/15774326.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Indullged  阅读(29)  评论(3编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起