I am attempting to connect to an Azure database via an android app I am creating, however I keep getting this particular error:
Network error IOException: Could not create socket.
I can connect to the database on my login activity successfully, but if I reuse the same code on a different activity it will not connect at all.
I have attempted to reformat the connection string, but the problem persists. This is my current code to connect which is the same in the Login Activity:
String username = "username";
String password = "password";
String host = "jdbc:jtds:sqlserver://databaseUrl:1433/database"
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
System.out.println("Connecting to database for duty...");
Connection conn = DriverManager.getConnection(host, username, password);
System.out.println("connected");
} catch (SQLException err) {
System.err.println(err.getMessage());
} catch (Exception e) {
System.err.println(e.getMessage());
}
Any help would be greatly appreciated
Related
When i am trying to connect using the below function, it is showing "Communication link failure " from the application but not when i try login mysql directly. What can be the reason for this , and i am trying to access using root in the application.
public static Connection getConnection() {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "12345");
} //end try
catch (Exception e) {
e.printStackTrace();
}
return con;
}
Ok - so I have been working on this for some time (sometimes not working on it), and I am ALMOST there but not yet. I am trying to tunnel into a mysql db and was able to successfully connect ssh using Jsch. But when I try to connect to the database, it gives me an "Access denied for user 'usernamne'#'localhost' (using password: YES)
Here is the following code: (of course I masked out sensitive info)
public void connect(){
String user = "user";
String password = "password";
String host = "host.com";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = null;
Properties info = new Properties();
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
jsch.addIdentity("/Users/user/.ssh/id_rsa", password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
if(session.isConnected()){
session.disconnect();
}
session.connect();
conn = DriverManager.getConnection("jdbc:mysql://localhost:4417/dbname","dbuser", "dbpassword");
System.out.print("Connection successful!" + "\n\n");
System.out.print("Connection:" + conn + "\n\n");
Statement stmt = conn.createStatement();
ResultSet resultSet = stmt.executeQuery("SELECT * FROM TABLENAME limit 1");
System.out.print(resultSet);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (JSchException j){
j.printStackTrace();
}
}
I've read other posts on here but I have not found the exact solution to my problem. I am able to ssh in correct. And what's even more interesting is that if I do the same exact procedure command_line, it works fine. So I don't know why it wouldn't work here.
Try this. it might help you . Already tested in my setup. Enjoy. :)
create db user in remote mysql db.
CREATE USER 'myuser'#'clientip' IDENTIFIED BY 'pass';
CREATE USER 'myuser'#'%' IDENTIFIED BY 'pass';
grant ALL ON mydb.* to 'myuser'#'clientip';
grant ALL ON mydb.* to 'myuser'#'%';
FLUSH PRIVILEGES;
Code for ssh tunneling.
int assigned_port;
final int local_port=8080;
// Remote host and port
final int remote_port=3306;
final String remote_host="192.168.150.139";
try {
JSch jsch = new JSch();
// Create SSH session. Port 22 is your SSH port which
// is open in your firewall setup.
session = jsch.getSession("sshuser", remote_host, 22);
session.setPassword("sshpassword");
// Additional SSH options. See your ssh_config manual for
// more options. Set options according to your requirements.
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
config.put("Compression", "yes");
config.put("ConnectionAttempts","2");
session.setConfig(config);
// Connect
session.connect();
// Create the tunnel through port forwarding.
// This is basically instructing jsch session to send
// data received from local_port in the local machine to
// remote_port of the remote_host
// assigned_port is the port assigned by jsch for use,
// it may not always be the same as
// local_port.
assigned_port = session.setPortForwardingL(local_port,
remote_host, remote_port);
} catch (JSchException e) {
LOGGER.log(Level.SEVERE, e.getMessage()); return;
}
if (assigned_port == 0) {
LOGGER.log(Level.SEVERE, "Port forwarding failed !");
return;
}
// Database access credentials. Make sure this user has
// "connect" access to this database;
// these may be initialized somewhere else in your code.
final String database_user="myuser";
final String database_password="pass";
final String database = "mydb";
// Build the database connection URL.
StringBuilder url =
new StringBuilder("jdbc:mysql://localhost:");
// use assigned_port to establish database connection
url.append(assigned_port).append ("/").append(database).append ("?user=").
append(database_user).append ("&password=").
append (database_password);
try {
Class.forName(
"com.mysql.jdbc.Driver");
System.out.println(url.toString());
java.sql.Connection connection =
java.sql.DriverManager.getConnection(url.toString());
String q="select * from customer";
PreparedStatement ps=connection.prepareStatement(q);
ResultSet rs= ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getInt(1)+rs.getString(2));
}
} catch (ClassNotFoundException |
java.sql.SQLException e) {
LOGGER.log(Level.SEVERE, e.getMessage());
e.printStackTrace();
}
finally{
session.disconnect();
}
How can I connect with java that interacts with my database? I am using the XAMPP for mysql
And I am having a problem knowing what port I am using.. I just copied the port which other are using from the internet But I dont really know what is my port number for the database
Also how do I check for the port going to data base?? //localhost:3306
HERE is my code:
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.print("COnnection succesfull");
}
catch(Exception ex)
{
System.out.print("Unable to connect ");
}
try
{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test?user=root&password=";
Connection con = DriverManager.getConnection(url);
System.out.print("Connection Stablished");
}
catch(Exception ex)
{
System.out.print("Connect cannot stablished");
}
I think you don't need to specify port if you want to connect to XAMPP's MySQL. Try this, this works for me:
String dbn = "yourdatabasename";
String usr = "root";
String pwd = "";
String connectionURL = "jdbc:mysql://localhost/"+dbn;
try {
// Load the Driver class.
Class.forName("com.mysql.jdbc.Driver");
// If you are using any other database then load the right driver here.
con = (Connection) DriverManager.getConnection (connectionURL, usr, pwd);
}
catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
To check which port MySQL is running on, you can check a file 'my.ini' located in
C:\Program Files (x86)\MySQL\MySQL Server 5.1 (Windows 8, might vary, but its the install directory).
The default is 3306 to my knowledge.
The code looks right, though I usually pass the username and password with
DriverManager.getConnection(url, username, password);
I try to know if I can connect Java to SQL Server using these codes :
package pkgtry;
import java.sql.*;
public class NewMain {
public static void main(String[] args) {
String connectionUrl="jdbc:sqlserver://(local):1433;DatabaseName=OJT;user=sa;password=''";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
String SQL = "";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next()) {
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
}
but on my end it show an error and says :
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection
to the host (local), port 1433 has failed. Error: "null. Verify the
connection properties, check that an instance of SQL Server is running
on the host and accepting TCP/IP connections at the port, and that no
firewall is blocking TCP connections to the port.".
What does it mean? How to fix it?
It means JDBC is unable to connect to the database server. It couldn't find the host (local), did you mean to put localhost here instead of (local)?
String connectionUrl="jdbc:sqlserver://(local):1433;DatabaseName=OJT;user=sa;password=''";
Do the following:
1)Make sure that the server is running on your computer . That is, its listening to incoming connection requests .
To do the above, use an IDE (I prefer netbeans....its very easy to use) and try creating a connection to the database. You will have to input username, password, databasename, the port no. on which the server is running and so on.
If you get a successful connection, your server is running fine.
If not, make sure you are using the correct driver, you have mentioned the right port number, right database name and so on.
2)Copy the connection string generated and replace it in the connection URL. I feel you should have a "localhost" instead of "(local)" in your connection string. But to be sure, just copy the connection string generated by your IDE.
3)Try connecting again and see if it works. It mostly should.
<%
String connectionUrl="jdbc:sqlserver://localhost:1433;DatabaseName=databaseNames;";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
out.println("<p>Driver not found:" + e + e.getMessage() + "</p>" );
}
try {
Connection conn = DriverManager.getConnection (connectionUrl, "sa", "yourPassword");
I'm new to servers and databases. I've been trying to test out a java application that connects, reads and modifies a Mysql database that is hosted on amazon ec2.
System.out.println("-------- MySQL JDBC Connection Testing ------------");
String DNS = "MYDNS";
String myDBname = "DBNAMe"
String MYSQLUSER = "USER";
String MYSQLPW = "PW";
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("MySQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://" +DNS+#"/"+myDBname, MYSQLUSER, MYSQLPASS)
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
currentDir = "broke";
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
The issue is that despite being able to connect using the credentials via Mysql workbench, adding 3306 to my security group, binding 0.0.0.0 to mysql config, I still can't get a connection going (after doing some searching of other similar problems on SO)
Anyone have any insight as to what could be wrong? I have tried many variations of the getConnection() arguments.
connection = DriverManager.getConnection("jdbc:mysql://username#ec2-host/myDBname, MYSQLUSER, MYSQLPASS)