I am very new to Play and Java (i come from a Python and Django background :) ). I am trying to connect to MYSQL database and read values from it. However, after trying for about few frustrating hours i am unable to do so. Please Help.
My build.sbt has the dependency added:
"mysql" % "mysql-connector-java" % "5.1.18"
My Application.conf file is as (the relevant section)
db.default.driver=com.mysql.jdbc.Driver
db.default.url="jdbc:mysql://127.0.0.1:3306/myDBName"
db.default.user="root"
db.default.password="myPassword"
And i am trying to read the values from Db on application start. Later i would also want to do it from any action in the controller. The relevant section of my code:
import java.sql.ResultSet;
import java.sql.SQLException;
import play.db.*;
import javax.sql.DataSource;
@Override
public void onStart(play.Application appConfig){
DataSource dataSources = DB.getDataSource();
java.sql.Connection connectionSQL = DB.getConnection();
ResultSet rs = connectionSQL.prepareStatement("select * from mytable").executeQuery();
while(rs.next()) {
System.out.println(rs.getString(1));
Logger.debug(rs.getString(1));
}
}
However i am getting a null pointer exception. I also tried many other SO questions such as Simple CRUD tutorial about Play Framework and MySQL using Ebean? but they are all for previous versions. Also,the official Documentation seems lacking in this regard. I understand it being a relatively new and open source project but that's just my two cents. If i am able to do this, i would try to publish an official tutorial for lost souls like me. Till then, please help me. Thanks
EDIT1 @biesior Sorry for missing out these details....Have added in the question now. Also.
- I do not have models yet.
- I may require in future but not now.
- Currently i just want to access existing tables.
Just as a side note i was able to create models and access MongoDB using Morphia object and perform operations. So i have the basic idea but as of now i just need to access existing MySQL db with play java
Well with Java I'd recommend Ebean's SqlQuery API for doing this (maybe because I just prefer it ;)).
In project/plugins.sbt uncomment the line (last one):
In built.sbt modify line and add the PlayEbean to enabled plugins, like:
In your conf/application.conf add this line after DB configs:
So you can use it i.e. in your action as (sample ofc):