Connecting to MySql Database using Java - java

So I've been teaching myselft mysql and am trying to integrate it into my Java code. I've looked at some past code snippets and tutorials and I can't seem to figure out why my code is incorrect. (removed password for obvious reasons)
Here's what I'm using to connect
public static void connectionToMySql(){
String host = "mysql9.000webhost.com";
String username = "a9808220_pin";
String pass = "";
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection = DriverManager.getConnection(host,username,pass);
/*insert code*/
connection.close();
System.out.println("It worked :)");
} catch (Exception e) {
System.out.println("Something went wrong :(");
e.printStackTrace();
}
}
I get an exception that there's no suitable driver. I'm not sure why because I have the jar downloaded and pathed correctly

Your connection should be a JDBC URL in the form
String url = "jdbc:mysql://mysql9.000webhost.com:3306/";
Now in order for this to work you should:
1) Verify that mySQL is running on the host mysql9.000webhost.com
2) Verify that the port is the default port ie 3306, if not change the code above to use the right port

String host should be like
String host = "jdbc:mysql:ip:port"//ip or hostname
example code that works for me...
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:1433;"
+"databaseName=test;"
+"user=sa;"
+"password=xxxxx;");
System.out.println("connected");

Related

Unable to connect to Azure using JDBC (based upon the connection string and samples provide) due to SSL issue

Am getting the following error: com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "Connection reset by peer: socket write error."
import java.sql.*;
import com.microsoft.sqlserver.jdbc.*;
public class SQLDatabaseConnection {
// Connect to your database.
// Replace server name, username, and password with your credentials
public static void main(String[] args) {
String connectionString =
"jdbc:sqlserver://XXXXX.database.windows.net:1433;"
+ "database=VDB;"
+ "user=XXX#VVV;"
+ "password=XXXX;"
+ "encrypt=true;"
+ "trustServerCertificate=false;"
+ "hostNameInCertificate=*.database.windows.net;"
+ "loginTimeout=30;";
// Declare the JDBC objects.
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
// Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(connectionString);
// Create and execute a SELECT SQL statement.
String selectSql = "SELECT TOP 2 * from Application";
statement = connection.createStatement();
resultSet = statement.executeQuery(selectSql);
// Print results from select statement
while (resultSet.next()) {
System.out.println(resultSet.getString(2) + " "
+ resultSet.getString(3));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Close the connections after the data has been handled.
if (resultSet != null) try {
resultSet.close();
} catch (Exception e) {
}
if (statement != null) try {
statement.close();
} catch (Exception e) {
}
if (connection != null) try {
connection.close();
} catch (Exception e) {
}
}
}
}
I'm only trying to do the "sample" connection snippet of code as referenced on the Azure site (which points to a MS entry), modified only to match my db and test table but without success.
Having reviewed all there is to know, I have:-
ensured that I'm using the right sqljdbc (I've tried all 4)
have the sqlauth.dll on the CLASSPATH
have set the sample up EXACTLY as shown; and incorporated the string that Azure offers.
I have tried various combinations of encrypt and trust without success. As I'm a newbie to Java and Azure, I'm reluctant and unsure how to fiddle with the JVM security settings.
I've proven that my machine can talk to the Azure database (through a VB ODBC connection); and I've tested with the firewall down.
Any thoughts?
I tried to reproduce the issue, but failed that I could access my SQL Azure Instance using the code which be similar with yours.
The difference between our codes is only as below, besides using the connection string of my sql azure instance.
Using the driver sqljdbc4.jar from the sqljdbc_4.0 link.
Using the code Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); to load MS SQL JDBC driver.
Not adding the sqlauth.dll file into the CLASSPATH.
Check my client IP which has been allowed by SQL Azure IP firewall.
Using the sql select 1+1 to test my code, and get the value 4 from code result.getInt(1).
That's fine for me. If you can supply more detals for us, I think it's very helpful for analysising the issue.
Hope it helps.

Connecting to PostgreSQL on Amazon EC2 through Java

I want to connect to PostgreSQL database in java, which is on Amazon EC2.
I can connect to it using a postgres client on Mac called Postico.
I specify next info:
Nickname
Host (ec2-xx-xx-xx-xx.xx-xx-x.compute.amazonaws.com)
User
Password
Database name
SSH host
User
Password - blank
Private key - .pem file
I could not find any example about how to connect it in Java.
I found some RedshiftJDBC driver and added it to project.
than I tried this:
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("MySQL JDBC Driver Registered!");
try {
this.connection = DriverManager.getConnection("jdbc:postgresql://" +DNS+"/"+myDBname, MYSQLUSER, MYSQLPW);
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
I knew it would not work, but at least I tried))
I have no idea how to specify Private key in request (how to send it), or whatever.
Could someone help me ?
Thank you.
Try this the below code with PostgreSQL JDBC driver. You want to make the code a bit more resilient (e.g. check db for null in-between connecting and sending a query, etc.), but this should get you going.
private final String DB_HOST = "YOUR_EC2_HOSTNAME";
private final String DB_PORT = "5432";
private final String DB_USER = "YOUR_POSTGRES_USERNAME";
private final String DB_PASSWD = "YOUR_POSTGRES_PASSWORD";
private final String DB_NAME = "YOUR_POSTGRES_DBNAME";
private final String DB_URL = "jdbc:postgresql://" + DB_HOST + ":" + DB_PORT + "/" + DB_NAME;
private final String INSERT = "INSERT INTO articles (date, name, uuid) VALUES (?, ?, ?)";
private Connection db = null;
public PostgreSQLService() {
try {
Class.forName("org.postgresql.Driver");
db = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWD);
} catch (ClassNotFoundException | SQLException ex) {
log.error(ex);
}
try (PreparedStatement st = db.prepareStatement(INSERT)) {
st.setEscapeProcessing(false);
st.setDate(1, new java.sql.Date(DateUtil.getToday().getTime()));
st.setString(2, "YOUR_NAME");
st.setObject(3, UUID.randomUUID());
if (st.executeUpdate() <= 0) {
throw new PostgreSQLServiceException("0 rows inserted while trying to insert a new row ::: " + st.toString());
}
} catch (SQLException sqle) {
throw new PostgreSQLServiceException("Received an SQLException trying to insert a row", sqle);
}
}
The Maven dependency is:
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.4.1208</version>
</dependency>
Note, you need to open up port 5432 in that EC2 instance's security group if you're executing this code from outside AWS.
I would also suggest looking at Amazon RDS. You can connect to it with the above code just the same as a Postgres instance running on EC2.
I hope this helps!
You don't specify that SSH info (SSH host, private key, etc.) when connecting from Java. The JDBC driver expects to be able to connect directly to the database server and does not support SSH tunneling. If you need to use SSH tunneling then you would have create that connection separately before starting the Java application.
If the Java application is running on AWS then you should be able to configure the network to allow a direct connection. If you are testing your Java application locally and need to connect to the remote database, then you run the ssh command locally to open a tunnel first. See this documentation: http://www.postgresql.org/docs/8.2/static/ssh-tunnels.html or this answer: PostgreSQL via SSH Tunnel

connecting with Derby from within the java application

this program works fine when i connect the java db under the 'Services' tab in netbeans but when i try to open the executable jar file of the prog outside neatbeans it doesn't work at all. I want this java application to be accessible by multiple users as i wish to put it on the my local network so i figured that i need to connect to the Derby database in network mode....am i correct.?.....how should i fix this..?following is code snipet of my application
public void DoConnect() {
try {
/*
** Load the Derby driver.
** When the embedded Driver is used this action start the Derby engine.
** Catch an error and suggest a CLASSPATH problem
*/
Class.forName("org.apache.derby.jdbc.ClientDriver");
try {NetworkServerControl server = new NetworkServerControl();
server.start (null);}
catch(Exception e)
{
System.err.println(e.getMessage());
}
System.out.println(driver + " loaded. ");
} catch (java.lang.ClassNotFoundException e) {
System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
System.out.println("\n >>> Please check your CLASSPATH variable <<<\n");
}
try {
//CONNECT TO THE DATABASE
String host = "jdbc:derby://localhost:1527/Employee";
String uName = "admin";
String uPass = "admin";
//EXECUTE SQL QUERY AND LOAD RESULTSET
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String SQL = "SELECT * FROM Workers";
rs = stmt.executeQuery(SQL);
//MOVE CURSOR TO FIRST RECORD AND GET DATA
rs.next();
int id_col = rs.getInt("ID");
String id = Integer.toString(id_col);
String first_name = rs.getString("First_Name");
String last_name = rs.getString("Last_Name");
String job = rs.getString("Job_Title");
//DISPLAY THE FISRT RECORD IN THE TEXT FIELD
textID.setText(id);
textFirstName.setText(first_name);
textLastName.setText(last_name);
textJobTitle.setText(job);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
IMHO it is bad practice to use a Derby database in network mode and to start the server in the same application. You combine all weaknesses of both world :
you cannot access the database from the outside (you server has to be local)
what happens if you server is allready running (if multiple executions on same node) ?
I think it works fine under Netbeans, because Netbeans is doing all the housekeeping for you : starting the server when you access to it via Netbeans interface, and closing it when closing Netbeans.
I think you should try the folowing :
start a server (manually) from outside of your application
remove the code for launching server from your app
(and do not forget to stop server when you have finished with it ...)
By the way I cannot understand what you mean by "not even starting" : if you start it from command line, you should have at least an error message ...
The way you've written the program there is no reason to meddle with the services tab. You should be able to just run (debug) the program directly in NB. Set a breakpoint, debug and step through it. When that works you can try to run from the command line.

Android connection failure with MySQL Database

I am trying to connect to my MySQL database in a new project that I am working on. The error message that I receive is: CommunicationsExceptions: Communications link failure.
I have tried to connect to my friends database, and it is working correct, but as soon as I try with my own localhost server I get errors.
I have also tried to write the exact same code in a JAVAFX application in netbeans and it is working perfectly, it is like there is something wrong with android and localhosts..
Here is my code:
private Connection conn = null;
private String dbName = "world";
private String user = "root";
private String pwd = "root";
private Statement statement = null;
public void connectingDatabase() throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("Found instance");
} catch (Exception ex) {
System.out.println("No instance ");
}
try {
setConn(DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/" + getDbName() + "?user=" + getUser() + "&password=" + getPwd()));
System.out.println("Connecta till " + getDbName());
} catch (Exception ex) {
System.out.println("no connection");
System.out.println(ex);
}
}
If I use my friends IP instead of 127.0.0.1:3306 or localhost it is working.
Does someone have any expertise in this kinds of problems?
Since the code is running on Android device and you want to connect to the MYSQL server running on your desktop, you cannot use 127.0.0.1 for connecting to the database. Instead use the ip address of the machine where MySQL database is hosted.
If localhost or 127.0.0.1 is still not working. Assign a static IP on your computer/server i.e: 192.168.1.10 and then use that in your connection URL
Good luck.

cannot connect to database sql server on another pc from java app

I'm new to java and cannot connect to database sql server on another pc
I tried
public class ConnectDB {
public Connection connect() {
Connection cn = null;
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
cn = DriverManager.getConnection("jdbc:jtds:sqlserver://192.168.1.1/HR;instance=MSSQLSERVER", "sa", "pass");
//cn = DriverManager.getConnection("jdbc:jtds:sqlserver://192.168.1.1/HR:1433;instance=MSSQLSERVER", "sa", "pass");
//cn = DriverManager.getConnection("jdbc:jtds:sqlserver://192.168.1.1;instance=MSSQLSERVER;databaseName=HR", "sa", "pass");
}catch(ClassNotFoundException | SQLException e){
System.out.println("Error: " + e.getMessage() );
} return cn;
}
}
and got Network error IOException: Connection timed out: connect
TCP/IP is enabled and when i ping on cmd no late occur
please anyone can help me.
Did you open the remote access on your database?
http://www.sophos.com/fr-fr/support/knowledgebase/118473.aspx
The URL format for jTDS is:
jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]
So, to connect to a database called "HR" hosted by SQL Server running on 192.168.1.1, you may end up with something like this:
jdbc:jtds:sqlserver://192.168.1.1:1433/HR;instance=SQLEXPRESS;user=sa;password=pass
Or, if you prefer to use getConnection(url, "sa", "pass"):
jdbc:jtds:sqlserver://192.168.1.1:1433/HR;instance=SQLEXPRESS

Categories

Resources