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.