Traversing To and Fro with SQL Server Based Java Applications using NetBeans IDE - How to connect to the database during form load
(Page 2 of 5 )
When the form (or JFrame) is created with "DBSample06," the code behind it (only the constructor) will look something like the following:
public class DBSample06 extends javax.swing.JFrame {
/** Creates new form DBSample06 */
public DBSample06() {
initComponents();
}
Make changes to the above code fragment in such a way that it looks similar to the following:
public class DBSample06 extends javax.swing.JFrame {
Connection conn;
Statement sql_stmt;
ResultSet rset;
/** Creates new form DBSample01 */
public DBSample06() {
initComponents();
this.setSize(400,200);
try
{
Class.forName
("com.microsoft.jdbc.sqlserver.SQLServerDriver");
conn = DriverManager.getConnection
("jdbc:microsoft:sqlserver://serverjag:1433","sa","");
sql_stmt = conn.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rset = sql_stmt.executeQuery( "SELECT empno, ename,
sal, deptno FROM Northwind..emp ");
String str = "";
if (rset.next()) {
this.txtEmpno.setText(rset.getString(1));
this.txtEname.setText(rset.getString(2));
this.txtSal.setText(rset.getString(3));
this.txtDeptno.setText(rset.getString(4));
}
}
catch (Exception e){
this.lblMsg.setText("Error: Please view Stack
Trace");
e.printStackTrace();
}
}
In the above code, I explicitly defined the initial size of the frame and connected to the database. As this is the constructor, it is automatically executed. Once executed, it tries to connect to the database, retrieve the information and populate the same into the result set. Once we get into the result set, we then assign the values to all controls on the form.
I made the following variables global to the class level:
Connection conn;
Statement sql_stmt;
ResultSet rset;
When you define any variable (or reference/object) outside all the methods but within the same class, they will be treated as class level variables (or references/objects). They are accessible to every method within the class (without any re-declarations or re-instantiations). All the above declarations get instantiated within the constructor, which gets automatically executed, when the form is loaded (or the class gets instantiated) for the first time.
Next: The Java code from IDE >>
More Java Articles
More By Jagadish Chaterjee