jdbc mysql 偶发空指针_JDBC 进阶:使用封装通用DML DQL 和结构分层以及at com.mysql.jdbc.PreparedStatement.setTimestamp空指针异常解...

博客介绍了在使用JDBC连接MySQL时遇到的偶发空指针异常,特别是在PreparedStatement.setTimestamp方法上。通过升级到5.1.48版本的驱动包解决了这个问题。此外,文章还展示了如何搭建数据库分层结构,包括配置文件、工具类、POJO类、DAO接口和实现、业务层接口和实现。整个过程旨在封装通用的DML和DQL操作,以提高代码复用性和可维护性。
摘要由CSDN通过智能技术生成

准备:

数据表

CREATE TABLE `t_user` (

`id` int(11) NOT NULL AUTO_INCREMENT,

`username` varchar(10) DEFAULT NULL,

`pwd` varchar(10) DEFAULT NULL,

`regTime` date DEFAULT NULL,

`lastLoginTime` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,

PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=20227 DEFAULT CHARSET=utf8;

9ea28fb2ffa9d1e8a63a551bbc8888a7.png

jar包:

9e9432ce080b2a53910a7dfb39c56b80.png

注意! 我这里使用的驱动包时5.1.48

如果使用了5.1.47会有个setTimestamp的空指针异常,网上有大神建议回退到5.1.46;

不过新版本出来了,我这边就使用新版本了。

这个bug MySQL官网有说明

[6 Jul 2019 0:44] Daniel So

Posted by developer:

Added the following entry to the Connector/J 5.1.48 changelog:

"PreparedStatement.setTimestamp threw a NullPointerException if getParameterMetaData() was called before the statement was executed. This fix adds the missing null checks to getParameterMetaData() to avoid the exception."

搭建分层结构

c4eed0ced56687f34ba0907f023eaa14.png

编写配置文件

driver = com.mysql.jdbc.Driver

jdbcUrl = jdbc:mysql://localhost:3306/testjdbc?useSSL=false

username = root

userpassword = 123456

编写工具类

package com.xzlf.commons;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ResourceBundle;

public class JdbcUtil {

private static String driver;

private static String jdbcUrl;

private static String username;

private static String userpassword;

static {

// 读取properties 文件

ResourceBundle bundle = ResourceBundle.getBundle("jdbc");

driver = bundle.getString("driver");

jdbcUrl = bundle.getString("jdbcUrl");

username = bundle.getString("username");

userpassword = bundle.getString("userpassword");

try {

Class.forName(driver);

} catch (ClassNotFoundException e) {

e.printStackTrace();

}

}

/**

* 获取connection 对象

* @return

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值