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
Related
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.
I wrote some code which is supposed to pull information from my SQL server to tell what item is currently running.
The code runs fine on my windows machine, however I plan on running this on a raspberry pi running Raspbian Jessie. When I run the code it gives me the error
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host H79SQLMERINSQL, port 1433 has failed. Error: "null. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
When I run my code on my windows machine, it runs completely fine and gives me the item number
Here is the code:
public void main(String []args) {
// address of the SQL Server
String connectionUrl = "jdbc:sqlserver://H79SQLMERINSQL:1433;" +
"databaseName=runtime;user=sa;password=sa;";
//ErrorDialog errors = new ErrorDialog();
// Declaration of variables
//JDBC objects
Connection conURL = null;
Statement statement = null;
ResultSet receivedStatement = null;
//Variables for calling
String itemNumber = null;
//The following code is where all of the SQL Server connections happen and the setting of variables for use later
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conURL = DriverManager.getConnection(connectionUrl);
System.out.println("Not Prblem");
// Create and execute an SQL statement that returns some data.
statement = conURL.createStatement();
receivedStatement = statement.executeQuery("SELECT Value "
+ "FROM v_StringLive "
+ "WHERE v_StringLive.TagName IN ('MD_ProcessData.ItemNumberMD1')");
// Iterate through the data in the result set and display it.
while (receivedStatement.next()) {
itemNumber = receivedStatement.getString(1);
//Below code is for displaying to the system
/*System.out.println("The item number is: "+receivedStatement.getString(2) + " " + receivedStatement.getString(6));*/
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
System.out.println("Error 101: Connection to SQL Server has timed out");
e.printStackTrace();
}
finally {
if (receivedStatement != null) try { receivedStatement.close(); } catch(Exception e) {}
if (statement != null) try { statement.close(); } catch(Exception e) {}
if (conURL != null) try { conURL.close(); } catch(Exception e) {}
}
System.out.println("Item: " + itemNumber);
}
I made sure that in my SQL Server Configuration Manager that my IP Address are all set to TCP Port 1433 and the TCP Dynamic Ports is set to blank.
I have spent many hours trying to figure this out to no success, Any help is greatly appreciated.
Thanks everyone
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
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");
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.