Hi im trying to get some table values from mysql database to playframework cli . For this i am using a Controller ,and one class to create the data connections. The first method is used to create the connection while the next one is used to execute the queries . However when i try to execute them it gives me a null pointer exception. I did read some other questions that were somewhat close to this but the issue is i am using play frameworks with an angular front end. Making adding the connector a little confusing . I did add it multiple times but it ust doesnt recognize it. I created a new java file and copy pasted the exact same code to another class and ran it using a main method andit works. the table name and the field names match each other. Any form of help is greatly appreciated.
Controller class:
public class HomeController extends Controller {
public Result addBooks() {
System.out.println(request().body().asText());
JsonNode jsonNode = Json.toJson(new AppSummary("Book Added Successfully"));
JsonNode json = Json.parse(request().body().asText());
connect newcon = new connect();
newcon.connection();
newcon.checkBooks();
return ok(jsonNode).as("application/json");
}
}
The connection class with the jdbc connection and one query to execute
package controllers.librarycontrollers;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class connect {
private Connection conn;
private Statement stmt;
private ResultSet rstst;
public void connection() {
try {
System.out.println("connected ");
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/librarymanager", "root", "");
stmt = conn.createStatement();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public void checkBooks() {
try {
String query = "select * from book";
rstst = stmt.executeQuery(query);
System.out.println("records added successfully");
while (rstst.next()) {
String title = rstst.getString("booktitle");
String name = rstst.getString("authorName");
System.out.println("booktitle:" + title + "authorName:" + name);
}
conn.close();
} catch (Exception c) {
System.out.println(c);
System.out.println("not connected");
}
}
}
I am getting a null pointer exception and also the "not connected" print.