Populating Text Fields from a Database
If you are developing corporate IT
applications, you will invariably find a need to populate a series of
text fields based upon a database query. To do that, you must
understand how to work with the contents of a JDBC
ResultSet
.
How do I do that?
The code to accomplish this task is straightforward. The following code will connect to the MS Access Northwind sample database, using the JDBC/ODBC Bridge driver:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn = DriverManager.getConnection("jdbc:odbc:NorthWind"); Statement stmt = conn.createStatement( ); ResultSet rs = stmt.executeQuery("SELECT * FROM Employees"); if(rs.next( )) { text1.setText(rs.getString("FirstName")); text2.setText(rs.getString("LastName")); }
The text fields
text1
and text2
are
populated with the
String
values in the FirstName
and LastName
columns of the result
set’s first row.
What about...
those times when the column data in the ResultSet
is not a String
? For those occasions, use one of
the other result set methods, such as getInt()
to retrieve the data and then
convert it to a String
value to pass to the
setText( )
method, like so:
text2.setText(Integer.toString(rs.getInteger("EmployeID") ));
Get SWT: A Developer's Notebook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.