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: explanation
(Page 3 of 4 )
This section explains the code provided in the previous section. I would like to explain the code part by part. Let us have the first statement:
Class.forName
("com.microsoft.jdbc.sqlserver.SQLServerDriver");
The above statement will simply load the Microsoft SQL Server 2000 driver into memory. Further proceeding, we have the following:
Connection conn = DriverManager.getConnection
("jdbc:microsoft:sqlserver://serverjag:1433","sa","");
The above statement will connect to the default SQL Server instance available at the server named "serverjag," at the default port "1433," with the user name "sa" and with a blank password. Further proceeding, we have the following:
Statement sql_stmt = conn.createStatement();
The above statement will simply create an object named "sql_stmt" based on the class "Statement" from the connection, which is created previously.
ResultSet rset = sql_stmt.executeQuery("SELECT empno,
ename, sal, deptno FROM Northwind..emp ORDER BY ename");
The above statement will execute the SELECT statement provided and the rows will be fetched into a "ResultSet" object "rset."
String str = "";
while (rset.next()) {
str += rset.getInt(1)+" "+ rset.getString(2)+" "+
rset.getFloat(3)+" "+rset.getInt(4)+"n";
}
From the above code fragment, I declared a string variable (which holds all rows in the form of text), "str." For every row fetched by "rset.next()," we are getting the "empno," "ename," "sal," and "deptno" details (with their positional index equivalents) and adding them to the string.
Before writing the string to the file, I converted the entire string to a series of bytes using the following statement:
byte buf[] = str.getBytes();
To write to the file, I need to open an "OutputStream," which is done using the following statement:
OutputStream fp = new FileOutputStream("query1.lst");
Once the "OutputStream" is ready, we can write all the bytes at once by issuing the following statement:
fp.write(buf);
Once everything is done, I need to close, flush and release all memory resources by issuing the following statements:
fp.close();
rset.close();
sql_stmt.close();
conn.close();
Next: How to INSERT, UPDATE or DELETE rows using Java >>
More Java Articles
More By Jagadish Chaterjee