JDBC Day1
今日一图
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 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步