Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Browse files
Browse the repository at this point in the history
JSONArray hosted on localhost:8080/StudentAdmin/sqlTest
- Loading branch information
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
|
||
import java.io.IOException; | ||
import java.io.PrintWriter; | ||
import java.sql.*; | ||
|
||
import javax.naming.Context; | ||
import javax.naming.InitialContext; | ||
import javax.naming.NamingException; | ||
import javax.servlet.ServletException; | ||
import javax.servlet.annotation.WebServlet; | ||
import javax.servlet.http.HttpServlet; | ||
import javax.servlet.http.HttpServletRequest; | ||
import javax.servlet.http.HttpServletResponse; | ||
import javax.sql.DataSource; | ||
|
||
@WebServlet("/Test") | ||
public class sqlTest extends HttpServlet { | ||
private static final long serialVersionUID = 1L; | ||
|
||
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { | ||
Context ctx = null; | ||
Connection con = null; | ||
Statement stmt = null; | ||
ResultSet rs = null; | ||
try{ | ||
ctx = new InitialContext(); | ||
DataSource ds = (DataSource) ctx.lookup("java:/comp/env/jdbc/LocalStudentAdminDB"); | ||
con = ds.getConnection(); | ||
stmt = con.createStatement(); | ||
rs = stmt.executeQuery("SELECT * FROM SA_Development.TERM"); | ||
PrintWriter out = response.getWriter(); | ||
|
||
String resultantJSON = "["; | ||
ResultSetMetaData rsmd = rs.getMetaData(); | ||
int columnCount = rsmd.getColumnCount(); | ||
int x = 0; | ||
|
||
while(rs.next()){ | ||
if (x!=0) {resultantJSON += ",";} | ||
resultantJSON += "\"" + rs.getString("TERM_NAME") + "\""; | ||
x += 1; | ||
} | ||
resultantJSON += "]"; | ||
response.setContentType("application/json"); | ||
out.print(resultantJSON); | ||
}catch(NamingException e){ | ||
e.printStackTrace(); | ||
} catch (SQLException e) { | ||
e.printStackTrace(); | ||
}finally{ | ||
try { | ||
rs.close(); | ||
stmt.close(); | ||
con.close(); | ||
ctx.close(); | ||
} catch (SQLException e) { | ||
System.out.println("Exception in closing DB resources"); | ||
} catch (NamingException e) { | ||
System.out.println("Exception in closing Context"); | ||
} | ||
|
||
} | ||
} | ||
|
||
} |