Java: Connecting to a MySQL Database? DriverManager.getConnection()? [duplicate] - java

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 4 years ago.
So I was just wondering, what (and probably, how much...) have I done wrong here with this code?
try {
Class.forName("com.mysql.jdbc.Driver");
Connection c = DriverManager.getConnection("jdbc:mysql://mysql1.000webhost.com/mydatabase", "myusername", "mypassword");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
As I've triple-checked the username/password, I'm guessing it's something wrong with the host name. The database is only on the server (I don't have any kind of saved local version or anything...do I need to?).
And also, can someone just tell me if I'm on the right lines for what I want to do? Basically I've created a piece of software with a free version and a very cheap paid version. I was thinking that to prevent piracy, since the program requires internet connection anyway, I could store their email address as the username, then their computer's MAC address would be the password (each time the program was run, I would compare the MAC address on their PC with the one registered along with their email in the database. I've got no idea whether that is a good anti-piracy measure, but I was just wondering, if I manage to get the connection working, is that something that I'd be able to do or would there be e.g. security issues with that?
Anyway, thanks in advance :)

if it is not localhost i cannot comment on the host but you also have to give port number.It is missing.
Connection con = DriverManager
.getConnection("jdbc:mysql://"+pHost+":"+pPort+"/Your_mysql_schema_name",username, password);
and also in MYSQL your schema name would be your database name.Ensure that you are giving schema name and also port number.Usually for MYSQL its 3306

Writing a piece of java code to operate your database from a remote connection is not a good idea. Someone could reverse engineer your code and change your data.
You should atleast Implement an simple service on the net that could handle the spam you might receive, and protect your data.

I Think you missed the database port no in your URL .Try this :
try {
Class.forName("com.mysql.jdbc.Driver"); // Not Required for JDBC 4.0 onwards
Connection c = DriverManager.getConnection("jdbc:mysql://mysql1.000webhost.com: 3306/mydatabase", "myusername", "mypassword");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

Try instead of mysql1.000webhost.com to change with server IP address.
Example,
try {
Class.forName("com.mysql.jdbc.Driver");
Connection c = DriverManager.getConnection("jdbc:mysql://123.456.789.012:3306/mydatabase", "myusername", "mypassword");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

I would recommend you some reading first. This slide show might present you how Java EE applications are build.
Next you might want to read a bit more how to connect your application with a database.
Hibernate is one of the most widely used tools for establishing connection between database and your Java program. It allows you to separate your connection data (e.g. username, password, connection url) from your code with use of configuration files in xml format. The line:
Connection c = DriverManager.getConnection("jdbc:mysql://mysql1.000webhost.com/mydatabase", "myusername", "mypassword");
Is a very dangerous way of establishing connetion, as you are providing confidential credentials inside the code. There are ways to retreive this information from binary files.
You also asked, if is it worth having some local version of your database. The anwser is: Yes. Having your database locally might significantly speed up the time required for development and testing. It also allows you to work on your code even when no internet connection is available.
Providing authentication with use of MAC address is a very dangerous idea. Those addresses are attached to given machines. In other words the user will be able to connect to your application only with machine, on which he or she created an account. When using other computer (e.g. laptop at work) authentication will be denied.

Related

Mysql in localhost

I have already installed Mysql on my computer and I have already created my database.
I have also created a Java program that connects to the database using the code attached below.
If I publish the program, will the connection to the database work correctly on other users' computers?
Will it be a problem if the code is in "localhost"?
Thanks to everyone who will help me!
public static Connection getConnection() throws Exception{
try {
String url = "jdbc:mysql://localhost:3306/mybooks?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
String username = "root";
String password = "mypassword";
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
} catch (Exception e) {
System.out.println(e);
}
return null;
}
You will need to put a MySQL server on a machine that's accessible to all your users via a LAN or the internet. That machine will need to have a usable internet address, either a hostname like database.rich05.example.com or some IP address like 192.0.2.123.
Then you'll need to create an accounts and passwords on the MySQL server for your users. You may choose to create just one account for all your users, or a separate one for each user. (I suggest the latter approach.)
Then you'll need to change your connection string from
jdbc:mysql://localhost:3306/mybooks?whatever=val&whatever=val
to
jdbc:mysql://192.0.2.123:3306/mybooks?whatever=val&whatever=val
or
jdbc:mysql://database.rich05.example.com:3306/mybooks?whatever=val&whatever=val
or whatever the internet address is. Then you'll configure your program to use the correct usernames and passwords.
In Java programs, connection strings and usernames are often stored in properties files.
Explaining all this in detail is too much for a Stack Overflow answer. Give it a try and ask more specific questions if you need to.

How To Improve SQL Connection

Hello every body I'm working on application which is sends data from android app to MS-SQL server and main windows software in C#, which is receives data from MS-SQl server.
The problem is the programs takes too time to build a connection especially in android app some times it crash the app.
By the way the Internet speed some times goes week in our country.
I searched for a solution but not found in internet and I cannot figure out any way to solve it.
And I see the Viber, Watsapp, Massenger ... etc it sends data instantly or synchronously even if Internet speed is week.
So can I get some help and suggestion.
And there is a connection Helper method :
public Connection connections(){
IP="www.examlple.net";
DB="DB_test";
DBUserName="admin";
DBPassword="*****";
StrictMode.ThreadPolicy policy= new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection=null;
String connectionURL=null;
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
connectionURL ="jdbc:jtds:sqlserver://"+IP+";DatabaseName="+DB+";integratedSecurity=true;user="+DBUserName+";password="+DBPassword;
connection = DriverManager.getConnection(connectionURL);
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return connection;
}
For the sake of completeness, with JTDS you can set both a loginTimeout and a socketTimeout on a connection string. Refer to the remarks on these here.
But as others have said, you should go through a web API of some sort. Do you really want to expose your SQL server to the internet?
Also, I just noticed you have specified integrated security=true, and you have also specified a username and password. You can't do that. One is for windows auth (integrated security) and the other is for SQL auth (user and password). You would have to use a username and password. But don't. Don't do this. go through a web API.

Difficulty connecting to database using SQLserver jdbc

I'm trying to connect to my database using sqljdbc4, I'm pretty new to this so i followed a couple of tutorial but it still doesn't seem to work, When i try to run the program i get this Exception:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user ''. ClientConnectionId:f181fd37-7e28-4392-ac86-02914c2090e1
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
And this is my code:
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DBank;","","");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
You are not passing any authentication credentials. If you want to use integrated security (windows authentication), then you need to explicitly specify that in your connection URL and you need to load the native library required for this.
See Connecting with Integrated Authentication On Windows on Windows on MSDN.
This essentially comes down to including the folder containing the (32 bit or 64 bit) sqljdbc_auth.dll in the java.library.path system property (see link for details) and adding integratedSecurity=true to your connection string:
DriverManager.getConnection(
"jdbc:sqlserver://localhost:1433;databaseName=DBank;integratedSecurity=true");
You are passing empty username and password while connecting to the database in getConnection method:
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DBank;","","");
Try supplying the db username and password, for example:
DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DBank;","myusername","mypassword");

Connect to mysql remote database using JDBC?

I'm a java beginner and I'm working on a simple application which connects to a remote mysql database using JDBC. I've tested it locally and it works just fine, however I cannot get it to work on for my remote server.
I don't think its of much use but heres the code:
Connection connection = null;
String dburl = "jdbc:mysql://314159265:3306/Db_Name";
String userName = "user";
String passWord = "password";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(dburl, userName, passWord);
Statement st = connection.createStatement();
String query = "INSERT INTO Example (`TestColumn`) VALUES('hello')";
int rsI = st.executeUpdate(query);
System.out.println("Hi");
}catch (Exception e) {
System.out.println(e);
} finally {
if (connection != null) {
try {
connection.close();
System.out.println("Database connection terminated");
} catch (Exception e) { /* ignore close errors */ }
}
}
When I run this, I get the following message:
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.
I'm pretty sure it must be some kind of server configuration issue.
Notes:
Username, password, IP, database name, etc. are just examples.
This could be a firewall problem, or a configuration problem. But I don't think it is a coding problem at all - you need to start troubleshooting the connection.
Trouble shoot by attempting to use third party client apps to connect to mysql. This will indicate whether it is configured for external access. Although it doesn't ensure that JDBC is visible from the outside, it does rule out some potential firewall problems.
Follow this guide to help you mess with your configurations
Remote MYSQL Database Access
If you are still stuck, it could be a coding problem so check out this page:
How to connent to a remote mysql database with java?
P.S. I am assuming you are using unix as the operating system.
I guess 314159265 could be replaced by some address....
like jdbc:mysql://localhost:3306/
or jdbc:mysql://127.0.0.1:3306/

How can i check if MySQL and Tomcat are running?

I've created a Java application that is split in different subcomponents, each of those runs on a separate Tomcat instance. Also, some components use a MySQL db through Hibernate.
I'm now creating an administration console where it's reported the status of all my Tomcat instances and of MySQL. I don't need detailed information, but knowing if they are running or not it's enough.
What could be the best solution to do that?
Thanks
Most straightforward way would be to just connect the server and see if it succeeds.
MySQL:
Connection connection = null;
try {
connection = DriverManager.getConnection(url, username, password);
// Succes!
} catch (SQLException e) {
// Fail!
} finally {
if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}
Tomcat:
try {
new URL(url).openConnection().connect();
// Succes!
} catch (IOException e) {
// Fail!
}
If you want a bit more specific status, e.g. checking if a certain DB table is available or a specific webapp resource is available, then you have to fire a more specific SELECT statement or HTTP request respectively.
I assume that you know the ports of which are running in advance (or from configuration files). The easiest way to check is to make socket connections to those ports like a telnet program does. Something like:
public boolean isServerUp(int port) {
boolean isUp = false;
try {
Socket socket = new Socket("127.0.0.1", port);
// Server is up
isUp = true;
socket.close();
}
catch (IOException e)
{
// Server is down
}
return isUp;
}
Usage:
isTomcatUp = isServerUp(8080);
isMysqlUp = isServerUp(3306);
However, I would say that is a false-negative check.. Sometimes it says server UP but the server is stuck or not responding...
I would make sure that what ever monitoring you setup is actually exercising some code. Monitoring the JVM via jmx can also be helpful after the fact. Check out http://www.cacti.net/ .
Firing a simple fixed query through MySQL
SELECT 'a-ok';
and have the .jsp return that a-ok text. If it times out and/or doesn't respond with a-ok, then something's hinky. If you need something more detailed, you can add extra checks, like requesting now() or something bigger, like SHOW INNODB STATUS.
The easiest thing is to look for the MySQL and Tomcat PID files. You need to look at your start scripts to make sure of the exact location, but once you find it, you simply test for existence of the pid file.
Create a servlet as a status page. In the servlet perform a cheap query, if the query succeeds let the servlet print OK otherwise Error. Put the servlet into a war and deploy it to all instances.
This could be used for checks in yor admin console by doing a loop over all instances.
I'd create a simple REST webservice that runs on each Tomcat instance and does a no-op query against the database. That makes it easy to drive from anywhere (command line, web app, GUI app, etc.)
If these are publicly available servers you can use a service like binarycanary.com to poll a page or service in your app.

Categories