I am trying to connect to my website's MySQL database, and I have no knowledge of PHP so I decided to use JDBC. I followed some video tutorials (non JDBC) and I used their steps. I skipped the MAMP step though because I am not hosting the server off of my PC. It is being hosted locally because it is going to be a larger website.
So I have this code entered in my Login Activity (first screen you see):
Connection connection = null;
Statement statement = null;
String username = "username";
String password = "password";
String dbURL = "jdbc:mysql://216.26.176.52:3306/lifesizefoto";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(dbURL, username, password);
statement = connection.createStatement();
System.out.println("Connected.");
} catch (ClassNotFoundException error) {
System.out.println("Cannot connect");
} catch (SQLException error) {
System.out.println("Error: " + error.getMessage());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (connection != null) { try {connection.close();} catch (SQLException ignore) {} }
if (statement != null) { try {statement.close();} catch (SQLException ignore) {} }
}
I have tried many variations to the .getConnection() statement, but I can't figure it out. I have also contacted the website host and he took down all firewalls for my IP and even opened up a special port for the app.
When I run my app, I get this error:
01-09 18:59:32.769: I/System.out(14178): Error: Communications link failure
01-09 18:59:32.769: I/System.out(14178): The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
I would appreciate any help. Thank you in advanced!
Two thoughts:
It's unlikely that your web site's MySQL server is bound to an external interface - it's likely only listening on the localhost interface. Your hosting provider should be able to confirm / possibly fix that for you.
Trying to connect a mobile app directly to a server database is probably not going to work well in the long run - I'd suggest that you either figure out how to write a server-side app (for your mobile app to connect to) in PHP, or find another language that your host supports, and do it in that.
Related
This is my first time connecting to remote database using android studio.
Program logs : not-Connected.
I have used same function to connect in eclipse, but it doesn't work in AS.
static Connection connection = null;
public static void databaseConnect() {
String jdbcURL = "jdbc:postgresql://ec2-52********amazonaws.com:5432/d3****hg";
String username = "ve*****cgo";
String password = "efc**********f16";
try {
connection = DriverManager.getConnection(jdbcURL, username, password);
Log.d("log", "databaseConnect: Connected");
} catch (Exception e) {
Log.d("log", "databaseConnect: not-Connected");
e.printStackTrace();
}
}
I have tried adding mssql-jdbc.jar to libs folder and adding android.premission.INTERNET to manifest, but I am obviously missing some steps. I couldn't find solution online so I am posting this question so somebody can hopefully help.
I've recently finished working on my first JavaFX app.
It connects with a MySQL database that is set up on a local server.
Before using the application I need to start the servers running using Xampp.
Now I want to finally pack my app into an .exe file and use it.
I'm a complete newbie when it comes to the servers and databases. My question is - what do I do to make my app connect with the database itself once the user opens it?
Do I need to switch from a local host server to a remote server that will not require starting it each time?
My JavaFX app connects with MySQL using JDBC.
private static String url = "jdbc:mysql://localhost:3306/Finance?useSSL=false&serverTimezone=UTC";
private static String login = "root";
private static String password = "";
public static Connection getConnection() throws SQLException {
Connection connection = DriverManager.getConnection(url, login, password);
return connection;
}
You can test your connection with a method like this:
public boolean canConnect() {
try {
con = DriverManager.getConnection(url, login, password);
//executed only if no errors are thrown
return true;
} catch (SQLException e) {
e.printStackTrace();
//can't connect
return false;
} finally {
//close connection if it was successful
try {
if (con!=null) con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
by calling it in your main method, or in your first stage like this:
if (!canConnect()) {
//notify the user
//start xampp or check connection to local server
} //else proceed
If you want to deploy your application with Xampp, you need to make Xampp to autostart when pc boots up, so the user don't have to start it manually in each boot.
If you are wondering how to auto-start your MySQL service in Xampp, you can find it here.
I'm trying to run the following code but It always results in a "http 500 Internal Server Error"
Could someone help me debug this error
I just started learning Servlets and JSP..So please excuse me if I miss any details in the question. Looking in the MYSQL database error logs, I found the following entries:
Aborted connection 44 to db: 'sakila' user: 'root' host: 'localhost' (Got an error reading communication packets)
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out=response.getWriter();
final String DB_URL="jdbc:mysql://localhost:3306/sakila";
final String user="root";
final String password="pass1234";
Statement stmt=null;
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
out.println("Cannot load driver");
}
Connection conn=null;
try {
conn=DriverManager.getConnection(DB_URL,user,password);
} catch (SQLException e) {
// TODO Auto-generated catch block
out.println("Cannot Connect to Database");
}
//out.print("Connected to Database");
out.println("<html>");
out.println("<body>");
String str= "SELECT actor_id, first_name last_name FROM temp where actor_id='1';";
try {
ResultSet rs=stmt.executeQuery(str);
while(rs.next()){
out.println(rs.getString("actor_id"));
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
/*
try {
ResultSet rs;
rs = stmt.executeQuery(str);
while(rs.next()){
int i=rs.getInt("actor_id");
String fn= rs.getString("first_name");
String ln=rs.getString("last_name");
out.print(i+"::");
out.print(fn+"::");
out.print(ln+"::");
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
*/
out.print("hkshfdkhfakfshdkha");
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.println("</body>");
out.println("</html>");
}
Aborted connection 44 to db: 'sakila' user: 'root' host: 'localhost'
(Got an error reading communication packets)
This error trace is appearing in your console because you are trying to making new db connection to the mysql database on every doGet() request without properly closing your db connection.
And thats why whenever a communication error occurs it increments the status counter for either Aborted_clients or Aborted_connects, which describe the number of connections that were aborted because the client died without closing the connection properly and the number of failed attempts to connect to MySQL server (respectively).
Out of the various reasons causing this issue, here are few important ones that you might want to check.
The client connected successfully but terminated improperly (and may
relate to not closing the connection properly)
The client slept for longer than the defined wait_timeout or
interactive_timeout seconds (which ends up causing the connection to
sleep for wait_timeout seconds and then the connection gets forcibly
closed by the MySQL server)
The client terminated abnormally or exceeded the max_allowed_packet
for queries
So as right mentioned by #Matt Clark you should be going for a connection pool mechanism to avoid this issue and also to follow best pratices around interfacing with databases.
If you check your application logs, it is my assumption that you will see the stacktrace generated by
e1.printStackTrace();
This is because you have an error in you SQL syntax.
SELECT actor_id, first_name last_name FROM temp where actor_id='1';
/\ add missing comma
On a side note - you should not be establishing the connection to the databse inside each request. This slows everything down.
Instead, you should be using a connection pool, I recommend C3P0.
The reason for abrupt termination in your database logs, is because your application throws an exception and abandons the connection without properly closing it.
hi i'm new in android developing and i want to write an application which use signalR java-client. in first step i did the answer of this and here is my client code:
Platform.loadPlatformComponent(new AndroidPlatformComponent());
String host = "localhost";
HubConnection connection = new HubConnection( host);
HubProxy hub = connection.createHubProxy("HubConnectionAPI");
SignalRFuture<Void> awaitConnection = connection.start(new LongPollingTransport(connection.getLogger()));
try {
awaitConnection.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
hub.subscribe(this);
try {
hub.invoke("DisplayMessageAll", "message from android client").get();
System.out.println("sent!!!");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
and u can download the server code from here
i have following error with awaitConnection.get();
error:
W/System.err: java.util.concurrent.ExecutionException: microsoft.aspnet.signalr.client.transport.NegotiationException: There was a problem in the negotiation with the server
i also have this error:
Caused by: microsoft.aspnet.signalr.client.http.InvalidHttpStatusCodeException:Invalid status code: 404
can anyone please help me? i searched a lot but i didn't found anything helpful for me
EDIT:
clients can access the hub via this but how can i implement on android so my application can connect?
this is the log file on server:
2015-11-11 09:05:08 10.2.0.18 GET /signalr/negotiate clientProtocol=1.3&connectionData=%5B%7B%22name%22%3A%22hubconnectionapi%22%7D%5D 80 - 10.2.0.253 SignalR+(lang=Java;+os=android;+version=2.0) - 404 0 2 3
changed the String host = "localhost";
to String host = "localhost/signalr";
localhost didn't work for me, i had to deploy the asp.net web application on IIS, allow the port in Firewall inbound rules and put it in signalr config in android.. hope this helps someone... Cheers!
In java RMI i am building a chat application. But i am not able to figure out a way to find out, whether the IP which is hitting my server is from my internal organization network(INTRANET) or from external world(INTERNET).
Right now i am using
try {
System.setProperty("java.rmi.server.hostname",InetAddress.getLocalHost().getHostAddress());
Registry statusRegistry = LocateRegistry.createRegistry(ChatConstants.statusPort);
ChatInterface chat = new ChatImpl(ChatConstants.statusPort) ;
statusRegistry.rebind("statusconnection",chat);
System.out.println("RMIStatusConnection Server is started...");
} catch (RemoteException e) {
System.out.println("RMIStatusConnection failed...");
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
}
Try RemoteServer.getClientHost(), but it may only provide the address of the nearest NAT device.
NB there's not much point in setting java.rmi.server.hostname like that. That's the default. You only need to set it if there's something wrong with the default setting.