-5

I want to use a little program to interact with my mysql-database. I already added and injected the drivers and so on. I found a tutorial and followed it step for step but java always throws an error.

I'm not very advanced in Java thanks to my "meh" school knowledge. Can someone tell me why the following code throws the following errors?

import java.sql.*;
public class db_test {

  Statement stmt;       
  ResultSet rs;

  public static void main(String[] args) {
    try {
      Class.forName("com.mysql.jdbc.Driver");
      String url     = "jdbc:mysql://localhost:3306/testdb";       
      Connection con = DriverManager.getConnection(url,"test", "1234");        
      stmt = con.createStatement();
      rs = stmt.executeQuery("SELECT name, surname FROM users");
      int anzahlZeilen = stmt.executeQuery("UPDATE users SET name = 'Harry' WHERE surname='Larry' ");
      while (rs.next()){        
        String  name = rs.getString("name");        
        String  surname = rs.getString("surname");        
        System.out.println("Surname: "+surname+" | Name: "+name);        
      }
      con.close();

    } catch(Exception e) {
      System.out.println("Error");
    } finally {
      System.out.println("Finally");

    }
  }
}

The error message says at "stmt = con.createStatement();" the following: "Non-Static Variable stmt cannot be referenced from a static context)".

The same error appears on everything that interacts with stmt and rs. I do not really understand how stmt / rs work (tutorial left this bit out) so it would be nice if some one can tell me what this is called so i can read something about it.

Thanks in advance.

  • `stmt` is not `static` that is, it is an instance field. `main` is static, so it is not associated to any instance. So there is *missing* an instance to access `stmt`. Solution: (not so good in your case) create an instance; better, declare both fields `stmt` and `rs` as `static` – user85421 Oct 14 '19 at 20:20
  • Yup, and those should definitely be declared in the method.... look into when to use static variables, and when not to – RobOhRob Oct 14 '19 at 20:20
  • Thanks, i think i will place them inside main :) –  Oct 14 '19 at 21:09

1 Answers1

1

If you want to keep the following variables outside main method, declare them with static keyword as follows:

static Statement stmt;       
static ResultSet rs;

Alternatively, place them as they are inside main method.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110