java如何从mysql获取数据到jList?
我是java新手。 如何从mysql获取数据并在Jlist中显示(Jlist名称:JLISTF) 我把向量和模型搞混了
下面是我JFRAME的照片
黄色部分表示JLIST,其名称为JLISTF 我想显示mysql中的数据
谢谢
代码:
public class Inventory extends javax.swing.JFrame {
Connection connect = null;
ResultSet rs = null;
PreparedStatement pst = null;
ResultSet rs2 = null;
public void populateJList(JList ItemList, String query, Connection connection) throws SQLException
{
DefaultListModel model = new DefaultListModel(); //create a new list model
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query); //run your query
while (resultSet.next()) //go through each row that your query returns
{
String ItemList2 = resultSet.getString("ItemCode"); //get the element in column "item_code"
model.addElement(ItemList2); //add each item to the model
}
ItemList.setModel(model);
resultSet.close();
statement.close();
}
public Inventory() {..}
private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) { ......}
private void saveButton3ActionPerformed(java.awt.event.ActionEvent evt) {
String inventcodef = inventCodeField.getText();
try{.........}
catch()
{...........}
}
# 1 楼答案
假设您已连接到数据库,并且知道要查询的信息,可以使用以下方法填充JList
将JLISTF变量作为第一个参数传递到此函数中
下一行假设您的列名是“item_code”,您将希望用您的实际列名替换它
此函数创建一个新模型(请参见How to Use Models),然后执行查询。它获取查询返回的每个值,并将其添加到新模型中。列表然后,setModel(model)告诉列表开始使用新模型