Access Denied for database when using JDBC - java

I am working on a simple mariaDB database called movieDB and there is a mariaDB user called customerAgent. I know there are many similar on StackOverflow, but I am not using a root account, but a normal account with minimum granted privileges.
I can access the database movieDB in terminal via SSH like this:
[root#myServer]# mysql -ucustomerAgent -p123
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 102
Server version: 10.2.12-MariaDB MariaDB Server
Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> USE movieDB;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
MariaDB [movieDB]> show grants;
+----------------------------------------------------------------------------------------------------------------------------+
| Grants for customerAgent#localhost |
+----------------------------------------------------------------------------------------------------------------------------+
| GRANT Customer_Role TO 'customerAgent'#'localhost' |
| GRANT USAGE ON *.* TO 'customerAgent'#'localhost' IDENTIFIED BY PASSWORD '*23AE809DDACAF96AF0FD78ED04B6A265E05AA257' |
| GRANT USAGE ON *.* TO 'Customer_Role' |
| GRANT SELECT ON `movieDB`.* TO 'Customer_Role' |
| GRANT SELECT, INSERT ON `movieDB`.`orders` TO 'Customer_Role' |
+----------------------------------------------------------------------------------------------------------------------------+
5 rows in set (0.00 sec)
MariaDB [movieDB]> select current_role();
+----------------+
| current_role() |
+----------------+
| Customer_Role |
+----------------+
1 row in set (0.00 sec)
MariaDB [movieDB]>
But when I execute JDBC codes on localhost, access is denied at the line stmt.execute("USE movieDB");:
Access denied for user 'customerAgent'#'localhost' to database 'movidDB'
The java JDBC codes are: (I have removed some unnecessaries in the class, but in the case that I missed anything important, please do point out!)
import java.sql.*;
import java.util.*;
Class movieDBFoundation {
static private String DBServerAddress = "localhost";
static private Connection conn;
static private String getDBServerAddress() {
return DBServerAddress;
}
public static void main(String[] args) {
System.out.println("Connection started.");
if(DBConnect()) {
System.out.println("Connection succedded.");
}
else {
System.out.println("Connection failed.");
return;
}
}
static private Boolean DBConnect() {
String connectString = "jdbc:mysql://" + getDBServerAddress() + ":3306/"
+ "?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&&useSSL=false";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(connectString, "customerAgent", "123");
System.out.println("Connection reached.");
Statement stmt;
stmt = conn.createStatement();
String SQL = "USE movidDB";
stmt.execute(SQL);
return true;
} catch (Exception e) {
System.out.println(e.getMessage());
}
return false;
}
}
Some answers in similar questions say JDBC need all privileges on a database, but that does not sound very safe nor secure. Is it a must to have all privileges to achieve what I am trying to do here?

Your problem is that the database movidDB don't exist. Should it not be movieDB?

Related

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

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;

Java & MySql : Console adds '#'%' to db username

I'm trying to connect to a MySql database from a test-app in Java.
I have just followed a plain tutorial I found online. The code works (and compiles OK), but I cant log in to the db and fetch anything. Getting the error:
1:
Error connecting to DB: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Access denied for user '******'#'%' to database '*****_javaapp'
java.lang.NullPointerException
Why does Java add the '#', and the '%' symbols in the console? Is that why I cant log in?
I am not able to modify priveliges on the db user. It's just set to "default" I guess by the ISP provider...
I have discussed this '#' & '%' issue with my friend, and I understand that these symbols are MySql syntax for "accept anything", but I still dont know what do to fix it as my MySql knowlede is limited..
If I modify some details in the db connection I sometimes get:
2:
Error connecting to DB: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
java.lang.NullPointerException
My code
My Main class:
package test;
import java.awt.EventQueue;
public class Main {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
// DB CONNECT
DBConnect connect = new DBConnect();
connect.getData();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main window = new Main();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Main() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
My connect class:
package test;
import java.sql.*;
public class DBConnect {
private Connection con;
private Statement st;
private ResultSet rs;
public DBConnect() {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://mywebhostadress:3306/some_db_name","some_db_user", "somepassword");
st = con.createStatement();
} catch (Exception ex) {
System.out.println("Error connecting to DB: " + ex);
}
}
public void getData() {
try {
String query = "select * from Client";
rs = st.executeQuery(query);
System.out.println("Records from db: ");
while (rs.next()) {
String org_number = rs.getString("org_number");
String org_name = rs.getString("org_name");
System.out.println("org_number: " + org_number + "org_name: " + org_name);
}
} catch (Exception exgetData) {
System.out.println(exgetData);
}
}
}
Thanks for any helpfull tips!
UPDATE:
Hmmm…
In MySQL Workbench I manage to set up the connection OK… But I get the same error here:
“The account you are currently using does not have sufficient privileges to make changes to MySQL users and privileges.”
Also, while trying to forward engineer in MySQL Workbench:
ERROR 1044: Access denied for user 'some_db_user'#'%' to database 'new_schema'
SQL Statement:
CREATE SCHEMA new_schema
I have also tried to do it directly in phpMyAdmin, but there I can see this error on the front page:
“Create new database - No Privileges”
I have tried to grant my default (and only) user all the rights I can give, but it doesn’t get accepted when I do a query in phpMyAdmin.
I Guess this is why I can’t access it from my Java application. But I might type something wrong…
Shouldn’t it be:
GRANT ALL PRIVILEGES ON some_db_name.* TO 'some_db_user'#'%' WITH GRANT OPTION; ?
(taken from: this post)
I get:
Error
SQL query:
GRANT ALL PRIVILEGES ON some_db_name . * TO 'some_db_user '#'%' WITH GRANT OPTION
MySQL said:
1044 - Access denied for user 'some_db_user '#'%' to database ' some_db_name '
The error you're seeing:
Error connecting to DB:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failure
The last packet sent successfully to the server was 0 milliseconds
ago. The driver has not received any packets from the server.
java.lang.NullPointerException
is simply a connection error. Normally I'd suggest that you should try accessing your MySQL DB through the MySQL command line client or Workbench to check if it's up but here it like you haven't actually specified a host for the MySQL server (as you have a Null Pointer Error there).
You'll need to properly specify your host name in the form you provide in the OP. So to connect to a database called "some_db_name" on a local instance of MySQL as root (with the default blank password) you'd use:
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/some_db_name","root", "");
The #'%' part means the user can access from anywhere. Otherwise you can lock a user down a specific IP address or host name. It's possible to create a user role #% with lower privileges than one with the same user name but at a specific IP so then if that user logs in at that location they then get the roles of the specific IP. It has no relation to the error you're seeing here and it's what the default behaviour is for any added user unless they're specifically added with a host mask.
SOLVED! I finally found the sollution.
My hosting provider had changed the settings for the default user on their new platform. (I wasn't able to change it). I have done a lot of testing on several different platforms that the provider has to offer.
-In their new system, I wasn't able to do anything because the user didn't automatically have the right priviliges...
In their old system, I was able to accesss everything (since the user had "dba" (database admin) rights).
Thanks for all the input guys.

Java SQL query problems, ResultSet doesn't contain anything

I am trying to do SQL with Java, this is my first time. I am trying to select all of a table and put it in a ResultSet, but the ResultSet seems empty. The same query on the MySQL client does show results, which leaves me wondering what is wrong with my code. It could either be the way the query is being done, or the way I am trying to get the data from the result set.
The query in the command line MySQL client...
mysql> SELECT * FROM accounts.sites;
+----------+-----------------------+--------------------------+--------------+----------------+
| username | domain | directory | fpm-template | nginx-template |
+----------+-----------------------+--------------------------+--------------+----------------+
| cyrus | cyrustheg.org | /var/www/sites/cyrustheg | standard | drupal |
| cyrus | tornews.org | /var/www/sites/tornews | standard | standard |
| cyrus | oletf.org | /var/www/sites/oletf | standard | standard |
| taf | theabsolutefinest.org | /var/www/sites/taf | standard | wordpress |
| taf | bitsplit.org | /var/www/sites/bitsplit | bitsplit | bitsplit |
+----------+-----------------------+--------------------------+--------------+----------------+
5 rows in set (0.00 sec)
I am using this code to build a resultSet with that query...
private void read() throws Exception {
try {
Class.forName("com.mysql.jdbc.Driver");
String dburl = "jdbc:mysql://" + dbHost + "/" + dbName +
"?user=" + dbUser + "&password=" + dbPass;
connect = DriverManager.getConnection(dburl);
resultSet = statement.executeQuery("SELECT * from accounts.sites");
} catch (Exception e) {
throw e;
}
}
This code iterates through the resultSet, looking for every domain for every user. I know the problem is either in the former code or this or the former code, because I've added a print statement to the while loop, and it is never called. This is why I conclude the resultSet is empty.
public HashSet<String> listSites(String user)
throws Exception, ExcSiteNosites {
HashSet<String> list = new HashSet<String>();
boolean exists = false;
try {
read();
while (resultSet.next()) {
if (resultSet.getString("username").equals(user)) {
exists = true;
list.add(resultSet.getString("domain"));
}
}
if (!exists) {
throw new ExcSiteNosites(user);
}
} catch (Exception e) {
throw e;
} finally {
resultSet.close();
statement.close();
connect.close();
}
return list;
}
The entire class: http://pastebin.com/0DSbFey7
The unit test for that class: http://pastebin.com/9UYLEeMB
I found the bug running that unit test, which makes the following output...
Listing cyrus's sites...
Listing taf's sites...
java.lang.NullPointerException
at database.Sites.listSites(Sites.java:96)
at test.dbSites.listall(dbSites.java:28)
at test.dbSites.main(dbSites.java:51)
java.lang.NullPointerException
at database.Sites.listSites(Sites.java:96)
at test.dbSites.listall(dbSites.java:28)
at test.dbSites.main(dbSites.java:53)
The NullPointerException I think might be an unrelated problem. I've not done any Java in a while, and I've not worked that out either. Though the problem I want help with (unless related) is just that the ResultSet seems empty.
You never initialize statement in your code, it's a private variable and you have no setter on it, so I think that you are not injecting it either.
So, when you call read(), you will have a NullPointerException on
resultSet = statement.executeQuery("SELECT * from accounts.sites");
this will be catched and thrown again by your catch.
So, in your listSites(), you will catch it, and throw it again, and in the finally, you will have another NullPointerException on
statement.close();
and it's the one in your stack trace.
You need to create a statement from the connection before use it to executeQuery()....
Statement statement = connection.createStatement();

Connecting Java to MySQL using mysql-connector-java-5.1.24

I'm reading through the JDBC API Tutorial and Reference 3/E (MAN, what a dry tome), and I'm having trouble connecting my Java program to my MySQL database using the MySQL Connector supplied by Oracle.
I've placed it in my folder
C:\Windows\Sun\Java\mysql-connector-java-5.1.24
and I've pointed my Workspace CLASSPATH in JGrasp to
C:\Windows\Sun\Java\mysql-connector-java-5.1.24\mysql-connector-java-5.1.24-bin.jar
I'm trying to connect to a database called "Coffee." It definitely exists:
mysql> show databases;
+---------------------+
| Database |
+---------------------+
| information_schema |
| coffee |
| mysql |
| performance_schema |
| phpmyadmin |
+---------------------+
5 rows in set (0.03 sec)
here's my Java code. (If you have the book, I'm on page 88. The only difference between my code and theirs is some comments, and that I'm going with MySQL.)
//first, import sql package
import java.sql.*;
//name class CreateCoffees
public class CreateCoffees {
public static void main(String[] args){
String url = "jdbc:mysql://127.0.0.1:coffee";
//declare variables
Connection conn;
String createString = "create table COFFEES " +
"(COF_NAME varchar(32), " +
"SUP_ID int, " +
"PRICE float, " +
"SALES int, " +
"TOTAL int)";
Statement stmt;
//instructions
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(java.lang.ClassNotFoundException cnfe){
System.out.println("Class Not Found - " + cnfe.getMessage());
}
try{
conn = DriverManager.getConnection(url, "root", "");
stmt = conn.createStatement();
stmt.executeUpdate(createString);
stmt.close();
conn.close();
}
catch(SQLException sqle){
System.out.println("SQL Exception: " + sqle.getMessage());
}
}
}
Everything compiles just fine, but when I run it, I throw the following SQLException:
SQL Exception: Cannot load connection class because of underlying exception: 'java.lang.NumberFormatException: For input string: "coffee"'.
What exactly am I doing wrong? Is there something I can run to otherwise test connectivity between Java and the database? I'm fairly new to both.
Also, it should be noted that this is not homework.
EDIT: It would seem the offending line of code is
String url = "jdbc:mysql://127.0.0.1:coffee";
and should be changed to
String url = "jdbc:mysql://127.0.0.1/coffee";
because coffee is a database and not a port.
I guess I need more of it. Thanks to everyone who helped.
Your connection URL is using coffee as the port. You should use something like:
jdbc:mysql://127.0.0.1:3306/coffee
Why do you have "coffee" as your port number? You're supposed to have your mysql server port number there
jdbc:mysql://127.0.0.1:coffee
Hint: default port number is 3306. So try
jdbc:mysql://127.0.0.1:3306/coffee
(Assuming your database name is coffee)
I think the parser is getting confused and thinking that coffee is a port number.
Try this:
jdbc:mysql://127.0.0.1/coffee

How to connect to local host using JDBC?

I installed MySql on my own machine. I created database, create table, ... using MySql CommandLine Client. When working on a project in school, I connected to school's database using this syntax:
public static Statement connect() {
try {
Class.forName( "com.mysql.jdbc.Driver" ).newInstance();
conn = DriverManager.getConnection( "1", "2", "3" );
stmt = conn.createStatement();
}
catch( Exception e ) {
System.out.println( "Connection Error: " + e );
}
return stmt;
}
In my local machine, I don't have to type in user name, all I did is just login with my password as root user:
Enter password: ****
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.1.53-community MySQL Community Server (GPL)
Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL v2 license
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> use chandb;
Database changed
mysql> show tables;
+------------------+
| Tables_in_chandb |
+------------------+
| another |
| cars |
| employees |
+------------------+
3 rows in set (0.03 sec)
mysql> select * from Another;
+----+-----------+----------+
| Id | GoldValue | Model |
+----+-----------+----------+
| 0 | 100 | Civic DX |
+----+-----------+----------+
1 row in set (0.00 sec)
mysql>
I would like to know how can I connect to my local machine's database? what should I put as parameters within method .getConnection
conn = DriverManager.getConnection(
"1", // ?
"2", // ?
"3" ); // ?
Best regards,
Chan
Simple Connection:
import java.sql.Connection;
import java.sql.DriverManager;
public class Main {
public static void main(String[] argv) throws Exception {
String driverName = "org.gjt.mm.mysql.Driver";
Class.forName(driverName);
String serverName = "localhost";
String mydatabase = "mydatabase";
String url = "jdbc:mysql://" + serverName + "/" + mydatabase;
String username = "username";
String password = "password";
Connection connection = DriverManager.getConnection(url, username, password);
}
}
It looks like you left your username and password in the source you posted.
I don't see why you can't just do
DriverManager.getConnection("jdbc:mysql://localhost/chandb", "user, "pass");

Categories

Resources