Working with DML to Develop SQL Server based Java Applications using NetBeans IDE - How to write the output of a SELECT statement to a text file using Java with NetBeans IDE: source code
(Page 2 of 4 )
Once you have completed all the steps in the previous section, you need to copy the following code into your button "actionperformed" event:
private void btnConnectActionPerformed(java.awt.event.ActionEvent
evt){
// TODO add your handling code here:
try {
Class.forName
("com.microsoft.jdbc.sqlserver.SQLServerDriver");
Connection conn = DriverManager.getConnection
("jdbc:microsoft:sqlserver://serverjag:1433","sa","");
Statement sql_stmt = conn.createStatement();
ResultSet rset = sql_stmt.executeQuery("SELECT empno,
ename, sal, deptno FROM Northwind..emp ORDER BY ename");
String str = "";
while (rset.next()) {
str += rset.getInt(1)+" "+ rset.getString(2)+" "+
rset.getFloat(3)+" "+rset.getInt(4)+"n";
}
byte buf[] = str.getBytes();
OutputStream fp = new FileOutputStream("query1.lst");
fp.write(buf);
fp.close();
rset.close();
sql_stmt.close();
conn.close();
this.txtMsg.setText("create the file with records");
}
catch(Exception e) {
this.txtMsg.setText("Failed to connect; Please view
Stack Trace");
e.printStackTrace();
}
}
Please be aware that you need to modify the driver and connection information according to your requirements. You can press F5 to execute your application. Once it completes successfully, you must see that a new text file exists named "query1.lst" with exactly the same information you find in the table.
If you receive any errors in connecting to Microsoft SQL Server, please refer to my first article in this series.
The next section will explain the above code.
Next: How to write the output of a SELECT statement to a text file using Java with NetBeans IDE: explanation >>
More Java Articles
More By Jagadish Chaterjee