嗯,我需要从数据库中取值,并将它们插入到组合框中进行选择。从数据库解析数据到组合框
听起来很容易使用2班,UI类和实体类,其中包含里面所有的SQL查询来做到这(什么关系数据库,它在那里):
//This is the UI class
public void fillComboBox(){
Entity et = new Entity();
try{
//call out dbConnector method from Entity class
conn = et.dbConnector();
String query="select distinct Name from DbTable order by Name";
PreparedStatement pst = conn.prepareStatement(query);
ResultSet rs = pst.executeQuery();
while(rs.next()){
//shows topic data in combobox
comboBoxName.addItem(rs.getString("Name"));
}
}
catch(Exception e){
e.printStackTrace();
}
}
//runs method
fillComboBox();
现在,上面的输出可以正常工作,没有任何故障。在我的表单中,组合框显示从我指定列中的数据库中取得的唯一值。
问题出现时,在其中实施其他层。
总之,我现在有三个班。
第1类:UI - >此类纯粹处理UI
2类:控制器 - >此类纯粹运行方法
3类:实体 - >此类纯粹运行任何与sql数据库查询有关的事情
我所做的,就是修改上面的代码,代码如下:
这是UI类:
//Declare Variables
JComboBox comboBoxName = new JComboBox();
Controller ct = new Controller();
comboBoxName.addItem(ct.fillComboBox());
和控制器类中的某个方法:
//Declare Variables
Entity et = new Entity();
public String fillComboBox(){
return et.takeNames();
}
最后,我的实体类,其中包含内的所有SQL查询。
//Declare all variables first
Connection conn = null;
String task = null, names = null;
String query;
//This method connects to database
//There's nothing wrong with this method, I just placed it here to give a general overview of what this method exactly is for you to understand, as I will be calling it out later. Yes, I removed off the **URL** portion intentionally.
public static Connection dbConnector(){
try{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:URL");
JOptionPane.showMessageDialog(null, "Connected!");
return conn;
}
catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
return null;
}
}
public String takeNames(){
try{
conn = dbConnector();
query = "select distinct Name from DbTable order by Name";
PreparedStatement pst = conn.prepareStatement(query);
ResultSet rs = pst.executeQuery();
while(rs.next()){
//shows Name data in combobox
names = rs.getString("Name");
}
pst.close();
}
catch(Exception ex){
ex.printStackTrace();
}
return names;
}
嗯,基本上,这是如何“新”的实施运行的是,在UI类召唤出Controller类,它调用了实体类,它运行的内部和分析方法返回值一直到用户界面。
从分离程序的不同部分的角度来看,此方法非常有用,使其看起来更整齐。太糟糕了,这是一个头痛的执行。 >。>
现在,这个错误将会是,它将只检索1个值,而不是多个值。它所做的检索是我指定的特定列中的第一个“独特”值。其余的“独特”值将被忽略。
我有一种预感,它有一切做与RS设置,@:
ResultSet rs = pst.executeQuery();
我脑子里想的是什么,只需要1点的值,并将它,然后忽略其余部分。有没有人有任何解决方案?我尝试了arraylist,但未能就如何在arraylist中存储大量rs值(这真的让我难倒了>。>)
我做了冗长的道歉后,但我尽力做了,直到我所能,我被困在这部分时间之前.....
你能做些什么像插入一些你面临的问题的图像顶部。这是一个文本墙的朋友。越早掌握这个问题的人就越有可能得到答案。一张图片胜过千言万语! – JGFMK
我指定的特定列 - 具体说明... – JGFMK
编码器不需要运行注释,您是如何编写应用程序的。他们只需要看现在的代码。他们可以理解代码。如果您提供样本数据表以及您得到的内容与想要澄清事物的内容! – JGFMK