[英]Java return string object
I have a database function that retrieves data and then populates a jtable. 我有一个数据库函数,该函数检索数据,然后填充一个jtable。 I need to change this function so it RETURNS the data from the database within an
Object[][]
. 我需要更改此函数,以便它从
Object[][]
的数据库中返回数据。 How can this be done? 如何才能做到这一点? (I'm unsure on how to store the data on each row iteration - the while loop part in the code below).
(我不确定如何在每次行迭代中存储数据-以下代码中的while循环部分)。
public void data() {
// clear table then load information
DefaultTableModel model=(DefaultTableModel)table.getModel();
model.getDataVector().removeAllElements();
table.repaint();
ResultSet rs=null;
Statement st=null;
try {
Class.forName("java.sql.Driver");
_con = DriverManager.getConnection(_url,_user,_pwd);
st = _con.createStatement();
String query = "SELECT * FROM table";
rs = st.executeQuery(query);
while (rs.next()) {
String d1 = rs.getString("record1");
String d2 = rs.getString("record2");
model.addRow(new Object[]{d1,d2});
}
} catch (Exception e) {
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (_con != null) {
_con.close();
}
} catch (SQLException ex) {
}
}
}
I don't think this method is a good idea for several reasons: 我认为此方法不是一个好主意,原因有几个:
Connection
outside this method and pass it in. Connection
并将其传入。 ResultSet
and Statement
should not be member variables of the class. ResultSet
和Statement
不应是该类的成员变量。 Make them local to the method. Just change the method to return what you want instead of void
. 只需更改方法以返回所需内容即可,而不是
void
。 I wouldn't use an Object [][]
; 我不会使用
Object [][]
; I'd prefer a List of Maps or some other type that encapsulated a row. 我更喜欢地图列表或封装行的其他类型。 Use the column names as the keys in the Map.
使用列名称作为Map中的键。
here's some code OP has asked for, and yes, OP should pay heed to duffymo's recomendations - I totally agree on them. 这是OP要求的一些代码,是的,OP应该注意duffymo的建议-我完全同意。
Object[] result = null;
try{
Class.forName("java.sql.Driver");
_con = DriverManager.getConnection(_url,_user,_pwd);
st=_con.createStatement();
String query="SELECT COUNT(*) cnt FROM table";
rs=st.executeQuery(query);
Integer size = null;
if (rs.next()){
size = rs.getInteger("cnt");
}
if (size != null){
Object[] result = new Object[size];
query="SELECT * FROM table";
rs=st.executeQuery(query);
int i = 0;
while(rs.next())
{
String d1=rs.getString("record1");
String d2=rs.getString("record2");
result[i++] = new Object[]{d1,d2};
}
}
}
catch(Exception e)
{
//TODO handle exceptions, e.g. rethrow
//throw new RuntimeException(e);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.