Unable to connect to mysql from java. mysql in another system - java

i wanted to connect to mysql from java code where mysql is in another system.
i have created a user in another machine "nilotpal".
Other machine address is 192.168.92.93.
I am able to ping to this machine. where am i missing?? can someone help?!!
The program i am using is:
import java.sql.*;
public class FirstExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://192.168.92.93:3306/tution";
// Database credentials
static final String USER = "nilotpal";
static final String PASS = "nilotpal";
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 database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}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)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample

Reference from Connect to mysql on a different server
Also make sure that mysql user nilotpal have remote connection permission. Other wise mysql-server will not allow your nilotpal user to login remotely. i.e. from your server (from program).
You can make sure that from mysql.user table.
mysql> select Host,User from user where User = "root";
+------------+------+
| Host | User |
+------------+------+
| 127.0.0.1 | root |
| ::1 | root |
| localhost | root |
| sgeorge-mn | root |
| % | root |
+------------+------+
4 rows in set (0.01 sec)
% means any host.
To create a user with remote connection permission, use following mysql query:
mysql> CREATE USER 'nilotpal'#'%' IDENTIFIED BY 'nilotpal';

First ping the machine using ping command, If it is pinging than check for the mysql user permission.
Granting Permission to user:
CREATE USER 'newuser'#'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON * . * TO 'newuser'#'localhost';
FLUSH PRIVILEGES;

Related

My Select Query with where clause not working

I am trying to fetch data from postgres database using where clause. It is returning null values. But running the same query in postgres worksheet, it is giving the datas.
And one more thing, I cannot able to use without double quotes(\"USER_INFO\"),while using without double quotes I am getting the error "column name does not exist".
But most of the online examples are without double quotes only.
Please help on this to resolve. Thanks in advance.
public class PostGreDB {
static final String JDBC_DRIVER = "org.postgresql.Driver";
static final String DB_URL = "jdbc:postgresql://localhost:5432/";
public static void main(String[] args) throws SQLException
{
Connection conn = null;
//Statement st = null;
try{
//STEP 2: Register JDBC driver
Class.forName("org.postgresql.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/","postgres","XXXX#1904");
//STEP 4: Execute a query
System.out.println("Creating statement...");
//st = conn.createStatement();
String sql;
sql = "SELECT * FROM public." + "\"USER_INFO\" where \"USER_INFO\".\"EMAIL_ID\" = ?";
System.out.println(sql);
try(PreparedStatement pst= conn.prepareStatement(sql)){
pst.setString(1 , "cppandi33#gmail.com");
pst.executeQuery();
try(ResultSet rs = pst.getResultSet()){
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
String first = rs.getString("USER_ID");
String last = rs.getString("USER_NAME");
String email = rs.getString("EMAIL_ID");
//Display values
System.out.print("User ID: " + first+"\n");
System.out.println("User Name: " + last+"\n");
System.out.println("Email: " + email);
}
rs.close();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
//STEP 6: Clean-up environment
// st.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
finally
{
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}//end finally try
}
}
}
When column contains "null" as data. It gives null only. Try to insert some data using insert query and after that we can try to fetch.

Using variables with JDBC

I want to have to use the users input for driverID, change onJob to true, if the user inputs the id.
So for example, if the user enters 1 as the driver id, the driver with id number 1 will have the onJob variable change to 1.
Here is my code currently;
public class TaxiDriver {
//String driverLocation = DRIVERFIRSTLOCATION;
//String destinationintoAPI;
//JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/DRIVER";
//Database credentials
static final String USER = "user";
static final String PASS = "password";
String driverId;
static Scanner reader = new Scanner(System.in);
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...");
System.out.println("Assign a driver to a jo...");
reader.nextInt();
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "UPDATE Drivers " +
"SET OnJob = 1 WHERE id = (driverId)";
stmt.executeUpdate(sql);
// Now you can extract all the records
// to see the updated records
sql = "SELECT id, license, first, last, OnJob, Email, Telephone, Address, Postcode, Veichle FROM Drivers";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
//retrieve by column name
int id = rs.getInt("id");
int license = rs.getInt("license");
String first = rs.getString("first");
String last = rs.getString("last");
int OnJob = rs.getInt("OnJob");
String Email = rs.getString("Email");
String Telephone = rs.getString("Telephone");
String Address = rs.getString("Address");
String Postcode = rs.getString("Postcode");
String Veichle = rs.getString("Veichle");
//Display
System.out.print("ID: " + id);
System.out.print(", license: " + license);
System.out.print(", First: " + first);
System.out.print(", Last: " + last);
System.out.print(", Email; " + Email);
System.out.print(", Telephone; " + Telephone);
System.out.print(", Address; " + Address);
System.out.print(", Postcode; " + Postcode);
System.out.print(", Veichle;" + Veichle);
if (OnJob == 0) {
System.out.println(": Driver is aviliable for pickup");
} else {
System.out.println(": Driver is not aviliable for pickup");
}
}
rs.close();
} 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
Right now I am getting these errors.
Connecting to a selected database...
Tue May 03 00:18:28 BST 2016 WARN: Establishing SSL connection without server's identity verification is not recommended.
According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set.
For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'.
You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Connected database successfully...
Assign a driver to a jo...
2
Creating statement...
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'driverId' in 'where clause'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:404)
at com.mysql.jdbc.Util.getInstance(Util.java:387)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:939)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3878)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2478)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2547)
at com.mysql.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1541)
at com.mysql.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2605)
at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1469)
at TaxiDriver.main(TaxiDriver.java:71)
Goodbye!
Much thanks in advance.
First, you actually need to read in a value into driverId somewhere.
That aside, the problem is with your SQL statement. You have:
String sql = "UPDATE Drivers " +
"SET OnJob = 1 WHERE id = (driverId)";
You are telling the database to look for records where the value of the records' id column equals the value of their driverId column.
You need to get the value of your driverId variable into the SQL rather than putting the actual characters "driverId" into the SQL, where (as you see) it is interpreted as the name of a column.
Using your approach you need to do:
String sql = "UPDATE drivers SET OnJob=1 WHERE id=" + driverId;
But dynamic SQL is dangerous and you are better off using a PreparedStatement. That will sanitize the user inputs and prevent SQL injection attacks.
String sql = "UPDATE drivers SET OnJob=1 WHERE id=?";
PreparedStatement ps = connection.createPreparedStatement(sql);
ps.setInt(1, Integer.parseInt(driverId));
ResultSet rs = ps.executeQuery();
You don't seem to be setting the driverId from user input.
Update your sql statement with valid id value, before executing the script.
i.e.
int driverId = 123;// This is user input, am assuming its type int.
String sql = "UPDATE Drivers SET OnJob = 1 WHERE id =" + driverId;
//now execute your sql
String driverId = "123";//This is user input, am assuming its type String.
String sql = "UPDATE Drivers SET OnJob = 1 WHERE id =" + "'" + driverId + "'";
//now execute your sql
Edit: I highly recommend QuantumMechanic's solution of using PreparedStatement as its much safer and hides all the handling of different types.

How to remove this bug while making jdbc simple program

Hi
I am making simple program of getting data from data base .I download sql for mac and insert schema , then table and entry .So I need to retrieve data from data base .I am using mysql .
I also insert conector jar of mysql .
I do like that
import java.sql.*;
![public class FirstExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/Database";
// Database credentials
static final String USER = "";
static final String PASS = "";
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 database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name, age FROM Employee";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("name");
// String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
// System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}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)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample][3]
Connecting to database...
Goodbye!
java.sql.SQLException: null, message from server: "Host '192.168.1.100' is not allowed to connect to this MySQL server"
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1086)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1114)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2493)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2526)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2311)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:834)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:416)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:347)
at java.sql.DriverManager.getConnection(DriverManager.java:582)
at java.sql.DriverManager.getConnection(DriverManager.java:185)
at FirstExample.main(FirstExample.java:21)
Your DB user is not allowed to connect to your MySQL server. In MySQL (strangely) there is something like a firewall and access is defined per user per host. You need to connect to MySQL via any SQL client and give access:
http://dev.mysql.com/doc/refman/5.1/en/adding-users.html
For example a bit too broad access but should work:
GRANT ALL PRIVILEGES ON *.* TO 'monty'#'%' WITH GRANT OPTION;
If you didn't create a user first:
CREATE USER 'monty'#'localhost' IDENTIFIED BY 'some_pass';

MySQL create or alter table

I am using MySQL 5.1 for my database and I'm sending the commands via a Java program (JBDC).
Is there a MySQL command for creating or altering a table?
Let's say I have a following table:
+----------+----------+
| column_a | column_b |
+----------+----------+
| value_a | value_b |
+----------+----------+
Now I want to use a command, that would add a column "column_c" if it didn't exist.
That would result in:
+----------+----------+----------+
| column_a | column_b | column_c |
+----------+----------+----------+
| value_a | value_b | |
+----------+----------+----------+
If the table didn't exist, it would create a new table with specified columns:
+----------+----------+----------+
| column_a | column_b | column_c |
+----------+----------+----------+
And finally, if the table had columns that weren't specified in the command, it would leave them untouched.
here is code in Java to create a table called Coffees:
/*Making the connection*/
try {//if any statements within the try block cause problems, rather than the program failing
//an exception is thrown which will be caught in the catch block
con = DriverManager.getConnection(url, "your username", "your password");
//create a statement object
stmt = con.createStatement();
//supply the statement object with a string to execute
stmt.executeUpdate("create table COFFEES (COF_NAME varchar(32), " +
"SUP_ID int, PRICE double, SALES int, TOTAL int, " +
"primary key(COF_NAME))");
//close the statement and connection
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
Explanation:
-In this example the java program interacts with a database that is located on a server, so we have to firstly we set the url of where the server is located and also sign in username and password, you may not be using the same method that I used.
-These need to be declared at the top of your java program:
String url = "jdbc:mysql://www.yoururlexample.co.uk";
Connection con;
Statement stmt
Hopefully this helps, you will then be able to insert data into the database and execute queries.
Edit:
This can be used in the executeUpdate statement if you want a table to be created if none exists with the name "COFFEES":
create table if not exists COFFEES
/*Making the connection*/
try {
//an exception is thrown which will be caught in the catch block
con = DriverManager.getConnection("jdbc:mysql:exaple.com", "username", "pass");
//create a statement object
stmt = con.createStatement();
//supply the statement object with a string to execute
stmt.executeUpdate("ALTER TABLE table_name ADD column_name datatype");
//close the statement and connection
stmt.close();
con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
I think that this is going to work for you.
Something like that might be a solution (this need at least one record in the table to work):
package com.stackoverflow.so20935793;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class App {
// complete this:
private static final String JDBC_URL = ".....";
private static final String JDBC_USER = ".....";
private static final String JDBC_PASS = ".....";
public static void main(final String[] args) {
Connection con = null;
PreparedStatement stm = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASS);
stm = con.prepareStatement("SELECT * FROM your_table LIMIT 1");
rs = stm.executeQuery();
if (rs.next() && rs.getMetaData().getColumnCount() == 2) {
// add your new column
}
} catch (final SQLException ex) {
// handle exception
} finally {
closeQuietly(rs);
closeQuietly(stm);
closeQuietly(con);
}
}
private static void closeQuietly(final AutoCloseable what) {
if (what == null) {
return;
}
try {
what.close();
} catch (final Exception ex) {
// ignore
}
}
}
(not tested)

getting out parameter from mysql stored procedure in java

I am having problem retrieving OUT parameter from mysql stored procedure in java.
CALL proc_after_topic_add('newtest',#result);
SELECT #result;
this query gives me desired out parameter but how would i retrieve it in java.I tried using CallableStatement but i get
java.sql.SQLException: Callable statments not supported.
error.Please guys help me.
I have tried following
String sql = "CALL proc_after_topic_add(?,?);";
CallableStatement cstmt = conn.prepareCall(sql);
cstmt.setString(1, topicname);
cstmt.registerOutParameter(2, java.sql.Types.INTEGER);
ResultSet rs = cstmt.executeQuery();
if (rs.next()) {
if (rs.getInt(1) == 1) {
res = 0;
} else {
res = -1;
}
}
I havent posted stored procedure code because there is nothing wrong with it.
PS:I a using mysql 5.5.21 and yes i should probably mention i am using mysql connector 3.0.15
Okay this is solved.For anyone who encounters the same problem,just download latest version of mysql connector.
Error in this line
cstmt.registerOutParameter(2, java.sql.Types.INTEGER);
change like this
String sql = "CALL proc_after_topic_add(?,?);";
cstmt.registerOutParameter(2, java.sql.Types.INTEGER);
Create a schema test and create a table employee in schema with 2 columns.
id and employeename and insert some data.
Use this Stored Procedure.
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`get_count_name1` $$
CREATE PROCEDURE `test`.`get_count_name1`(IN the_name VARCHAR(64),OUT
the_count INT)
BEGIN
SELECT COUNT(*) INTO the_count from employee where employeename=the_name;
END$$
DELIMITER ;
Use this example.
username and password are root and root for me. change as per your
requirement. Here i am counting the occurence of employeename="deepak"
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/test";
// Database credentials
static final String USER = "root";
static final String PASS = "root";
public static void main(String[] args) {
Connection conn = null;
CallableStatement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
String sql = "{call get_count_name1 (?, ?)}";
stmt = conn.prepareCall(sql);
//Bind IN parameter first, then bind OUT parameter
String name = "Deepak";
stmt.setString(1, name); // This would set ID as 102
// Because second parameter is OUT so register it
stmt.registerOutParameter(2, java.sql.Types.INTEGER);
//Use execute method to run stored procedure.
System.out.println("Executing stored procedure..." );
stmt.execute();
int count=stmt.getInt(2);
System.out.println(count);
stmt.close();
conn.close();
}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)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample

Categories

Resources