Getting ruby enviroment variable DATABASE_URL in Java Android Application - java

I've Rails app in heroku and created database. I can see it's url when I use heroku config. Also I have Java android application which has 2 activities. I create database class there as docs say:
public class Database
{
public Database()
{
System.out.println(System.getenv("DATABASE_URL"));
try {
Connection connection=getConnection();
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
private static Connection getConnection() throws URISyntaxException, SQLException {
URI dbUri = new URI(System.getenv("DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath();
System.out.println(username);
return DriverManager.getConnection(dbUrl, username, password);
}
}
And create database object in my Activity:
public void onCreate(Bundle savedInstanceState) {
Database database=new Database();
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
But I see null instead of url. Well it's predictable because they are two different application. So what is the proprer way to get DATABASE_URL in my Java android app? Or I should just copy database's url in Java variable?

I think that direct connect from Android app to DB is quite bad idea.
If you really need it, you can fetch it from heroku app via some http api.
But it is better to use HTTP API for all interaction between android app and db, via your ruby app.

Related

Does MariaDB disconnect automatically or Should i have to disconnect Manually?

I got to use MariaDB for my University Project.
it's my first time doing it, so I dont't know well how to use and code JDBC Driver and mariaDB.
Now I'm implementing the code in many places while looking at examples.
As I see, All the examples seems to creating Statement and making connection by using "DriverManager.getConnection"
Now I have a question.
I'm going to create a DBmanager Class that can connect, create tables, execute queries, and execute the code that updates data on tables in a single line.
I thought all the examples would run alone in one method and came from different places, so I could only try a new connection and create a code that would not close. But I have a gut feeling that this will be a problem.
Is there any way I can leave a connection connected at a single connection to send a command, and disconnect it to DB.disconnect()? And I'd appreciate it if you could tell me whether what I'm thinking is right or wrong.
The code below is the code I've written so far.
I am sorry if you find my English difficult to read or understand. I am Using translator, So, my English could not be display as I intended.
import java.sql.*;
import java.util.Properties;
public class DBManager {
/*********INNITIAL DEFINES********/
final static private String HOST="sumewhere.azure.com";//Azure DB URL
final static private String USER="id#somewhere";//root ID
final static private String PW="*****";//Server Password
final static private String DRIVER="org.mariadb.jdbc.Driver";//DB Driver info
private String database="user";
/***************API***************/
void setDB(String databaseinfo){
database=databaseinfo;
}
private void checkDriver() throws Exception
{
try
{
Class.forName("org.mariadb.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
throw new ClassNotFoundException("MariaDB JDBC driver NOT detected in library path.", e);
}
System.out.println("MariaDB JDBC driver detected in library path.");
}
public void checkOnline(String databaseinfo) throws Exception
{
setDB(databaseinfo);
this.checkDriver();
Connection connection = null;
try
{
String url = String.format("jdbc:mariadb://%s/%s", HOST, database);
// Set connection properties.
Properties properties = new Properties();
properties.setProperty("user", USER);
properties.setProperty("password", PW);
properties.setProperty("useSSL", "true");
properties.setProperty("verifyServerCertificate", "true");
properties.setProperty("requireSSL", "false");
// get connection
connection = DriverManager.getConnection(url, properties);
}
catch (SQLException e)
{
throw new SQLException("Failed to create connection to database.", e);
}
if (connection != null)
{
System.out.println("Successfully created connection to database.");
}
else {
System.out.println("Failed to create connection to database.");
}
System.out.println("Execution finished.");
}
void makeCcnnection() throws ClassNotFoundException
{
// Check DB driver Exists
try
{
Class.forName("org.mariadb.jdbc");
}
catch (ClassNotFoundException e)
{
throw new ClassNotFoundException("MariaDB JDBC driver NOT detected in library path.", e);
}
System.out.println("MariaDB JDBC driver detected in library path.");
Connection connection = null;
}
public void updateTable(){}
public static void main(String[] args) throws Exception {
DBManager DB = new DBManager();
DB.checkOnline("DB");
}
}
For a studying project it's okay to give a connection from your DB Manager to client code and close it there automatically using try-with-resources construction.
Maybe you will find it possible to check Connection Pool tools and apply it further in your project or use as example (like HikariCP, here is a good introduction).
Read about Java try with resources. I think that this link could be usefull for your problem.
JDBC with try with resources

how can i connect from java to mysql server?

The error is that I cant open the connection to mysql database, it must be an error in parameters but I am confused , I have no idea where is the problem.
First you need to create a MySQL schema. Secondly, use JDBC to connect to your recently created database (via localhost - make sure you get the user/password right).
After that you should use DAO-like classes. I'll leave here a Connect class:
public class Connect {
private static final String USERNAME = "root";
private static final String PASSWORD = "12345";
private static final String URL = "localhost";
private static final String SCHEMA = "new_schema";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection connect() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://"+URL+"/"+SCHEMA+"?user="+USERNAME+"&password="+PASSWORD);
}
}
After you have the Connect class, you should connect to the database using Connection c = Connect.connect(). Here's a class that implements it.
public static List<Album> list() throws SQLException {
Connection c = Connect.connect();
ResultSet rs = c.createStatement().executeQuery("SELECT * FROM Albums");
List<Album> list = new ArrayList<>();
while (rs.next()) {
String name = rs.getString("nome"); // first table column (can also use 1)
String artist = rs.getString("artista"); // second table column (can also use 2)
Album a = new Album(name, artist);
list.add(a);
}
return list;
}
It should also give you an insight as to how you should use SQL commands.
If you'd like a more in-depth help you should post the code you used, otherwise it's difficult to give you a more "to-the-point" explanation.
JDBC URLs can be confusing. Suggest you try using a SQL tool that understands the JDBC protocol (such as the database development perspective in Eclipse) to validate the URL and make sure you can connect to the database before you start coding. Cutting and pasting a URL known to work into your code can avoid many problems.

Using JDBC MySQL to connect database in Android?

I create an Android app to connect database using MySQL. When I test connection with localhost 10.0.2.2:3306, I can get database, but when I use the real host to get database from my server, I can not get anything. My host is: https://192.168.1.xxx:xxxxx and my database name is test. What is my problem? Please help me. Thank you.
This is my code:
private class MyTask extends AsyncTask<Void, Void, Void> {
private String idFromServer;
private String url="jdbc:mysql://192.168.1.xxx:xxxxx/test";
String name = "AAA";
#Override
protected Void doInBackground(Void... params) {
try {
ResultSet result = null;
String a = "SELECT * FROM testtable";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(url,"aaa","abcdef");
Statement state = con.createStatement();
result = state.executeQuery(a);
while (result.next()) {
if (name.equals(result.getString("name"))) {
idFromServer = result.getString("id");
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
id.setText(idFromServer);
super.onPostExecute(result);
}
}
Generally MySql is installed with security restrictions so it is possible to access to it only from localhost.
You need to execute a command similar to the following to permit access from other ip
GRANT ALL PRIVILEGES
ON database.*
TO 'youruser'#'%'
IDENTIFIED BY 'yourpassword';
Note that it is a bad practice to offer access to MySql from any IP because it opens the possibility to be hacked. So generally it is a good idea to place a server that intercept requests from your android application and directly call the database.
Note: check also if it is open the route between your application and the mysql server.
If you use 3G you are not using a local network and the IP of the MySql server is different from 192.168.1.xxx (that is the ip of a local network). It is also possible that outside of the local network the MySql Server is not visible. It depends from the configuration of your network.
You need to "open" your network exposing the port to access mysql and checking which is the ip of your local network as seen from internet. Otherwise you can access to the local network using a phone with wireless connection to your local network.

Can I connect to h2 embedded db without setting Class.forName("org.h2.Driver")?

Can I connect to h2 embedded db without setting Class.forName("org.h2.Driver") ?
I used only those parameters: url, login and pass
public static Connection getConnection() {
String url= ResourseHelper.getUrl();
String user= ResourseHelper.getUser();
String pass= ResourseHelper.getPass();
try {
return DriverManager.getConnection(url, user, pass);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
And than I create embedded database using this connection. And it works. Is it correct?
Yes, for Java 1.6 and newer, Class.forName("org.h2.Driver") is no longer needed. This is due to a change in JDBC 4.0. For details, see Getting Connected Becomes Easier.

JDBC not connecting

While the build paths are not correct I obtain “com.microsoft.sqlserver.jdbc.SQLServerDriver” from the stack trace. As they are built correctly, I obtain my printed statement “Successfully connected”. The JDBC is living within the getter/setters of the webservice as a method.
When I place the JDBC content in its own file with no builds and run as a java application I receive: “com.microsoft.sqlserver.jdbc.SQLServerDriver”
When I place the JDBC content in its own file with builds and run as a java application I receive: “Successfully connected”
When the method is called from a test file as a java application I receive: “Successfully connected”
Ex:
public static void main(String[] args) {
insert.main(args);
When the method is run as a java application on PO I receive: “Successfully connected”
When I place the method to be called under a setter (which will be invoked by the client, which will cause the jdbc to be invoked) I receive: “com.microsoft.sqlserver.jdbc.SQLServerDriver”
Would you happen to have any tips for me? I’m clueless why it will work under being invoked as an application but not via client?
public class insert{
public static void main(String[] args) {
Connection con = null;
Statement st = null;
final String DB_URL = "jdbc:jtds:sqlserver://00.00.00.00:0000/DB";
// Database credentials
final String USER = "usrname";
final String PASS = "pw";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(DB_URL, USER, PASS);
st = con.createStatement();
System.out.println("successfully connected!");
} catch (Exception err) {
System.out.println(" " + err.getMessage ());
}
finally {
try {
con.close();
} catch (Exception e) { /* ignored */ }
try {
st.close();
} catch (Exception e) {
/* ignored */
}
}
}
}
Any tips at this point would be greatly appreciated.
The problem is that your jar misses the necessary libraries that provides com.microsoft.sqlserver.jdbc.SQLServerDriver class and others to communicate with your SQL server. You have to make sure the library is loaded and available when is being executed from tomcat. Just copy your library and drop it inside %TOMCAT_INSTALL%/lib folder, where %TOMCAT_INSTALL% is the folder where your tomcat is installed, so the library will be available for every project (war, jar, etc) that runs in your tomcat installation.

Categories