How to resolve Exception::java.security.AccessControlException: access denied in HttpServlet - java

I have created one Servlet class and I am trying to retrieve one record from Oracle 11g and also I am trying to use MySQL database but getting this exception: error ouput image
I am using below stuff:
WebServer: Tomcat9
JRE: 1.8
Databases: Oracle 11g,MySQL
Here is my servlet class:
public class EmployeeSearchApp extends HttpServlet{
private static final String EMP_SEARCH_DETAILS = "SELECT EMPMO,ENAME,JOB,SAL,EMPNO FROM EMP WHERE EMPNO=?";
private static final String url="jdbc:oracle:thin:#localhost:1521:orcl";
private static final String userName = "scott";
private static final String password = "tiger";
/*
* private static final String url="jdbc:mysql://localhost:3306/world"; private
* static final String userName = "ram"; private static final String password =
* "padma";
*/
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
PrintWriter pw=null;
int eno=0;
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
//Getting the print Writer Object
pw=res.getWriter();
//Setting the content type
res.setContentType("text/html");
//getting the parameter value
eno=Integer.parseInt(req.getParameter("eno"));
//JDBC code
//Registering JDBC driver
Class.forName("oracle.jdbc.driver.OracleDriver");
//Class.forName("com.mysql.jdbc.Driver");
//Establishing the db connection
con=DriverManager.getConnection(url,userName,password);
//Preparing the Prepared Statement object
ps=con.prepareStatement(EMP_SEARCH_DETAILS);
//set the value into query param
ps.setInt(1, eno);
//execute the sql query
rs=ps.executeQuery();
//process the result set object
if(rs.next()) {
pw.println("<h1>EMPLOYEE DETAILS</h1>");
pw.println("<h1>Employee ID:"+rs.getInt(1)+"</h1>");
pw.println("<h1>Employee Name:"+rs.getString(2)+"</h1>");
pw.println("<h1>Employee Job:"+rs.getString(3)+"</h1>");
pw.println("<h1>Employee Sal:"+rs.getDouble(4)+"</h1>");
pw.println("<h1>Employee Dept NO:"+rs.getInt(5)+"</h1>");
}
}catch (SQLException se) {
se.printStackTrace();
pw.println("<h1 style='color:red;'>Internal Database problem</h1>");
}
catch (ClassNotFoundException cnf) {
cnf.printStackTrace();
pw.println("<h1 style='color:red;'>Internal problem</h1>");
}
catch (Exception e) {
e.printStackTrace();
pw.println("<h1 style='color:red;'>Internal problem</h1>");
}finally {
rs.close();
ps.close();
con.close();
}
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
doGet(req, res);
}
}
and the exception on console is as follows
Exception::java.security.AccessControlException: access denied
What could be the possible scenarios when one may get this exception?
And how do I resolve this?

Stack-trace shows that a security manager (i.e: java policies) is enabled, and restraining you from accessing system properties.
That means that your JVM/Tomcat has been configured to restrain web application privileges and actions. Only the administrator of the target platform can help you with that (either add sufficient authorizations in running policies, or give you an alternative method for what you aim for).

Related

Learn to program in Java Servlet connection to db

I'm learning to program in java and the use of servlet and jsp page.
I have some trouble understanding how I can make the connection with the database.
In particular I have a Java page called Database.java where I create the connection with the database and in which there are all the functions that are performed.
And I created a page called Prenotation.java where I have to do some actions. My problem is that I would not like to leave the database connection on this page (as you can see from the code) but I would like to make the connection via the Database.java page.
I've tried several times but I do not understand how I can do it.
Can you give me some advice? Thank you.
Database.java
package db;
import java.math.BigDecimal;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.concurrent.TimeUnit;
import entity.*;
public class Database {
private Connection connection = null;
private PreparedStatement statement = null;
private ResultSet rs = null;
private String dbname = "Hotel";
String nomeutente = "root";
String password = "123456789";
private static Database db = null;
public static synchronized Database getDatabase() {
if (db == null) {
db = new Database();
}
return db;
}
private Database() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + dbname
+ "?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC",
nomeutente, password);
} catch (Exception exc) {
exc.printStackTrace();
}
}
public Connection getConnection() {
return connection;
}
public boolean checkUser(String email, String password) throws SQLException {
boolean result = false;
String query = "select password from users where email=?";
statement = connection.prepareStatement(query);
statement.setString(1, email);
rs = statement.executeQuery();
if (rs.next() && password.equals(rs.getString("password"))) {
result = true;
}
rs.close();
statement.close();
return result;
}
public boolean existingMail(String email) throws SQLException {
String query = "select * from users where email=?";
boolean result = true;
statement = connection.prepareStatement(query);
statement.setString(1, email);
rs = statement.executeQuery();
if (rs.next()) {
result = true;
} else {
result = false;
}
rs.close();
statement.close();
return result;
}
public boolean insertUtente(Utente u,String password) throws SQLException {
String query = "INSERT INTO users (email,nome,cognome,luogodinascita,datadinascita,indirizzo,password) VALUES (?,?,?,?,?,?,?)";
if(existingMail(u.getEmail())) {
return false;
}
statement = connection.prepareStatement(query);
statement.setString(1, u.getEmail());
statement.setString(2, u.getNome());
statement.setString(3, u.getCognome());
statement.setString(4, u.getLuogodinascita());
statement.setString(5, u.getDatadinascita());
statement.setString(6, u.getIndirizzo());
statement.setString(7, password);
statement.execute();
statement.close();
return true;
}
public Utente getUtente(String email) throws SQLException {
String query= "select * from users where email=?";
statement = connection.prepareStatement(query);
statement.setString(1, email);
rs=statement.executeQuery();
if(!rs.next()) {
return null;
}
Utente u=new Utente(email,rs.getString("nome"),rs.getString("cognome"),rs.getString("datadinascita"),rs.getString("luogodinascita"),rs.getString("indirizzo"));
rs.close();
statement.close();
return u;
}
public boolean modificaPassword(String email, String password) throws SQLException {
String query="UPDATE users SET password='"+password+"' WHERE email='"+email+"'";
Statement statement=connection.createStatement();
statement.executeUpdate(query);
statement.close();
return true;
}
public boolean modificaProfilo(Utente u) throws SQLException {
String query="UPDATE users SET nome = ?, cognome = ?, datadinascita = ?, luogodinascita = ?, indirizzo = ? WHERE email = ?";
statement = connection.prepareStatement(query);
statement.setString(1, u.getNome());
statement.setString(2, u.getCognome());
statement.setString(3, u.getDatadinascita());
statement.setString(4, u.getLuogodinascita());
statement.setString(5, u.getIndirizzo());
statement.setString(6, u.getEmail());
statement.executeUpdate();
statement.close();
return true;
}}
This instead is the page of which I speak
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.JOptionPane;
import db.Database;
import entity.Prenotazione;
/**
*
* #author OOPs
*/
public class Prenotation extends HttpServlet {
private static final String ResultSet = null;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session=request.getSession();
String idPrenotazione = request.getParameter("idPrenotazione");
String email = request.getParameter("email");
int typeRoom = Integer.parseInt(request.getParameter("typeRoom"));;
String arrivalDate = request.getParameter("arrivalDate");
String departureDate = request.getParameter("departureDate");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
// out.println("driver loaded");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Hotel?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root" ,"123456789");
out.println("Connect");
Statement st = con.createStatement();
// Statement stmt = con.createStatement();
out.println("connection successfull");
int total = 0;
PreparedStatement ps = con.prepareStatement( "SELECT COUNT(*) as total FROM reservation WHERE typeRoom = ? AND (? >= arrivaldate AND ? <= departuredate) OR (? >= arrivaldate AND ? <= departuredate)");
int c = 0;
ps.setInt(++c, typeRoom);
ps.setString(++c, arrivalDate);
ps.setString(++c, departureDate);
ps.setString(++c, arrivalDate);
ps.setString(++c, departureDate);
ResultSet rs = ps.executeQuery();
// ResultSet rs2 = stmt.executeQuery(check);
out.println("<h1> Stringa check eseguito </h1>");
if( total > 0) {
// response.sendRedirect("home.jsp");
response.sendRedirect("PrenotazioneNegata.jsp");
}
else {
st.executeUpdate("insert into reservation (email,typeRoom,arrivalDate,departureDate)values ('"+email+"','"+typeRoom+"','"+arrivalDate+"','"+departureDate+"')");
response.sendRedirect("PrenotazioneAvvenuta.jsp");
}
out.println("<h1> Registrazione Eseguita </h1>");
}catch(Exception e){
out.println("Errore." +e);
}
finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
A web container will typically route requests to the same servlet instance so it needs to be thread safe. Currently, the Database class provides a single connection, which would be used by concurrent requests so it is not thread safe.
Consider creating something like a ConnectionFactory class. For example:
public class ConnectionFactory {
public Connection getConnection() {
// move all the creation code from Database class to here
// create and return a new instance
}
}
Then modify the Database class to use the factory
public class Database {
private final ConnectionFactory connectionFactory;
public Database(ConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
// change to private and use the factory
private Connection getConnection() {
return connectionFactory.getConnection();
}
// example method to be used by servlet
public int getTotalReservations(int typeRoom, String arrivalDate, departureDate) {
// query related code currently in serlvet goes here...
}
}
And use the servlet lifecycle init() method to create the objects so the servlet can use it. For example:
public class Prenotation extends HttpServlet {
private Database database;
#Override
public void init() throws ServletException {
super.init();
this.database = new Database(new ConnectionFactory()); // no statics needed!
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession();
String idPrenotazione = request.getParameter("idPrenotazione");
String email = request.getParameter("email");
int typeRoom = Integer.parseInt(request.getParameter("typeRoom"));;
String arrivalDate = request.getParameter("arrivalDate");
String departureDate = request.getParameter("departureDate");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
// use the method from `Database` which knows how to query the DB.
int totalReservations = database.getTotalReservations(typeRoom, arrivalDate, departureDate);
// more processing... and forward to the JSP
}
Note that Database now refers to both a USERS table and a RESERVATTIONS table. It would be better to split these into separate classes, such as UsersQuery and ReservationsQuery. They can both share the same ConnectionFactory instance.
See also:
single responsibility principle
inversion of control (injecting ConnectionFactory into Database)
servlet lifecycle
why static variables (or singletons) are/can be evil
DataSource (instead of the low level ConnectionFactory)

reading data using java servlet in sencha touch

i've created this servlet to connect to database and retrieve data then output them in JSON format.
this is the servlet :
public class ConnectServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("application/json");
PrintWriter out=res.getWriter();
JSONArray relatedWorkordersArray = new JSONArray();
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/users","root","");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from user");
JSONObject jObj=new JSONObject();
st = (Statement) con.createStatement();
rs = (ResultSet) st.executeQuery("select * from user");
while (rs.next()) {
String nom = rs.getString("nom");
String prenom = rs.getString("prenom");
int age = rs.getInt("age");
JSONObject Object = new JSONObject();
Object.put("nom", nom);
Object.put("prenom", prenom);
Object.put("age", age);
relatedWorkordersArray.put(Object);
}
jObj.put("data",relatedWorkordersArray.toString());
jObj.put("Success", true);
rs.close ();
st.close ();
con.close();
//print JSON object
out.print(jObj);
Now, In my sencha touch project i've created a JSON-P STORE and i've putted in his url the name of this servlet : ConnectServlet.java but i have an error: unable to load data using the supplied configuration. open in browser : ConnectServlet.java
how can I do to make this proxy using the servlet to get data from database?
you may find your solution here.click here

Unexpected Token L when printing a json object Using advanced rest chrome

Im using a servlet that connects to a database and prints out whether or not you are logged in or not, When using printWriter.write(JsonObject) i get the error in rest Unexpected Token L. I am using a tomcat server to host the data.
public class Login extends HttpServlet {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/employeedatabase";
// Database credentials
static final String USER = "root";
static final String PASS = "admin";
static Connection conn = null;
static Statement stmt = null;
static ResultSet rs;
static PrintWriter out;
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Login() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json; charset=UTF-8");
out = response.getWriter();
String email = request.getParameter("username");
String password = request.getParameter("password");
String result = "";
if(Validation.validateNull(email) && Validation.validateNull(password)){
if(!Validation.validateEmail(email))
{
result = "Invalid email";
}
if(databaseFuctions.Login(email,password))
{
result = "Login accepted";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
getFromDatabase("manager",email,request,response);
// getFromDatabase("qa",email,request,response);
// getFromDatabase("developer",email,request,response);
} catch (Exception e1) {
// TODO Auto-generated catch block
System.out.println(e1.getMessage());
}
}
else if(!databaseFuctions.Login(email, password))
{
result = "Login invalid";
}}
else{
result = "No login/password entered";
}
out.write(result);
}
public static void getFromDatabase(String table,String email,HttpServletRequest request, HttpServletResponse response){
JSONObject JObject = new JSONObject();
ResultSet ds;
try {
ds = stmt.executeQuery("SELECT * from "+table+" where email = '"+email+"'");
while(ds.next())
{
int id = ds.getInt("id");
int salary = ds.getInt("salary");
String name = ds.getString("name");
String role = ds.getString("role");
String emailAddress = ds.getString("email");
String phone = ds.getString("phone");
JObject.put("id", id);
JObject.put("salary", salary);
JObject.put("name", name);
JObject.put("role", role);
JObject.put("email", emailAddress);
JObject.put("phone", phone);
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
out.print(JObject.toString());
out.flush();
System.out.println(JObject.toString());
}
When printing in the system i get all the correct data, or checking the raw data from rest i get the correct data. But i dont quite understand why the printer is throwing the exception any help is amazing
Ok If the error is in the client is beacuse you are returning a mal formed JSON value, so you are returning something like that: { id: 13, name: "Name"}Login invalid then the first character the L is not valid for the JSON Syntax.
This is becuase you are writing in the response the json string from the method getFromDatabase out.print(JObject.toString()); and after the method call you add to the response the string result = "Login invalid"; out.write(result); that cause you have a invalid JSON.
One way to solve this is return the JSONObject from the method getFromDatabase, and add the put the result method in this object JObject.put("result", result) and the write the object to the response.

javax.sql.datasource getconnection returns null

Can someone please show me how to fix the code below so that it does not throw an error?
The following line of code is giving me a null pointer exception:
return dataSource.getConnection();
Note that dataSource is an instance of javax.sql.DataSource which is specified in web.xml, and which works fine when called by other code.
Here is the actual method in DataAccessObject.java where the null pointer is occurring:
protected static Connection getConnection(){
try {
return dataSource.getConnection(); //
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
The preceding method is being called by this line of code:
connection = getConnection();
Which is located in the following method in a class called CourseSummaryDAO as follows:
public List<CourseSummary> findAll(Long sid) {
LinkedList<CourseSummary> coursesummaries = new LinkedList<CourseSummary>();
ResultSet rs = null;
PreparedStatement statement = null;
Connection connection = null;
try {
connection = getConnection(); //
String sql = "select * from coursetotals where spid=?";
statement = connection.prepareStatement(sql);
statement.setLong(1, sid);
rs = statement.executeQuery();
//for every row, call read method to extract column
//values and place them in a coursesummary instance
while (rs.next()) {
CourseSummary coursesummary = read("findAll", rs);
coursesummaries.add(coursesummary);
}
return coursesummaries;
}catch (SQLException e) {
throw new RuntimeException(e);
}
finally {
close(rs, statement, connection);
}
}
To recreate this simply, I created the following TestCourseSummaries class:
public class TestCourseSummaries {
public static void main(String[] args) {
Long id = new Long(1002);
CourseSummaryDAO myCSDAO = new CourseSummaryDAO();
List<CourseSummary> coursesummaries = myCSDAO.findAll(id);
for(int i = 0;i<coursesummaries.size();i++){
System.out.println("type, numunits are: "+coursesummaries.get(i).getCourseType()+","+coursesummaries.get(i).getNumUnits());
}
}
}
EDIT:
To address JustDanyul's question, I am enclosing the code that calls in my application, and the underlying DataAccessObject code which is extended by the two DAO objects in the calling code:
Here is the code in my application which triggers the error. See there are two classes that each extended DataAccessObject. Perhaps they are conflicting with each other, causing the second one not to get the database connection?
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String idString = req.getParameter("id");
Long id = new Long(idString);
ThisObj thisobj = new ThisDAO().find(id);
req.setAttribute("thisobj", thisobj);
ThoseObjDAO myThoseDAO = new ThoseObjDAO();
List<ThoseObj> thoseobjects = myThoseObjDAO.findAll(id);
req.setAttribute("thoseobjects", thoseobjects);
jsp.forward(req, resp);
}
And here is the code for the DataAccessObject class which is extended by the two DAO classes in the calling code:
public class DataAccessObject {
private static DataSource dataSource;
private static Object idLock = new Object();
public static void setDataSource(DataSource dataSource) {
DataAccessObject.dataSource = dataSource;
}
protected static Connection getConnection() {
try {return dataSource.getConnection();}
catch (SQLException e) {throw new RuntimeException(e);}
}
protected static void close(Statement statement, Connection connection) {
close(null, statement, connection);
}
protected static void close(ResultSet rs, Statement statement, Connection connection) {
try {
if (rs != null) rs.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (SQLException e) {throw new RuntimeException(e);}
}
protected static Long getUniqueId() {
ResultSet rs = null;
PreparedStatement statement = null;
Connection connection = null;
try {
connection = getConnection();
synchronized (idLock) {
statement = connection.prepareStatement("select next_value from sequence");
rs = statement.executeQuery();
rs.first();
long id = rs.getLong(1);
statement.close();
statement = connection.prepareStatement("update sequence set next_value = ?");
statement.setLong(1, id + 1);
statement.executeUpdate();
statement.close();
return new Long(id);
}
}
catch (SQLException e) {throw new RuntimeException(e);}
finally{close(rs, statement, connection);}
}
}
The data source is created in web.xml, as follows:
<resource-ref>
<description>dataSource</description>
<res-ref-name>datasource</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
I suspect that the code where it "runs fine" in, is code actually running in an application server. The example you are posting, which just runs a static void main() method, wont get any resources which has been defined in web.xml.
I am guessing that you use JDNI to setup the initial datasource. And then using something like
#Resource(name="jdbc/mydb")
private DataSource dataSource;
to set up your connection. Right?
EDIT:
After seeing your code, it seems like your data source is newer initialised at all. Just putting a element into your web.xml will not do it alone. You will also need to actually configure the dataSource, you know, specify the driver, username, password, uri etc etc etc.
I'm guessing the find() method of the DAO that works, isn't actually using the dataSource. What you have shown so far, doesn't insigunate that your have a initialised dataSource at all.
Just to give you an idea, I liked a tutorial on how you would do this with Tomcat and JDNI. (Or even better, use spring-jdbc).
http://www.mkyong.com/tomcat/how-to-configure-mysql-datasource-in-tomcat-6/
Use dataSource as <javax.sql.DataSource> instance, rather than an instance of <javax.activation.DataSource>.
In short, you should replace the statement <import javax.activation.DataSource;> by this other <import javax.sql.DataSource;>.
Use dataSource as javax.sql.DataSource instance, rather than an instance of javax.activation.DataSource. In short, you should replace the statement:
import javax.activation.DataSource;
by this other:
import javax.sql.DataSource;

why can't java see my mysql driver

I'm having trouble working out why java can't see my mysql driver:
I've downloaded the driver .jar from the mysql website
I've added the jar to my runtime classpath
I can confirm the jar is on the classpath, by printing out the relevant system property
But I'm still getting ClassNotFound Exceptions. Is there anything else I need to be doing?
class example:
package org.rcz.dbtest;
import java.sql.*;
public class DB {
private Connection connect = null;
private Statement stmt = null;
private PreparedStatement prepared = null;
private ResultSet rset = null;
private String driverClassName = "com.myqsl.jdbc.Driver";
private String jdbcUrl = "jdbc:mysql://localhost/ctic_local?user=root&password=server";
private String queryString;
public DB(String query)
{
System.out.println(System.getProperty("java.class.path"));
queryString = query;
}
public void readFromDatabase()
{
try
{
Class.forName(driverClassName);
connect = DriverManager.getConnection(jdbcUrl);
stmt = connect.createStatement();
rset = stmt.executeQuery(queryString);
writeResultSet(rset);
}
catch (ClassNotFoundException cex)
{
System.out.println("Could not find mysql class");
}
catch(SQLException sqex)
{
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
// ResultSet is initially before the first data set
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getSTring(2);
String user = resultSet.getString("name");
String comment = resultSet.getString("comment");
System.out.println("User: " + user);
System.out.println("Comment: " + comment);
}
}
}
My main class simply passes the query into the DB class:
package org.rcz.dbtest;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException
{
String qstring = "SELECT * FROM comments";
new DB(qstring).readFromDatabase();
System.in.read();
}
}
You've a typo in the driver class name.
private String driverClassName = "com.myqsl.jdbc.Driver";
it should be
private String driverClassName = "com.mysql.jdbc.Driver";
// -------------------------------------^
Unrelated to the concrete problem, holding DB resources like Connection, Statement and ResultSet as an instance variable of the class is a bad idea. You need to create, use and close them in the shortest possible scope in a try-finally block to prevent resource leaking. See also among others this question/answer: When my app loses connection, how should I recover it?

Categories