How to access the another system mysql database through java program? - java

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 :)

Related

JDBC connecting to MySQL on Amazon ec2

I'm a little new at that, but after starting my ec2 instance, and installing MySQL instance through RDS, I manage to connect to it through MySQL Workbench using ssh (.pem file).
My problem is I can't seem to have it right, when I'm trying to connect with jdbc, how exactly the authentication suppose to be done?
Here is my code, hope somebody can give me a hint on how to proceed:
public void create_table(){
Connection c = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection ("jdbc:mysql://127.0.0.1:3306/test","root", "password");
// c = DriverManager.getConnection ("jdbc:mysql://mydatabase.us-east-1.rds.amazonaws.com:3306/test","user="+"root"+"password=root", "");
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "CREATE TABLE USERS " +
"(ID INT PRIMARY KEY ," +
" DEVICE TEXT NOT NULL, " +
" NAME TEXT NOT NULL)";
stmt.executeUpdate(sql);
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
EDIT
I forgot few important details...
I wrote my code in Java using Jersey and servelt.
I Uploaded my WAR file to my ec2 instance.
Now after both web-app and MySQL server are running on the same instance, I want to build the communication..
Thank you!
Your SQL Syntax is incorrect. Text values are inserted as VARCHAR type in SQL. You can change the length of the text value depending on your need by changing the value with in the bracktes in VARCHAR(HERE). Try this code.
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/STUDENTS";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating table in given database...");
stmt = conn.createStatement();
String sql = "CREATE TABLE USERS " +
"(ID INTEGER not NULL," +
" DEVICE VARCHAR(255) not NULL," +
" NAME VARCHAR(255) not NULL,"+
"PRIMARY KEY (ID))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
how exactly the authentication suppose to be done?
you can use one of the form you use in your example but there are wrong things in both
c = DriverManager.getConnection ("jdbc:mysql://127.0.0.1:3306/test","root", "password");
you connect to localhost, if you have your test db on RDS you need to reference the end point of RDS like your second example
c = DriverManager.getConnection ("jdbc:mysql://mydatabase.us-east-1.rds.amazonaws.com:3306/test","user="+"root"+"password=root", "");
Here the end point will be correct but the string to connect is wrong. You can use the following form
String jdbcUrl = "jdbc:mysql://mydatabase.us-east-1.rds.amazonaws.com:3306/test?user=root&passwor‌​d=password";
Connection con = DriverManager.getConnection(jdbcUrl);
or
String url = "jdbc:mysql://mydatabase.test.us-east-1.rds.amazonaws.com:3306/";
String userName = "root";
String password = "password";
String dbName = "test";
Connection connection = DriverManager.getConnection(url + dbName, userName, password);
To find precisely your database end-point, login to the RDS console (make sure to select the right region if not us-east-1), select your database and the Endpoint will be there
The other potential issue you might run is on Security Groups
The DB instance was created using a security group that does not authorize connections from the device or Amazon EC2 instance where the MySQL application or utility is running. If the DB instance was created in a VPC, it must have a VPC security group that authorizes the connections. If the DB instance was created outside of a VPC, it must have a DB security group that authorizes the connections.
Check your security group rules for both the RDS DB and the ec2 instance and make sure you can connect that the ec2 instance has access to RDS server

How to confirm the insert query is a success?

I am inserting into the database with foll0wing code and it's working fine as I can see the data populates in the db, however I want to capture the result programmatically whether it was a success or failure
1) Here is the code to insert
public void SignUp(String last_name, String first_name, String email,
String password, String confirm_password, String phone) {
Connect connect = new Connect();
Connection conn = connect.Connection();
Statement stmt = conn.createStatement();
String query = "INSERT INTO users VALUES(NULL,('" + last_name + "'),('"
+ first_name + "'),('" + email + "'),('" + password + "'),('"
+ confirm_password + "'),('" + phone + "'))";
stmt.executeUpdate(query);
conn.close();
}
2) Here is the code I used to connect
public Connection Connection() {
Connection conn = null;
try {
String userName = "admin";
String password = "admin";
String url = "jdbc:mysql://localhost/project";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, userName, password);
System.out.println("\n Database connection established");
} catch (Exception e) {
e.printStackTrace();
System.err.println("\n Cannot connect to database server");
}
}
executeUpdate
public int executeUpdate(String sql)
throws SQLException
Returns: either the row count for INSERT, UPDATE or DELETE statements,
or 0 for SQL statements that return nothing
The simplest way would be to query for it directly. Its always a good idea to check the API, but with an update I am not sure that barring an exception there is a clean way to tell if it was successful (other than a lack of exceptions being thrown).
As a side note, take a look at Prepared Statements. It is generally not a good idea to use strait text when executing un-sanitized sql.

communication link failure in java

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"

Access mysql data base from another system using java

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();
}
}

connecting to database

can anyone help me how to connect my java forms to my mysql database?
i have this following codes but it didn't work...
private void saveActionPerformed(java.awt.event.ActionEvent evt) {
String value1 = textField1.getText();
String value2 = textField2.getText();
String value3 = textField3.getText();
String value4 = textField4.getText();
Connection con = null;
String url = "jdbc:mysql://localhost:3306/Marketing";
String driver = "com.mysql.jdbc.Driver";
String db = "Marketing";
String user = "root";
String pass = "";
System.out.println(value1 + value2 + value3 + value4);
try {
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
PreparedStatement st = con.prepareStatement("insert into clients (idclients, name, address, contact_person, contact_num) values(?,?,?,?,?)");
st.setString(2, value2);
st.setString(3, value3);
st.setString(4, value4);
st.executeUpdate();
JOptionPane.showMessageDialog(jPanel1, "Data is successfully inserted into database.");
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(jPanel1, "Error in submitting data!");
}
}
One problem I can see straight away is that your PreparedStatement expects 5 parameters (1 - 5) yet you're only setting 3!
Secondly, I'm not sure why you use DriverManager.getConnection( url +db , ... ) when your database URL already contains a database name, so use just DriverManager.getConnection(url,user,pass).
Having said that though, it would be good if you could clarify what exactly doesn't work?
There is problem with connection code :
url = jdbc:mysql://localhost:3306/Marketing
db = Marketing
url + db = jdbc:mysql://localhost:3306/MarketingMarketing
here you have to remove one extra marketing
The error is in this statement:
con = DriverManager.getConnection(url + db, user, pass);
The getConnection method connect to database on url specified in 1st parameter. Here you combine 2 variables named url and db so your connection url will become: jdbc:mysql://localhost:3306/MarketingMarketing which may be not the thing you want. Use only url instead of url + db.

Categories