JavaWeb购物系统(十一)购物系统-连接数据库(Mysql、sqlServer、Access的匹配方案)

我们推荐使用的是连接Mysql,因为我的购物系统就是在Mysql环境下测试的。当然在最后,我也对sqlServerAccess的连接做了一些测试,但可能得修改业务相关的sql语句,因为不同的数据库管理系统厂商对sql支持不同。

至于为什么要做不同数据库的匹配:当然是有的学校必须得用sqlServerAccess

正文

Mysql

使用德鲁伊数据库连接池apache.dbutils工具类

JdbcUtil

package com.myUtil;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JdbcUtil {
    private static ThreadLocal<Connection> threadLocalConn = new ThreadLocal<>();
    private static DataSource ds;
    static {
        Properties properties = new Properties();
        try {
            properties.load(JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    public static Connection getConnection() {
        Connection connection = threadLocalConn.get();
        if (connection==null){
            try {
                // 得到连接
                connection = ds.getConnection();
                // 关闭自动提交
                connection.setAutoCommit(false);
                threadLocalConn.set(connection);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }

    /**
     * 事务的提交
     */
    public static void commit(){
        Connection connection = threadLocalConn.get();
        if (connection != null){
            try {
                connection.commit();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }finally {
                try {
                    connection.close(); // 关闭连接
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        // 提交之后将connection从ThreadLocal清除掉
        threadLocalConn.remove();
    }

    /**
     * 回滚/撤销connection管理的dml等操作
     */
    public static void rollback(){
        Connection connection = threadLocalConn.get();
        if (connection!=null){
            try {
                connection.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }finally {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        threadLocalConn.remove();
    }
    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        if (resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (statement != null){
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }


}

BasicDao

package com.dao;
import com.myUtil.JdbcUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public class BasicDao<T> {
    private QueryRunner qr = new QueryRunner();
        public Boolean dmlData(String sql,Object... parameters){
            Connection connection = null;
            try {
                connection = JdbcUtil.getConnection();
                int update = qr.update(connection, sql, parameters);
                if (update>0){
                    return true;
                }else {
                    return false;
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                JdbcUtil.close(null,null,null);
            }
        }
        public List<T> queryMulti(String sql, Class<T> clazz, Object... parameters){
            Connection connection = null;
            try {
                connection = JdbcUtil.getConnection();
                List<T> query = qr.query(connection, sql, new BeanListHandler<>(clazz), parameters);
                return  query;
            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                JdbcUtil.close(null,null,null);
            }
        }

        /**
         *
         * @param sql
         * @param clazz
         * @param parameters
         * @return 一行数据
         */
        public T querySingle(String sql, Class<T> clazz,Object... parameters){
            Connection connection = null;
            try {
                connection = JdbcUtil.getConnection();
                return qr.query(connection, sql, new BeanHandler<>(clazz), parameters);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                JdbcUtil.close(null,null,null);
            }
        }

        /**
         *
         * @param sql
         * @param parameters
         * @return 单行单列
         **/
        public T rowColumn(String sql,Object... parameters){
            Connection connection = null;
            try {
                connection = JdbcUtil.getConnection();
                T query = (T) qr.query(connection, sql, new ScalarHandler(), parameters);
                return  query;
            } catch (SQLException e) {
                throw new RuntimeException(e);
            } finally {
                JdbcUtil.close(null,null,null);
            }
        }
}

properties配置文件

#Mysql
driverClassNam=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/数据库名?serverTimezone=UTC
username=用户名
password=密码

注意:我这里的驱动是 Mysql8.0 版本的。
Mysql5.7版本的请用 com.mysql.jdbc.Driver

SqlServer

经过测试,通过 SqlServer 也可以用德鲁伊数据连接池apache.dbutils工具类

前置条件

  1. 德鲁伊数据库连接池下载地址
  2. dbutils下载地址
  3. SqlService驱动下载地址

JdbcUtil

这个类和Mysql的一样

BasicDao

这个类和Mysql的一样

properties配置文件

#sqlSqerver
driverClassNam=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://localhost:1433;DatabaseName=数据库名;encrypt=false
username=用户名
password=密码

sqlServer得改我代码里边的相关sql语句
例如:select * from `user` 改为 select * from [user]

Access

Access就像在文件存储数据。查资料后,连接方式有种ODBC桥接的方式,但得要求JDK版本为8.0以下。所以我们采用另外一种,使用驱动的方式。

前置条件:

  1. Access驱动
  2. 德鲁伊数据库连接池下载地址
  3. dbutils下载地址
    但这个驱动还有个限制:查询50次限制、查询结果1000条限制、插入500次限制

JdbcUtil

package com.myUtil;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JdbcUtil {
    private static ThreadLocal<Connection> threadLocalConn = new ThreadLocal<>();
    public static Connection getConnection() {
        Connection connection = threadLocalConn.get();
        if (connection==null){
            try {
                // 得到连接
                Class<?> aClass = Class.forName("com.hxtt.sql.access.AccessDriver");
	            String url = "jdbc:Access:///D://Access数据库文件/Database2.accdb";
	            connection = DriverManager.getConnection(url);
                // 关闭自动提交
                connection.setAutoCommit(false);
                threadLocalConn.set(connection);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return connection;
    }
    /**
     * 事务的提交
     */
    public static void commit(){
        Connection connection = threadLocalConn.get();
        if (connection != null){
            try {
                connection.commit();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }finally {
                try {
                    connection.close(); // 关闭连接
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        // 提交之后将connection从ThreadLocal清除掉
        threadLocalConn.remove();
    }

    /**
     * 回滚/撤销connection管理的dml等操作
     */
    public static void rollback(){
        Connection connection = threadLocalConn.get();
        if (connection!=null){
            try {
                connection.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }finally {
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        threadLocalConn.remove();
    }
    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        if (resultSet != null){
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (statement != null){
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

BasicDao

MysqlSqlServer一样。

不使用 apache.dbutils工具类

我们只需将上边BasicDao改为我这里自己写的,自动封装对象的代码。

package com.dao;
import com.myUtil.JdbcUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public class BasicDao<T> {
    // 查询单行
    public T querySingle(String sql, Class<T> clazz){
        T object = null;
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            object = clazz.newInstance();
            connection = JdbcUtil.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            if (!resultSet.next()){
                return null;
            }
            Field[] declaredFields = clazz.getDeclaredFields();
            for (Field file : declaredFields) {
                String name = file.getName();
                file.setAccessible(true);
                Object res = resultSet.getObject(name);
                file.set(object,res);
            }
            return object;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtil.close(null,preparedStatement,resultSet);
        }
    }


    // 添加/删除/修改数据
    public boolean dmlData(String sql){
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = JdbcUtil.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            int result = preparedStatement.executeUpdate();
            if (result > 0){
                return true;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            JdbcUtil.close(null,preparedStatement,null);
        }
        return false;
    }

    // 查询多行数据
    public List<T> queryMulti(String sql, Class<T> clazz) {
        Connection connection = null;
        List<T> list = new ArrayList<>();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        T object = null;
        try {
            connection = JdbcUtil.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            Field[] declaredFields = clazz.getDeclaredFields();
            while (resultSet.next()){
                object = clazz.newInstance();
                for (Field file : declaredFields) {
                    String name = file.getName();
                    file.setAccessible(true);
                    Object res = resultSet.getObject(name);
                    file.set(object,res);
                }
                list.add(object);
            }
        } catch (Exception e) {
            throw  new RuntimeException(e); //将编译异常->运行异常 ,抛出
        } finally {
            JdbcUtil.close(null, preparedStatement, resultSet);
        }
        if (list.size() == 0){
            return null;
        }else {
            return list;
        }
    }

}

至此购物系统的全部模块都讲解完毕。因为是初次做,所以有些地方还考虑的还不是很完善。整个购物系统方面,没有添加太多的功能。有什么问题,还有改进的地方,还望大家提出宝贵意见。
最后希望大家多多关注 ^_^,你们的关注是我不断前进的动力!!!
感谢感谢~~~

你可能感兴趣的:(JavaWeb购物系统,数据库,mysql,sqlserver)