简体   繁体   English

根据jlist选定的值从数据库中获取项目并存储在数组中

[英]get items from database according to jlist selected values and store in array

I have a table Users in my database with columns phone no and region . 我的数据库中有一个Users表,表中的phone noregion In my GUI, I have a JList from where the user can select one or more regions, and accordingly I need to send out messages to the phone numbers with matching region. 在我的GUI中,我有一个JList ,用户可以从中选择一个或多个区域,因此我需要向具有匹配区域的电话号码发送消息。

The problem I'm facing is in retrieving the phone numbers from the database. 我面临的问题是从数据库中检索电话号码。 This is my code 这是我的代码

        final JList listRegion = new JList(list);
        listRegion.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        listRegion.setVisibleRowCount(3);
        JScrollPane scroll = new JScrollPane(listRegion);
        scroll.setBounds(113, 254, 123, 50);    
        frame.getContentPane().add(scroll);

I'm storing the selected list values like this 我正在存储这样的选定列表值

Object[] areaList = listRegion.getSelectedValues();

Now I need to retrieve all the numbers with their corresponding regions matching the regions in areaList and need to store them in an array. 现在,我需要检索与区域列表中的区域匹配的所有数字及其对应的区域,并将它们存储在数组中。 I have tried something like this. 我已经尝试过这样的事情。 But it seems to be wrong. 但这似乎是错误的。

for( int i=0; i<areaList.length ; i++){
    String sql2 = "select phone_no from users where region = areaList["+i+"]";
    result = statement.executeQuery(sql2);

    while(result.next()){
        String numbers = result.getString(1);
        //System.out.println(numbers);
    }
} 

I am poor with arrays. 我对数组不好。 Hence not able to do it. 因此无法做到这一点。 Please guide me with the correct way of doing this. 请以正确的方式指导我。

You are not able to access the areaList variable from sql. 您无法从sql访问areaList变量。 Probably you need something like (not tested): 可能您需要类似的东西(未经测试):

String sql2 = "select phone_no from users where region in (";
for( int i=0; i<areaList.length ; i++){
    sql2 += "\'"+ areaList[i]+"\'";
    if (i<areaList.length-1)
        sql2+=",";
}
sql+=")";

result = statement.executeQuery(sql2);

while(result.next()){
        String numbers = result.getString(1);
        //System.out.println(numbers);
}

Also note that you should use a PreparedStatement , instead building the sql manually, this way you will be protected by sql injection issues. 还要注意,您应该使用PreparedStatement ,而不是手动构建sql,这样,您将受到sql注入问题的保护。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM