I have been trying to write a Java program which connects to mysql db and retreives data from it.
I have written a simple program which worked successfully, but the below snippet throws some errors which I even havent heard of.
The snippet is as follows:
public class test{
String rows,rows1;
String dbUrl = "jdbc:mysql://localhost:3306/login";
String dbClass = "com.mysql.jdbc.Driver";
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection (dbUrl,"root","");
Statement stmt = con.createStatement();
String query="select distinct(username) from tracking";
ResultSet rs=stmt.executeQuery(query);
while(rs.next())
{
rows=rs.getString("username");
System.out.println(rows);
String query1="select distinct(session_id) from tracking where username='"+rows+"'";
ResultSet rs1=stmt.executeQuery(query1);
while(rs1.next())
{
rows1=rs1.getString("session_id");
String query2="select * from tracking where username='"+rows+"' and session_id='"+rows1+"'";
ResultSet rs2=stmt.executeQuery(query2);
while(rs2.next())
{
System.out.println("Result"+rs2.getString("method"));
}
}
}
con.close();
}
catch(ClassNotFoundException e) {
e.printStackTrace();
}
catch(SQLException e) {
e.printStackTrace();
}
};
The errors are as follows
test.java:12: error: non-static variable dbUrl cannot be referenced from a stati
c context
Connection con = DriverManager.getConnection (dbUrl,"root","");
^
test.java:19: error: non-static variable rows cannot be referenced from a static
context
rows=rs.getString("username");
^
test.java:20: error: non-static variable rows cannot be referenced from a static
context
System.out.println(rows);
^
test.java:21: error: non-static variable rows cannot be referenced from a static
context
String query1="select distinct(session_id) from tracking where username='"+rows+
"'";
^
test.java:25: error: non-static variable rows1 cannot be referenced from a stati
c context
rows1=rs1.getString("session_id");
^
test.java:26: error: non-static variable rows cannot be referenced from a static
context
String query2="select * from tracking where username='"+rows+"' and session_id='
"+rows1+"'";
^
test.java:26: error: non-static variable rows1 cannot be referenced from a stati
c context
String query2="select * from tracking where username='"+rows+"' and session_id='
"+rows1+"'";
I am unable to understand the errors here.
Make your variables STATIC.
You are using the variables rows, rows1 etc in your MAIN method which is static. Whenever you are using any variables inside a static method, the variables itself has to be static.
Probably you are making one of the common errors in Java. May be you can go through other types of common errors so that you can avoid them.