将数据库表的一列存储到ArrayList

时间:2019-02-08 19:26:55

标签: java

我正在编写一个程序,该程序跟踪RFID标签在RFID检查器之间移动时的移动。这模仿了房间之间的钱包移动。每个检查器都是通往不同房间的门。

我有一个SQLite数据库,其中包含卡的名称,位置和标签的名称,以区分不同的卡。

我需要一个ArrayList来告诉我数据库上当前有哪些标签。

我有一个DAO方法,可显示数据库中的所有值并将其存储在ArrayList中,如下所示:

SELECT * FROM Wallets;
[name: Henry, location: 0, tag: 5c00ce6df0, name: jim, location: 0, tag: wallet1]

我正在尝试编写另一种DAO方法,该方法仅显示如下标记:

SELECT Tag FROM Wallets;
[5c00ce6df0, wallet1]

一旦将这些值保存在ArrayList中,我打算将它们传递到另一个DAO方法中,该方法将获取标签并返回所有相关信息,如下所示:

SELECT * FROM Wallets WHERE Tag = 'wallet1';
name: jim, location: 0, tag: wallet1

这是我的getAllWallets() DAO的代码:

public ArrayList<Wallet> getAllWallets() throws SQLException{
    Connection dbConnection = null;
    Statement statement = null;
    ResultSet resultset = null;
    String query = "SELECT * FROM Wallets;";
    ArrayList<Wallet> list = new ArrayList<>(); 

    try {
        dbConnection = getDBConnection();
        statement = dbConnection.createStatement();
        System.out.println(query);
        // execute SQL query
        resultset = statement.executeQuery(query);

    while (resultset.next()) {
        Wallet w = new Wallet(query, 0, query);

        w.setName(resultset.getString("Name"));
        w.setLocation(resultset.getInt("Location"));
        w.setTag(resultset.getString("Tag"));
        list.add(w);
        }   
    } 

    catch (SQLException e) {
        System.out.println(e.getMessage());
    } 
    finally 
    {
        resultset.close();
        statement.close();
        dbConnection.close();
        }   
    return list;
    }

到目前为止,这是我为getWalletTag() DAO所做的尝试:

public ArrayList<String> getWalletTag() throws SQLException {
    Connection dbConnection = null;
    ResultSet resultset = null;
    Statement statement = null;
    ArrayList<String> list = new ArrayList<String>(); 
    String query = "SELECT Tag FROM Wallets;";

    try {
        dbConnection = getDBConnection();
        statement = dbConnection.createStatement();
        // execute SQL query
        System.out.println(query);
        resultset = statement.executeQuery(query);

        String tag = tag.toString(); // i know this is totally wrong but i got stuck

        list.add(tag);

    }
    catch (SQLException e) {
        System.out.println(e.getMessage());
    }

    finally 
    {
        if (resultset != null) {
        resultset.close();
        }
        if (statement != null) {
        statement.close();
        }
        if (dbConnection != null) {
        dbConnection.close();
        }
    }
    return list;
}

我正在努力的是如何将Tag列的所有值都放入数组列表中。是否有捷径可寻?任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

在“理想的宇宙”中,您可能希望使用ORM(例如Hibernate)和框架(例如Spring Boot)。

这两者对您的应用程序都可能是“大材小用”。

如果您的目标是获取“标签列表”,那么您所获得的代码就可以了:

  • 连接到数据库。
  • 进行查询。
  • 将结果集一次复制到一个Java对象列表中。
  • 完成后关闭数据库连接。

如果您的目标是“优化”查找特定于 的标签(而不进行其他数据库查询),那么您应该使用Java MapSet而不是ArrayList。

您希望考虑使用Spring Boot和Sqlite,这是一些教程:

这部分代码看起来不错:

import time,smtplib
import pprint,logging,os,time,json
from subprocess import Popen, PIPE, call
from pprint import pprint
from email.mime.text import MIMEText
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase

email = 'username2@company.com'
gerriturl = ""

def sendEmail2(type,data):
    global originalchange
    global gerriturl,email,username1
    body = '''%s''' % (data)
    #msg = MIMEMultipart(body)
    msg = MIMEMultipart()
    sender = 'techci@company.com'
    receivers = []
    cc = ['username1@company.com']
    REPLY_TO_ADDRESS = 'embedded-tech-integrators@group.company.com'
    if type =='failure':
        print("Inside  failure email %s"%email)
        b = '\U0001F6A8'
        print("b.decode('unicode-escape')")
        receivers.append('username2@company.com')
        #receivers.append(email)
        print('%s'%receivers)
        msg['Subject'] = '%s AUTO  FAILED FOR GERRIT %s :PLEASE TAKE IMMEDIATE ACTION!!!'%(b.decode('unicode-escape'),gerriturl)
    msg['From'] = sender
    msg['To'] = ', '.join(receivers)
    msg['Cc'] = ', '.join(cc)
    msg["Content-Type"] = "text/html"
    try:
        mail = smtplib.SMTP('relay.company.com', 25)
        msg.attach(MIMEText(body, 'html'))
        msg.add_header('reply-to', REPLY_TO_ADDRESS)
        print('Email sent successfully %s %s'%(receivers,cc))
    except Exception as e:
        logger.error('Problem sending email')
        logger.error('%s' % e)
def main():
    data = "THIS IS A TEST EMAIL"
    sendEmail2('failure',data)

if __name__ == "__main__":
    main()

所以是两个选择之一:

  1. 忘记有关public ArrayList<Wallet> getAllWallets() throws SQLException{ resultset = statement.executeQuery(query); while (resultset.next()) { Wallet w = new Wallet(query, 0, query); w.setName(resultset.getString("Name")); w.setLocation(resultset.getInt("Location")); w.setTag(resultset.getString("Tag")); list.add(w); } ... 的信息,只需使用您的钱包来识别标签,或者

  2. 使用相同的查询,只需将“标签”列保存到数组列表中即可(而不是其他任何内容)。

选项2:

getWalletTag()

...或...

 public ArrayList<String> getWalletTag() throws SQLException {
   String query = "SELECT Tag FROM Wallets;";
   ...
   resultset = statement.executeQuery(query);
   List<String> tags = new ArrayList<String>();
   while (resultset.next()) {
     tags.add(resultset.getString("Tag"));
     ...