Sqlite连接数据库工具类

2023-05-16

  • 连接数据库 DataBaseConfig
@Slf4j
public class DataBaseConfig {

    private static final String CLASS_NAME = "org.sqlite.JDBC";
    private static final String DRIVER = "jdbc:sqlite:";
    private static final String DB_URL = "/database/bluetooth.db";

    //程序只加载一次
    static {
        try {
            Class.forName(CLASS_NAME);
            log.info("驱动加载完毕!");
        } catch (ClassNotFoundException exception) {
            exception.printStackTrace();
            log.error("驱动出现异常,请检查驱动!!!");
        }
    }

    public static Connection getConnection() {
        try {
            log.info("Opened database successfully");
            File directory = new File("");// 参数为空
            String courseFile = directory.getCanonicalPath();
            return DriverManager.getConnection(DRIVER + courseFile + DB_URL);
        } catch (SQLException | IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 关闭连接
     */
    public static void getClose(Connection conn, PreparedStatement ps) {
        closes(conn, ps);
    }

    private static void closes(Connection conn, PreparedStatement ps) {
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection conn, PreparedStatement ps, Statement stmt) {
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        closes(conn, ps);
    }

    public static void getClose(Connection conn, PreparedStatement ps, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        closes(conn, ps);

    }
  • 数据实体 UserLogin
@Data
public class UserLogin {

    private Long id;
    private Long userId;
    private String userName;
    private String devicePort;
    private int deviceBaudRate;
    private String loginTime;

    public UserLogin() {
    }

    public UserLogin(Long id, Long userId, String userName, String devicePort, int deviceBaudRate, String loginTime) {
        this.id = id;
        this.userId = userId;
        this.userName = userName;
        this.devicePort = devicePort;
        this.deviceBaudRate = deviceBaudRate;
        this.loginTime = loginTime;
    }
}
  • 数据接口 UserLoginMapper
public interface UserLoginMapper {

    List<UserLogin> findAllUsers();

    UserLogin findLogin(Long userId);

    UserLogin findName(String userName);

    int insert(UserLogin userLogin);

    int delete(Long userId);

    int modify(UserLogin userLogin);
}
  • 数据接口实现 UserLoginService
@Slf4j
public class UserLoginService implements UserLoginMapper {

    @Override
    public List<UserLogin> findAllUsers() {
        List<UserLogin> userLogins = new ArrayList<>();
        Connection connection = DataBaseConfig.getConnection();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        String sql = "SELECT * FROM user_login;";
        try {
            if (connection != null) {
                preparedStatement = connection.prepareStatement(sql);
                resultSet = preparedStatement.executeQuery();
                while (resultSet.next()) {
                    UserLogin userLogin = new UserLogin(resultSet.getLong("id"),
                            resultSet.getLong("user_id"),
                            resultSet.getString("user_name"),
                            resultSet.getString("device_port"),
                            resultSet.getInt("device_baud_rate"),
                            resultSet.getString("login_time"));
                    userLogins.add(userLogin);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DataBaseConfig.getClose(connection, preparedStatement, resultSet);
        }
        log.info("userLogins ====> " + userLogins);
        return userLogins;
    }

    @Override
    public UserLogin findLogin(Long userId) {
        Connection connection = DataBaseConfig.getConnection();
        PreparedStatement prst = null;
        ResultSet resultSet = null;
        UserLogin userLogin = new UserLogin();
        String sql = "SELECT * FROM user_login WHERE user_id = ?;";
        try {
            if (connection != null) {
                prst = connection.prepareStatement(sql);
                prst.setLong(1, userId);
                resultSet = prst.executeQuery();
                if (resultSet.next()) {
                    userLogin = new UserLogin(resultSet.getLong("id"),
                            resultSet.getLong("user_id"),
                            resultSet.getString("user_name"),
                            resultSet.getString("device_port"),
                            resultSet.getInt("device_baud_rate"),
                            resultSet.getString("login_time"));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DataBaseConfig.getClose(connection, prst, resultSet);
        }
        log.info(" userLogin ======>" + userLogin);
        return userLogin;
    }

    @Override
    public UserLogin findName(String userName) {
        Connection connection = DataBaseConfig.getConnection();
        PreparedStatement prst = null;
        ResultSet resultSet = null;
        UserLogin userLogin = new UserLogin();
        String sql = "SELECT * FROM user_login WHERE user_name = ?;";
        try {
            if (connection != null) {
                prst = connection.prepareStatement(sql);
                prst.setString(1, userName);
                resultSet = prst.executeQuery();
                if (resultSet.next()) {
                    userLogin = new UserLogin(resultSet.getLong("id"),
                            resultSet.getLong("user_id"),
                            resultSet.getString("user_name"),
                            resultSet.getString("device_port"),
                            resultSet.getInt("device_baud_rate"),
                            resultSet.getString("login_time"));
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DataBaseConfig.getClose(connection, prst, resultSet);
        }
        log.info(" userLogin ======>" + userLogin);
        return userLogin;
    }

    @Override
    public int insert(UserLogin userLogin) {
        Connection connection = DataBaseConfig.getConnection();
        PreparedStatement preparedStatement = null;
        String sql = "INSERT INTO user_login(user_id, user_name, device_port, device_baud_rate, login_time) VALUES(?, ?, ?, ?, ?);";
        // 更新的条数
        int result = 0;
        try {
            if (connection != null) {
                preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setLong(1, userLogin.getUserId());
                preparedStatement.setString(2, userLogin.getUserName());
                preparedStatement.setString(3, userLogin.getDevicePort());
                preparedStatement.setInt(4, userLogin.getDeviceBaudRate());
                preparedStatement.setString(5, userLogin.getLoginTime());
                result = preparedStatement.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DataBaseConfig.getClose(connection, preparedStatement);
        }
        log.info("insert success count " + result);
        return result;
    }

    @Override
    public int delete(Long userId) {
        Connection connection = DataBaseConfig.getConnection();
        PreparedStatement preparedStatement = null;
        int result = 0;
        String sql = "DELETE from user_login where user_id = ?;";
        try {
            if (connection != null && userId != 0) {
                preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setLong(1, userId);
                result = preparedStatement.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DataBaseConfig.getClose(connection, preparedStatement);
        }
        log.info("delete success count" + result);
        return result;
    }

    @Override
    public int modify(UserLogin userLogin) {
        Connection connection = DataBaseConfig.getConnection();
        PreparedStatement preparedStatement = null;
        int result = 0;
        String sql = "UPDATE user_login set user_name = ?, device_port = ?, device_baud_rate = ?, login_time = ? where user_id = ?;";
        try {
            if (connection != null) {
                preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setString(1, userLogin.getUserName());
                preparedStatement.setString(2, userLogin.getDevicePort());
                preparedStatement.setInt(3, userLogin.getDeviceBaudRate());
                preparedStatement.setString(4, userLogin.getLoginTime());
                preparedStatement.setLong(5, userLogin.getUserId());
                result = preparedStatement.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DataBaseConfig.getClose(connection, preparedStatement);
        }
        log.info("update success count " + result);
        return result;
    }
}
  • 单例工厂 UserLoginFactory
/**
 * 单例工厂
 * Created by YongXin Xue on 2021/08/10 0:29
 */
public class UserLoginFactory {

    private static UserLoginMapper userLoginMapper;

    public static UserLoginMapper getUserLoginMapper(){
        if (userLoginMapper == null){
            userLoginMapper = new UserLoginService();
        }
        return userLoginMapper;
    }

}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Sqlite连接数据库工具类 的相关文章

  • Objective-C SQLite 连接多个数据库中的表

    我正在做一个IPAD 项目 该项目有2个sqlite数据库 第一个是 customer sqlite 第二个是 address sqlite Customer sqlite 随应用程序一起提供 每次启动应用程序时都会从服务器下载 addre
  • 没有这样的列 sqlite 异常

    我试图从用户配置文件中获取一些数据 但找不到该列 我已经检查了每个查询之间的空间 看起来没有什么问题 到目前为止我还看不出问题所在 有什么想法吗 之前谢谢 这是我的代码和错误消息 表名 private static final String
  • 如何使用 2 个字符串参数从 sqlite 数据库检索特定字符串数据?

    这是我用来制作方法的代码 String item item1 getText toString item item toLowerCase String date getDate edited new Datahelper this edi
  • sqlite python 插入

    我以前问过类似的问题 这里是我想要实现的目标的详细解释 我有两个 sqlite 表table1 是标准表 具有服务器 id 状态等字段 table2 具有服务器 id 状态 数字 日志文件等字段 Table2 为空 Table1 有值 我正
  • 为 Android 应用程序复制 Sqlite 数据库

    我正在尝试使用本教程在我的 Android 应用程序中使用我自己创建的数据库http www reigndesign com blog using your own sqlite database in android applicatio
  • 如何使用 C# 访问 SQLite?

    我正在尝试使用 C ASP NET 以编程方式连接到我的 Sqlite 数据库 string requete sql SELECT FROM USERS connStr Data Source C LocalFolder FooBar db
  • iPhone iOS 2.0 到 iOS 4.0 SQLite 兼容性

    我希望我的应用程序能够与 iOS 2 0 兼容 就像 iOS 3 0 和 iOS 4 0 一样 我将使用 SQLite 的原因有很多 现在 我应该用 SQLite 做什么 我应该使用仅随 iOS 2 0 附带的 SQLite 提供的功能吗
  • 使用 sqlite json_each 过滤 json 数组中的多个项目

    我有一个包含以下架构和数据的 sqlite 表 CREATE TABLE Feeds id INTEGER PRIMARY KEY AUTOINCREMENT groups JSON NOT NULL DEFAULT INSERT INTO
  • SQL:计数和子查询

    再次使用 count 和 sql 在 sqlite 上 我有表格 论文 paper id doi 年份 作者 paper id author id inst id 作者 作者 ID 姓名 名字 安装 inst id 名称 see id in
  • python sqlite3更新不更新

    问题 为什么这个sqlite3语句没有更新记录 Info cur execute UPDATE workunits SET Completed 1 AND Returns WHERE PID AND Args pickle dumps Re
  • sqlite通过命令行导入csv时出错

    sqlite3 test sql SQLite version 3 6 12 Enter help for instructions Enter SQL statements terminated with a sqlite gt crea
  • 如何在 Django 中使用 Python 函数扩展 SQLite?

    有可能在 Python 中为 SQLite 定义新的 SQL 函数 http docs python org library sqlite3 html sqlite3 Connection create function 我怎样才能在 Dj
  • Android 数据库连接和游标哦天哪

    我读过很多关于如何在使用 android 时创建和使用数据库连接的博客和教程 尽管我有很多工作示例 但不同的实现会导致不同的问题 例如 我使用数据源类 Datasource和一个数据库辅助类 DBManagement 数据源 public
  • android sqlite 一次读取所有行

    有没有办法读取 sqlite 表中的所有行并在文本视图中立即显示它们 这就是我阅读它们的方式 它逐行阅读 retrieves all the titles public Cursor getAllTitles return db query
  • py2exe + sqlalchemy + sqlite 问题

    在进入全速开发模式之前 我正在尝试让一些基本的东西在 Python 中工作 具体如下 Python 2 5 4 PyQt4 4 4 3 SqlAlchemy 0 5 2 py2exe 0 6 9 setuptools 0 6c9 pysql
  • 测试抽象模型 - django 2.2.4 / sqlite3 2.6.0

    我正在尝试使用 django 2 2 4 sqlite3 2 6 0 python 3 6 8 测试一些简单的抽象混合 目前 我在使用架构编辑器从测试数据库中删除模型时遇到问题 我有以下测试用例 from django test impor
  • sqlite 无法识别通用列表

    在 Windows 应用商店应用程序项目中 我从 Web 服务获取 JSON 如下所示 http paste2 org jfMJ2AGA http paste2 org jfMJ2AGA 我有这两门课 public class media
  • sqlite:获取所有行的最快方法(连续磁盘访问)

    我想使用 system data sqlite 读取表中的所有行 由于我有一个非常大的表 gt 450GB 超过 60 亿行 我想确保 sqlite 将使用连续的磁盘访问 正如您可能知道的那样 对硬盘的随机访问速度很慢 由于内存限制 我无法
  • 插入失败“OperationalError:没有这样的列”

    我尝试使用我尝试修复的姓名和电话创建一个数据库 但它会随时向我重播 File exm0 py line 14 in
  • 如何在android上的manageQuery中添加限制子句

    Android 的 API 通过 SQLite 提供了一种干净的机制来查询联系人列表 但是 我不确定如何限制结果 Cursor cur Activity mCtx managedQuery People CONTENT URI column

随机推荐