Reputation: 129
I have connected to my SQL Server using JTDS v.1.2.8
I am new with the JDBC Plugin and I am trying to figure it out. I also did check the forums for a related question/answer but I couldn't find one, so here I am, asking :)
What I want to achieve is that I want to display the data I get from the SQL Database in a better way, like a listView or a tableView.
This is the code I'm using at the moment, I am just calling "tblItems" and it just displays table's info inside a textView which works, but kinda sucks to look and read at it.
Any comment or answer to point me in the solution of this is very appreciated.
Thanks for your time.
TextView tv = (TextView)this.findViewById(R.id.display);
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection con = DriverManager.getConnection(url, username, password);
System.out.println("Database connection successfully");
String result = "Database connection success\n";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from tblItems");
ResultSetMetaData rsmd = rs.getMetaData();
while(rs.next()) {
result += rsmd.getColumnName(1) + ": " + rs.getInt(1) + "\n";
result += rsmd.getColumnName(2) + ": " + rs.getString(2) + "\n";
result += rsmd.getColumnName(3) + ": " + rs.getString(3) + "\n";
}
tv.setText(result);
}
catch(Exception e) {
e.printStackTrace();
tv.setText(e.toString());
}
Upvotes: 1
Views: 7544
Reputation: 806
Create a model class like below:
public class Model
{
private int one;
private String two;
private String three;
// Getters and Setters omitted
}
Then, get data from your database and put into a List, for example:
List<Model> list = new ArrayList<Model>();
try
{
Class.forName( "net.sourceforge.jtds.jdbc.Driver" );
Connection con = DriverManager.getConnection( url, username, password );
System.out.println( "Database connection successfully" );
String result = "Database connection success\n";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery( "select * from tblItems" );
ResultSetMetaData rsmd = rs.getMetaData();
while ( rs.next() )
{
Model obj = new Model();
obj.setone( rs.getInt( 1 ) );
obj.settwo( rs.getString( 2 ) );
obj.setthree( rs.getString( 3 ) );
list.add( obj );
}
}
catch ( Exception e )
{
e.printStackTrace();
}
Create a ListViewadapter and pass that list in:
ListViewAdapter adapter=new ListViewAdapter(this, list);
listView.setAdapter(adapter);
Finally you can get your data in ListViewAdapter
class like that and set as you want into ListView
.
txt1.setText(list.get(position).getone());
txt2.setText(list.get(position).gettwo());
txt2.setText(list.get(position).gethree());
I think this will help you!
Upvotes: 2