请问怎样将数据库access中的数据读入到vector中,并且打印出来?
由于我数据库中一table有8个字段,所以我设计了两个vector,一个vector用来读取table中的数据,另一个vector用来存储前一个vector.可程序运行的时候发现每次只能读取table中的最后一行数据.请问怎么解决?
部分程序入下:
public void addrow()
{
Vector v=new Vector(8);
//int count=0;
try {
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver ");
String url= "jdbc:odbc:addressbook ";
Connection conn;
try {
conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
String sql= "select * from lianxiren ";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
//将数据库里的数据添加到v中.
v.add(0, rs.getString(1));
v.add(1, rs.getString(2));
v.add(2, rs.getString(3));
v.add(3,rs.getString(4));
v.add(4, rs.getString(5));
v.add(5, rs.getString(6));
v.add(6, rs.getString(7));
v.add(7, rs.getString(8));
//count++;
}
//content.insertElementAt(v, count);
content.add(v);
rs.close();
stmt.close();
conn.close();
} catch (
SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (
ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println(content.size());
//System.out.println(count);
}
------解决方案--------------------你用键值对应一个记录,到了下个记录还是这个键,当然会被覆盖了,所以是最后一条记录
while(rs.next())
{
//将数据库里的数据添加到v中.
v.add(0, rs.getString(1));
v.add(1, rs.getString(2));
v.add(2, rs.getString(3));
v.add(3,rs.getString(4));
v.add(4, rs.getString(5));
v.add(5, rs.getString(6));
v.add(6, rs.getString(7));
v.add(7, rs.getString(8));
//count++;
}
------解决方案--------------------以下伪代码,可以参考一下。
JRE 5.0及以上。
class Tbl_name {
private ..col1;
....
private ..col8;
pubic .. getCol1() {
}
....
public Vector <Tbl_name> query(Connection conn, ....) {
Vector <Tbl_name> rows = new Vector <Tbl_name> ();
try {
Statement stmt = conn.createStatement();
String sql= "select * from lianxiren ";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
Tbl_name row = new Tbl_name();
//将数据库里的数据添加到v中.
row.col1 = rs.getString(1);
....
row.col2 = rs.getString(8);
rows.add(row);
}
}
rs.close();
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
------解决方案--------------------public void addrow()
{
//int count=0;
try {
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver ");
String url= "jdbc:odbc:addressbook ";
Connection conn;
try {
conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
String sql= "select * from lianxiren ";