I try to connect from eclipse emulator android to an sql server using this code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
String driver = "net.sourceforge.jtds.jdbc.Driver";
Class.forName(driver).newInstance();
String connString = "jdbc:jtds:sqlserver://83.212.240.15:1521/hua;encrypt=false;user=xxxxxx;password=xxx;instance=SQLEXPRESS;";
String username = "xxxxx";
String password = "xxxxx";
conn = DriverManager.getConnection(connString,username,password);
Statement stmt = conn.createStatement();
ResultSet reset = stmt.executeQuery("insert into picture values('hi');");
conn.close();
but in the database nothing happens.Any ideas?
Thanks in adnvanced
Well this is not directly the answer you are expecting but I would not suggest to access a database directly. Better use e.g. a REST webservice for all database access. So you don't need to make your credentials public.
It is quiet simple so observe the network traffic so it would be realy easy to hack you database server(s).
Anyway if your App is really only for private usage you need to check that you app has the Internet permission for accessing your network ressources.
Related
I'm new to programming and I am a little lost. I'm building a desktop app that upon being launched, prompts the user to log in and the app then connects to my sites mySQL database and verifies it and if the user is found, then a second JFrame appears and the user can now use the program.
I hadn't thought of that, but now I'm faced with the problem of someone decompiling the app and getting access to the mySQL connection details.
Here is a trimmed version of the connection code for reference.
import java.sql.Connection;
import java.sql.DriverManager;
public class databaseConnection {
public static void main(String[] args) throws Exception {
getConnection();
}
public static Connection getConnection() throws Exception {
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/dbase";
String username = "root";
String password = "root";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,
username, password);
System.out.println("Connected.");
return conn;
} catch (Exception e) {
System.out.println(e);
}
return null;
}
}
Is there a way to hide or encrypt the url, username and password? I understand nothing is absoluetly secure and this would just make it a tad harder for someone with malicious intent, but strasight up leaving the information for anyone to see seems a little foolish.
thanks
There's no good way to solve this issue, which is why you don't see that many desktop programs connecting to a central database (anymore). Any credentials contained inside your programs are visible. Sure, you can use any amount of time you want to invent "security schemes", but it won't change the fact that it's just insecure.
You have basically three ways to avoid that issues. Make your application a webapp so the users can't access the code, make your users set up their own databases with their own credentials (this obviously won't help if you want all users to be able to exchange information between each other) or thirdly, write a backend layer so the desktop clients don't connect to the database directly. They would then send commands to the backend to perform database operations, and you can control the backend credentials to allow connections to whom you want.
I am trying to write some Java code that connects to a remote database from my personal computer. I can currently ssh to these machines using a private/public key authorisation. I can access the GUI of these machines by creating SSH tunnels (with Putty).
I don't think the problems is with my code as I can create a DB using MySQL Workbench and can successfully query the db. When trying to access the db I use the same tunnell address that I use for the GUI. So my questions is down to how should I connect to the DB? Can anyone shed some light to my question? My code is posted below.
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLConnector {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//Connection URL Syntax: "jdbc:mysql://ipaddress:portnumber/db_name"
String dbUrl = "jdbc:mysql://localhost:9092/db";
//Database Username
String username = "root";
//Database Password
String password = "root";
//Query to Execute
String query = "select * from employee;";
//Load mysql jdbc driver
Class.forName("com.mysql.jdbc.Driver");
//Create Connection to DB
Connection con = DriverManager.getConnection(dbUrl,username,password);
//Create Statement Object
Statement stmt = con.createStatement();
// Execute the SQL Query. Store results in ResultSet
ResultSet rs= stmt.executeQuery(query);
// While Loop to iterate through all data and print results
while (rs.next()){
String myName = rs.getString(1);
String myAge = rs.getString(2);
System. out.println(myName+" "+myAge);
}
// closing DB Connection
con.close();
}
}
The error I get is:
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
This should probably be a comment, but my reputation doesnt allow for comments. I would venture to guess that the port on the server's network is blocking that port (whatever port you're using) but is allowing for ssh. What is this server/where/can you change the settings on any firewall to allow for connection?
If I get you right, the mysql is listening at port 9092 at the host you are connecting with ssh.
Then use this ssh command to connect:
ssh -L9092:localhost:9092 username#192.168.1.233
It creates a tcp listening socket at your local machine and tunnel any connections to port 9092 at local machine to the port 9092 at remote machine
Edit:
I missed that you are using putty. Then open connection settings dialog, then browse to ssh and find port forwarding. the notation is nearly the same: local port, to some ip:port at remote site: here you can find a step-by-step guide with screenshots
I am using a Google Cloud SQL using Java-SQL connector. The issue I am facing is that the connection to database drops unexpectedly. While Googling I came across this question and tried the solution suggested in the same question.
In your console click the project, on the left side click Storage > CloudSQL then click on your database name. You will see an 'Edit' button on top. Click that and scroll down to Activation Policy, change it to Always On and then click save.
But I'm still facing the same issue. Fortunately I have been keeping the logs on Google App Engine and I have attached the snapshot of the exception that occurred while connecting to database.
Gist of the code that I've posted below is used to establish connection to the database.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.StringTokenizer;
import java.util.logging.Logger;
import com.google.appengine.api.utils.SystemProperty;
import static com.google.appengine.api.utils.SystemProperty.environment;
import static com.google.appengine.api.utils.SystemProperty.Environment.Value.Development;
import static com.google.appengine.api.utils.SystemProperty.Environment.Value.Production;
Connection con=null;
SystemProperty.Environment.Value env = environment.value();
if(env == Production)
{
System.out.println("Inside Production Phase");
// Load the class that provides the new "jdbc:google:mysql://" prefix.
Class.forName("com.mysql.jdbc.GoogleDriver");
url = "jdbc:google:mysql://<my-project-id>:<cloud-sql-instance>/<database-name>?user=<user-name>&password=<database-password>&useUnicode=true&characterEncoding=UTF-8";
}//if
else if(env == Development)
{
System.out.println("Inside Development Phase");
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
url = "jdbc:mysql://127.0.0.1:3306/<database-name>?user=root";
}//else if
con = DriverManager.getConnection(url);
Is anyone facing the same problem, Please help.
Got a temporary fix, used following parameters while making connection to Google Cloud SQL
url = "jdbc:google:mysql://my-app:mysql2/project-name?user=root&password=password&autoReconnect=true&failOverReadOnly=false&maxReconnects=10";
Reference URL: https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-configuration-properties.html
My application uses a database based on sqlite-jdbc. When I generate the runnable jar file, connecting to my database works fine however if I let Proguard process my application, it breaks the database connection.
The following code establishes a connection with the database file's path submitted. When using Proguard, the message "Got connection!" is never printed hence getConnection() is stuck.
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
private void loadDatabase(String databaseName) throws SQLException
{
String databaseLibrary = "jdbc:sqlite:";
JOptionPane.showMessageDialog(null, "Getting connection...");
Connection databaseConnection = DriverManager.getConnection(databaseLibrary
+ databaseName);
JOptionPane.showMessageDialog(null, "Got connection!");
// ...
}
Only if the Shrink and Obfuscate options are disabled in Proguard the database connectivity does not break after processing.
Any ideas on how this can be fixed and why this happens?
I'm writing a desktop java app on that I want to connect to a MySQL database on a server. Here is the code to do that:
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
private static Connection getDBConnection() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
String username = "myUserName";
String password = "myPassWord";
String url = "jdbc:mysql://www.domainName.com:3306/databaseName";
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
//hangs here
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
When I run this, it hangs on the DriverManager.getConnection() call. Why does this happen? Is my URL malformed?
(I'm not getting any error messages, but the program doesn't respond as if in an infinite loop. I haven't waited longer than 90 seconds to see if the connection will ever be established.)
Also, what is the purpose of the Class.forName() call? How does it work?
I am almost entirely certain that the username and password are correct. (I just used userName and passWord as placeholders above.)
UPDATE: I fixed the port number, and now I get this error:
Cannot connect to database: java.sql.SQLException: Access denied
for user 'userName'#'r236059121.resnet.mySchool.edu' (using
password: YES)
Does this mean I need to configure settings on the database? Or does it mean that I've got the credentials wrong? (They work for PHP scripts deployed on the server that contains the database.)
SOLUTION: Added the host above to the Access Host list on cPanel.
Seems to me like your database is not reachable and you will probably get an error when the call runs into a timeout. Are you sure the hostname and port are right and reachable from your machine?
You don't need the newInstance() at the end of Class.forName(). Class.forName() triggers the classloader to load that class, which in turn triggers some internal registration code in the driver which makes the driver available.
I think the line should just be
Class.forName("com.mysql.jdbc.Driver");
(close the .newInstance() bit)
That causes the driver to register itself with the driver manager and allows the driver manager to pick a driver for the database url.
I think the hang is caused by a DNS problem, or some other reason why your db cannot be reached. By default, the MySQL JDBC driver does not time out for a connection. See http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html and look for connectTimeout.
In your code, you have
String url = "jdbc:mysql://www.domainName.com:portNumber/databaseName";
I take it that you used a real port there? By default, it should be 3306. You can test with the test database which is present in virtually all mysql instances:
String url = "jdbc:mysql://www.domainName.com:3306/test";
You also wrote:
String username = "myUserName";
String password = "myPassWord";
Obviously you should use real credentials here too. Ask your dba what they are. If you're the DBA then...well you should probably read up on MySQl administration :) Seriously when you installed MySQL you were probably promted for a password for the root user. Use those (in the obvious way)
In real code you should probably not hang when the db is not there. So I advise adding a connectTimeout option like so:
String url = "jdbc:mysql://www.domainName.com:3306/test?connectTimeout=3000";
(connectTimeout is in milliseconds, so this would time out after 3 seconds)
Rosarch - You are not able to connect to your DB since its unreachable.
It'll timeout after a while.
Try telnetting -
telnet <IP-OF-domainName.com> <PortNumber>
You'll mostly see that it shows timeout.
Solutions -
1.) If you are behind a firewall, you need to punch a hole to allow access
2.) If you are behind a proxy, need to configure it to allow access