[英]data being overwritten in **Result.next()** loop
我有一个进入我的数据库的搜索按钮,并搜索一个名称,但是当有两个条目输入相同的名称时,它只会带我回去,而我不知道为什么。 下面是我现在使用的代码。
public boolean search(String str1, String username){//search function for the access history search with two parameters
boolean condition = true;
String dataSourceName = "securitySystem";//setting string datasource to the securitySystem datasource
String dbUrl = "jdbc:odbc:" + dataSourceName;//creating the database path for the connection
try{
//Type of connection driver used
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//Connection variable or object param: dbPath, userName, password
Connection con = DriverManager.getConnection(dbUrl, "", "");
Statement statement = con.createStatement();//creating the statement which is equal to the connection statement
if (!(username.equals(""))){
PreparedStatement ps = con.prepareStatement("select * from securitysystem.accessHistory where name = ?");//query to be executed
ps.setString(1, username);//insert the strings into the statement
ResultSet rs=ps.executeQuery();//execute the query
if(rs.next()){//while the rs (ResultSet) has returned data to cycle through
JTable table = new JTable(buildTableModel(rs));//build a JTable which is reflective of the ResultSet (rs)
JOptionPane.showMessageDialog(null, new JScrollPane(table));//put scrollpane on the table
}
else{
JOptionPane.showMessageDialog(null,"There has been no system logins at this time");// else- show a dialog box with a message for the user
}
}
statement.close();//close the connection
} catch (Exception e) {//catch error
System.out.println(e);
}
return condition;
}
这是一个如何使用TableModel
向表中添加数据的示例。
假设您具有这些初始模型条件
String[] columnNames = {"Column1", "Column2", "Column3"};
DefaultTableModel model = new DefaultTablModel(columnNames, 0);
JTable table = new JTable(model);
...
你应该做这样的事情
while (rs.next()){
String s1 = rs.getString(1);
String s2 = rs.getString(2);
String s3 = rs.getString(3);
Object[] row = {s1, s2, s3};
model.addRow(row);
}
编辑:要直接从数据库获取列名,您想使用ResultSetMetaData
。
试试这个方法。
public DefaultTableModel buildTableModel(ResultSet rs){
ResultSetMetaData rsMeta = rs.getMetaData();
int cloumns = rsMeta.getColumnCount();
String columnNames = new String[columns];
for (int i = 1; i <= columns; i++){
columnNames[i - 1] = rsMeta.getColumnName(i);
}
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
while (rs.next()){
// Just an example retrieving data. Fill in what you need
String s1 = rs.getString(1);
String s2 = rs.getString(2);
String s3 = rs.getString(3);
Object[] row = {s1, s2, s3};
model.addRow(row);
// End example
}
return model;
}
然后,
if (rs != null){
JTable table = new JTable(buildTableModel(rs));
}
您的代码多次调用rs.next()
。 在上面的搜索方法中调用buildTableModel(...)
方法之前,先调用它,实际上浪费了您从未使用过的数据行。
取而代之的是,只需将ResultSet传递到方法中,而无需对其进行下一步调用,然后在buildTableModel(...)
内部使用while循环填充数据向量。 如果向量为空,则引发异常,或返回具有0行的TableModel。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.