- 先导入插件druid导入至maven中
- 配置需要导入的数据库,账号密码都正常填入,唯一需要注意的是url地址,因导入数据库包不同我们需要的代码段落不同,以为导入较新的包需要在后面添加时区的操作本例子使用亚洲上海时区
jdbc:mysql://localhost:3306/band24?serverTimezone=Asia/Shanghai
- 在java中进行mysql连接配置
ublic class MysqlDbUtil {
private static DruidDataSource dataSource=null;
private static void initDataSource() {
if (dataSource==null){
dataSource=new DruidDataSource();
dataSource.setUrl("jdbc:mysql://localhost:3306/band24?serverTimezone=Asia/Shanghai" +
"&useUnicode=true&characterEncoding=UTF-8");
dataSource.setUsername("root");
dataSource.setPassword("nianlan123");
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); //java依赖包
dataSource.setInitialSize(2);
dataSource.setMinIdle(2);
dataSource.setMaxActive(10);
dataSource.setMaxWait(20000); //20秒
dataSource.setTimeBetweenEvictionRunsMillis(20000);;
dataSource.setValidationQuery("SELECT'x'");
dataSource.setTestWhileIdle(true);
dataSource.setTestOnBorrow(true);
}
}
public static Connection getconnection()throws SQLException {
initDataSource();
return dataSource.getConnection();
}
}
- 新建测试目录在测试目录下对数据库增删改语句的修正与测试
例子用增加操作为例
@Test //测试注释
public void testInsert() {
try {
Connection conn = MysqlDbUtil.getconnection();
String sql = "insert into band(name,remark,status) value (?,?,?)";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, "我");
pst.setString(2, "班级信息");
pst.setByte(3, (byte)9);
int i = pst.executeUpdate();
pst.close();
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
-在数据库中查找是否有数据增加
by 本人初学,如有错误还望指出
多学多做,一路前行