I am working on a interface in java swing.we have four system connected with a lan.the interface is for accessing the database from the other system in the same local area network i used the following code to access the database by giving the ip address,database name,tablename but i could not connect the other systems database.how can i do this?
public void dbconnection() {
String name = "";
String port = "3306";
String user = "systech";
String pass = "systech";
String dbname = "cascade_demo";
String host="192.168.1.61";
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://"+host+":"+ port + "/" + dbname;
System.out.println("URL:" + url);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url, user, pass);
String qry2 = "select * from item_master";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(qry2);
while (rs.next()) {
name = rs.getString(1);
System.out.println("Name:" + name);
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
System.out.println("Exception:" + e);
}
}
Use below code
public void dbconnection() {
String name = "";
String port = "3306";
String user = "systech";
String pass = "systech";
String dbname = "cascade_demo";
String host="192.168.1.61";
try {
String url = "jdbc:mysql://"+host+":"+ port + "/" + dbname;
Class.forName("com.mysql.jdbc.Driver").newInstance ();
Connection con = DriverManager.getConnection(url, user, pass);
String qry2 = "select * from item_master";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(qry2);
while (rs.next()) {
System.out.println("Name:" + rs.getString(1));
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
System.out.println("Exception:" + e);
}
}
Also, make sure to include jar file for connecting. You will get jar file here.
Update 1:
So, you have a
CommunicationsException: Communications link failure
I'm quoting from this answer which also contains a step-by-step MySQL+JDBC tutorial:
If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException:
Communications link failure, then it means that the DB isn't reachable at all. This can have one or more of the following causes:
IP address or hostname in JDBC URL is wrong.
Hostname in JDBC URL is not recognized by local DNS server.
Port number is missing or wrong in JDBC URL.
DB server is down.
DB server doesn't accept TCP/IP connections.
DB server has run out of connections.
Something in between Java and DB is blocking connections, e.g. a firewall or proxy.
To solve the one or the other, follow the following advices:
Verify and test them with ping.
Refresh DNS or use IP address in JDBC URL instead.
Verify it based on my.cnf of MySQL DB.
Start the DB.
Verify if mysqld is started without the --skip-networking option.
Restart the DB and fix your code accordingly that it closes connections in finally.
Disable firewall and/or configure firewall/proxy to allow/forward the port.
Update 2
If your system is Windows, go to Start>>Run.
Type command. This will open command prompt.
Type "ping 192.168.1.61"
You might get reply in below format.
Pinging 192.168.1.61 [192.168.1.61] with 32 bytes of data:
Reply from 192.168.1.61: bytes=32 time=101ms TTL=124
If you don't get something in above format, then your MYSQL Server with ip 192.168.1.61 is NOT REACHABLE. Ask your team to start the server first. :(
If you have Linux version, open terminal and follow step 3.
Also check below link. Those might help you...
http://www.cyberciti.biz/tips/how-do-i-enable-remote-access-to-mysql-database-server.html
You should down load the jdbc driver and replace
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
by
Class.forName("com.mysql.jdbc.Driver");
If you still have issues asfter replacing Obdc stuff, please post the exception.
ALso check firewall settings and DB permissions.
If you'll get exception your app will not free system resources. This will work better:
} finally {
try {
rs.close();
st.close();
con.close();
} catch( Exception e ) {
e.printStackTrace();
}
}
Related
I am trying to connect to a server (via JDBC) which requires a password, but a blank username. When I try using an empty String ("") it causes an error:
java.sql.SQLException: invalid arguments in call
The code I am using worked to connect to another server (which requires username and password), so it is operable; just not in this specific case (empty string username). I also can access the connection for this specific server which requires no username via SQLDeveloper, so that's not offline or inaccessible. In SQLDeveloper I can enter an empty username field without incident.
From what I've read one can connect with JDBC with username and password, or with neither. But I can't find a solution for a blank username. There must be a hacky way around the problem.
private Connection getConnection() throws SQLException
{
OracleDataSource ds = new OracleDataSource();
ds.setURL("jdbc:oracle:thin:#" + serverName + ":" + portNumber + ":" + sid);
System.out.println("attempting connection");
connection = ds.getConnection(textFieldUsername.getText(), new String(passwordField.getPassword()));
System.out.println("connection established");
return connection;
}
Have you tried to connect through the DriverManager interface?
Connection conn = DriverManager.getConnection(url, props);
Where props doesn't have any entry for the username.
My requirement is to check can we connect to a database with no schema defined through a java program and create a database.
this works fine
Connection connection =
DriverManager.getConnection("jdbc:db2://wcspocca-db.cloudapp.net:50001/db2inst1","vmadmin","password#123;");
database: db2
schema: db2inst1
but
Connection connection =
DriverManager.getConnection("jdbc:db2://wcspocca-db.cloudapp.net:50001/","vmadmin","password#123;");
fails
WHY?
com.ibm.db2.jcc.am.mo: [jcc][10165][10045][4.7.85] Invalid database URL syntax: jdbc:db2://wcspocca-db.cloudapp.net:50001/. ERRORCODE=-4461, SQLSTATE=42815
DriverManager.getConnection("jdbc:db2://wcspocca-db.cloudapp.net:50001/!!DBNAME!!","vmadmin","password#123;");
How I usually connect to a database using jave is like the following: Spacing it out to allow you to read the text below
//Wide Scope Variables
static Connection conn = null; //right now this connection is off
static String dbURL = "database url"; //I use SQL developer and your able to grab the connection url there
static String user = "This can be empty and ask user for input of hard code the user name";
static String pass = "same as above";
In the method where you want to check the driver and connection I usually do it like this
//Register the Driver
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException e)
{
System.err.println(e.getMessage());
}
//Set up connection
try
{
conn = DriverManager.getConnection(dbURL,user,password);
conn.clearWarnings();
stmt = conn.createStatement();
}
catch(SQLException e)
{
System.err.println(e.getMessage());
}
The first try catch code registers the driver to the SQL developer then the second try catch sets up the connection to the database. This helped save me a lot of head aches and I find it the most Direct route when using java.
Because in the second example the database is not specified. You can find the requirements in the DB2 JDBC documentation:
>>-+-jdbc:db2:------+--//--server--+---------+--/--database----->
+-jdbc:db2j:net:-+ '-:--port-'
'-jdbc:ids:------'
>--+---------------------------+-------------------------------\><
'-:--| connection-options |-'
The database parameter is not optional.
check the url carefully, after the port number if you do not put database name which you want to connect then how it will connect. Its like you are giving a home address whitout the plot number.
I want to connect oracle DB with JAVA, I have code like this :
Class.forName("oracle.jdbc.driver.OracleDriver");
dbURL = "jdbc:oracle:thin:#localhost:1521:DB";
con = DriverManager.getConnection(dbURL, "sys as sysdba" , "");
return con;
it's not working, but I tried with command promt like this conn /as sysdba, it can be Connected. I have beed googling about this article but all of code not work.
Anyone can help.
Thanks
To log on as SYSDBA with the JDBC Thin driver you must configure the server to use the password file. So you need to provide password for sys.
Try catching the exception, it must provide more information about the problem.
public static Connection getConnection(String name, String pass) {
connection = null;
try {
Class.forName(JDBC_DRIVER);
connection = DriverManager.getConnection(DB_URL, name, pass);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return connection;
}
Do you get the same error when trying to connect with a different username and password instead of "sys as sysdba" , "" ?
Also, in the dbURL, check if the url and database name are set correctly.
The problem most likely lies in the empty password. Try substituting "" with "()". If the sys really uses empty password, it must work. If it doesn't help, consider changing the password manually by alter user
when i ll try to connecting mysql using jdbc means its succeessfully connected on localhost.but i replaced localhost by my ip address means itz not connected..y dis error is came..how it is cleared..help me.
dis is my coding:
package com.retrieve;
import java.sql.*;
public class retrieve{
public static void main(String[] args) {
System.out.println("Getting All Rows from a table!");
Connection con = null;
String url = "jdbc:mysql://192.168.1.249:3306/";
String db = "login";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+db, user, pass);
try{
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM login");
System.out.println("username: " + "\t" + "password: ");
while (res.next()) {
String s = res.getString("username");
String s1 = res.getString("password");
System.out.println(s1 + "\t\t" + s);
}
con.close();
}
catch (SQLException s){
System.out.println("SQL code does not execute.");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
The error is:
Getting All Rows from a table!
java.sql.SQLException: Data source rejected establishment of connection, message from server: "Host '192.168.1.249' is not allowed to connect to this MySQL server"
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:650)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:1808)
at com.mysql.jdbc.Connection.(Connection.java:452)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:411)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at com.retrieve.retrieve.main(retrieve.java:15)
With your MySQL server you need to add permission for your user to be able to access your db from the specified IP
Execute following query from mysql console
GRANT ALL ON YOUR_DB.* TO 'root'#'192.168.1.249';
create user 'login'#'192.168.1.249' on your mysql server.
mysql builds users from 'name' (here - login you specified) and 'host' (address from which user connects to server). You can use '%' char to describe 'all hosts'.
consider reading this section of docs:
http://dev.mysql.com/doc/refman/5.1/en/user-account-management.html
Try to close all the resources like Statment, ResultSet objects etc.Also, as #Jigar mentione, grant permission to the users as well.
Please check your port .If you changed your port number ,you got this error like
"com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure"
How to access the another system mysql database through java program?Am using the following program but i have get the communication error?what are the changes are need to connect the another system mysql database?
Public void dbconnection() {
String name = "";
String port = "3306";
String user = "system";
String pass = "system";
String dbname = "cascade_demo";
String host="192.168.1.61";
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://"+host+":"+ port + "/" + dbname;
System.out.println("URL:" + url);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url, user, pass);
String qry2 = "select * from item_master";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(qry2);
while (rs.next()) {
name = rs.getString(1);
System.out.println("Name:" + name);
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
System.out.println("Exception:" + e);
}
}
You're not creating an instance of the driver class:
Class.forName("com.mysql.jdbc.Driver").newInstance();
[update: not necessary after all, ignore that]
And you're also referencing "sun.jdbc.odbc.JdbcOdbcDriver", is that necessary? If so, shouldn't you instantiate it also? [update: probably not]
If it works with localhost, and not with the IP specified, you need to configure mysql to listen on all ports.
jcomeau#intrepid:/tmp$ cat dbconnection.java; javac dbconnection.java; sudo java -cp .:/usr/share/maven-repo/mysql/mysql-connector-java/5.1.16/mysql-connector-java-5.1.16.jar dbconnection
import java.sql.*;
public class dbconnection {
public static void main(String args[]) {
String name = "";
String port = "3306";
String user = "root";
String pass = "";
String dbname = "imagetagging";
String host="127.0.0.1";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://"+host+":"+ port + "/" + dbname;
System.out.println("URL:" + url);
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection(url, user, pass);
String qry2 = "select * from taggers";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(qry2);
while (rs.next()) {
name = rs.getString(1);
System.out.println("Name:" + name);
}
rs.close();
st.close();
con.close();
} catch (Exception e) {
System.out.println("Exception:" + e);
}
}
}
URL:jdbc:mysql://127.0.0.1:3306/imagetagging
Name:1
Name:2
Name:3
Name:4
Name:5
Name:6
Name:7
Name:8
Name:9
Name:10
Name:11
Name:12
Name:13
Name:14
Name:15
Name:16
Name:17
Name:18
Name:19
Name:20
Name:21
As I understand you just need to specify another connection string, with another host and other credentials, e.g.:
...
String port = "3306";
String user = "user_name";
String pass = "password";
String dbname = "db_name";
String host="host_name";
...
You have to do 3(with 4th step optional) simple things to connect to your remote mysql database server.
Open up any GUI tool for mysql database management (your IDE, Mysql Workbench or smth else), check if you can connect to your database by specifying your credentials, host, port and database name.
If that succeeds you know there is nothing wrong on the db part (go to 3), if not, and you are sure you do everything correctly up to this point go to point 2.
check out this post on how to enable remote access to your db and try again (go to pkt 1)
You would have to clean up a bit your code, have a look into simple and to the point tutorial on how to connect and execute simple sql statements with java on Vogella tutorial
Once everything is working correctly, remember to give +1 on Vogella tutorial, praise the cybercity or any other website for the explanation on how to enable remote access on you db and don't forget to come back to stackoverflow and reward all good answers :)