I am trying to fetch records from database. but I am facing this access denied issue. I tried the other solutions mentioned on Stack Overflow like granting privilege to the user.. but none worked.
Code for accessing database :
public void service(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Servlet JDBC</title></head>");
out.println("<body>");
out.println("<h1>Servlet JDBC</h1>");
out.println("</body></html>");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employees","root","root");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM employee");
// displaying records
while(rs.next()){
out.print(rs.getObject(1).toString());
out.print("\t\t\t");
out.print(rs.getObject(2).toString());
out.print("<br>");
}
} catch (SQLException e) {
throw new ServletException("Servlet Could not display records.", e);
} catch (ClassNotFoundException e) {
throw new ServletException("JDBC Driver not found.", e);
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(con != null) {
con.close();
con = null;
}
} catch (SQLException e) {}
}
out.close();
}
Stack trace of the error :
java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4187)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4119)
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:927)
com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:4686)
com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1304)
com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2483)
com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2516)
com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2301)
com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:834)
com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
java.lang.reflect.Constructor.newInstance(Unknown Source)
com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:416)
com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:346)
java.sql.DriverManager.getConnection(Unknown Source)
java.sql.DriverManager.getConnection(Unknown Source)
WebAppAss.DatabaseAccess.service(DatabaseAccess.java:36)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
What could be the problem in this case. I tried creating a new database but that didn't work too.
Start mysql client in the console and execute this query: select Host, User from mysql.user;. You MUST have a row like this:
+----------------+------------------+
| Host | User |
+----------------+------------------+
| localhost | root |
+----------------+------------------+
a row with "localhost" in Host and "root" in User. If you don't have it that's the cause of your problem (it doesn't matter if you have other rows with "root" in User)
If you don't have such row, add a new user with this:
CREATE USER 'appUser'#'localhost' IDENTIFIED BY 'appPassword';
Change 'appUser' by 'root' if you want, but I strongly suggest to use another user. Then add permissions to your new user by executing this in the mysql client:
GRANT ALL PRIVILEGES ON employees.* TO 'appUser'#'localhost';
(again, change 'appUser' by 'root' if you want)
The problem was the permissions granted to root in the information.schema table. 'root'#'%' didnt have any permissions.. And as I was using 127.0.0.1 as my connection address, so it was giving the access denied error.. % is the wildcard for an ip address. so mysql considers root#127.0.0.1 as any other ip address but not localhost. so just granting it permission solved my problem.. Try using some Mysql client like SQLYog etc.. it is easy to grant the privileges and also to view the privileges with the user.
Try it:
mysql --no-defaults --force --user=root --host=localhost --database=mysql
Change a new password:
UPDATE user SET Password=PASSWORD('NEWPASSWORD') where USER='root';
FLUSH PRIVILEGES;
Related
Project details:
| mysql-connector-java version : 8.0.27 |
| JDK version : 15.0.1 |
I am unable to make a connection to the MySQL database hosted on docker using Java. I have attached my code below for reference.
Note : I am able to make a connection to the database using python instead of java while making no changes to the connection details whatsoever. This problem only persists with java.
`
import java.sql.*;
public class TestJDBCMySQL
{ public static void main(String[] args)
{ String url = "jdbc:mysql://localhost/workson";
String uid = "retracted";
String pw = "retracted";
try ( Connection con = DriverManager.getConnection(url, uid, pw);
Statement stmt = con.createStatement();)
{
ResultSet rst = stmt.executeQuery("SELECT ename,salary FROM emp");
System.out.println("Employee Name,Salary");
while (rst.next())
{ System.out.println(rst.getString("ename")+","+rst.getDouble("salary"));
}
}
catch (SQLException ex)
{
System.err.println("SQLException: " + ex);
}
}
}
`
What I've done so far :
Creating a new user and granting all privileges using MySQL workbench
Verifying credentials. I was able to connect to the database using the docker cli with the exact same credentials.
Ensuring the database exists ( it does )
Add the mysql-connector-java to the reference library in VsCode
Specifying the port in the connection URL
This question already has an answer here:
Exception in thread "main" java.sql.SQLException: Access denied for user ''#'localhost' (using password: NO)
(1 answer)
Closed 2 years ago.
I'm making a java project with SceneBuilder and Eclipse; i need to connect to a local database created using MySQL, but after running my Java code in eclipse i get the following error:
Exception in thread "main" java.sql.SQLException: Access denied for user ''#'localhost' (using password: NO)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:836)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:246)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:197)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.mysql.cj.jdbc.admin.TimezoneDump.main(TimezoneDump.java:70)
Instead of 'root'#'localhost' (using password: NO) that is a login credentials error, now i have ''#'localhost' (using password: NO).
Using MySQL workbench and command prompt, i can correctly access using "root"/"root", and launch queries on my db. Running the same Eclipseproject on another laptop or my home pc, i can run it without errors. So the problem is not in the code but in some setting of my current laptop.
I already tried to:
Uninstall and reinstall Eclipse.
Uninstall and reinstall mySQL products: Workbench, Server, J Connector.
Switch Eclipse workspace.
Open the 3306 port from windows firewall.
That's the part of the code where i try to connect to my db.
package model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class UserDAO {
private static String USER = "root";
private static String PASS = "root";
private static String DB_URL = "jdbc:mysql://127.0.0.1:3306/beecological?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
private static String DRIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver";
public static boolean checkUsername(String username) {
Statement stmt = null;
Connection conn = null;
int res = 1;
try {
Class.forName(DRIVER_CLASS_NAME);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
res = Queries.verifyUsernameAvailable(stmt, username);
stmt.close();
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
if(res == 1) {
return false;
}
return true;
}
public static void saveUser(User instance) {
Statement stmt = null;
Connection conn = null;
try {
Class.forName(DRIVER_CLASS_NAME);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
Queries.insertUser(stmt, instance);
stmt.close();
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
}
public static boolean verifyLogin(User instance) {
Statement stmt = null;
Connection conn = null;
int res = 0;
try {
//caricamento driver mysql
Class.forName(DRIVER_CLASS_NAME);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
res = Queries.verifyUserRegistered(stmt, instance);
stmt.close();
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
if (res == 0) {
return false; //utente immesso non esiste
}
return true;
}
}
Solution
The problem was not about MySQL login credentials, but on Eclipse configuration.
In my folder project the .classpath and the .project files were corrupted. Infact going to myproject>right click>Run As..>Run Configurations the main class was setted as com.mysql.cj.jdbc.admin.TimezoneDump.main instead of my mainApp class. Trying to change there the main class file not worked, because for Eclipse the mainApp doesn't exist.
So this is what i've done to solve the error:
Delete the project from Eclipse (not on the disk)
Close Eclipse
Go to Project folder and delete .classpath and .project files
Open eclipse, go to File > Open projects from File System and choose the project directory
Right click on the project > Run As > Run Configurations and set the right Main class
I am getting the following exception :-
java.sql.SQLException: [DataDirect][OpenEdge JDBC Driver][OpenEdge] Access denied(Authorisation failed)
at com.ddtek.jdbc.openedge.client.ddd.aw(Unknown Source)
at com.ddtek.jdbc.openedge.client.ddd.j(Unknown Source)
at com.ddtek.jdbc.openedge.OpenEdgeImplConnection.j(Unknown Source)
at com.ddtek.jdbc.openedgebase.BaseConnection.b(Unknown Source)
at com.ddtek.jdbc.openedgebase.BaseConnection.k(Unknown Source)
at com.ddtek.jdbc.openedgebase.BaseConnection.b(Unknown Source)
at com.ddtek.jdbc.openedgebase.BaseConnection.a(Unknown Source)
at com.ddtek.jdbc.openedgebase.BaseDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at com.ncr.sj250216.JdbcTest.main(JdbcTest.java:18)
There is no compile time error in my code, i am using the right jars as referenced libraries.
package com.ncr.sj250216;
import java.sql.*;
public class JdbcTest
{
public static String
URL="jdbc:datadirect:openedge://sun3899.daytonoh.ncr.com:28409;DatabaseName=dispatch";
public static String username="CSMSRUP";
public static String password=null;
public static void main(String [] args)
{
try
{
Class.forName ("com.ddtek.jdbc.openedge.OpenEdgeDriver");
System.out.println("Driver loaded");
Connection conn = DriverManager.getConnection(URL,username,password);
System.out.println("Connected");
Statement stmt = conn.createStatement();
System.out.println("Statement created");
ResultSet rs = stmt.executeQuery("select remark from pub.dupdate_remarks");
System.out.println("ResultSet : \n");
while (rs.next())
{
System.out.println(rs.getString(1));
}
System.out.println("AFTER CRUISING THROUGH THE RESULT SET");
rs.close();
stmt.close();
conn.close();
}
catch (Exception x)
{
x.printStackTrace();
}
}
}
Access denied and Authorization failed mean that you either have the wrong userid & password or you are attempting to connect to the wrong db.
If you have access to the server that the db runs on you can test your credentials using Progress' sqlexp command line tool:
sqlexp -user userName -password passWord -db dnName -S servicePort
Or you could use any popular Windows based SQL querying tool to try the connection...
I am working on a GWT project in which I need to make some MySQL queries. I have handled RPC properly and in the server-side I am trying to make a mysql connection but am running into an exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.
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.google.appengine.tools.development.agent.runtime.Runtime.newInstance_(Runtime.java:112)
at com.google.appengine.tools.development.agent.runtime.Runtime.newInstance(Runtime.java:120)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1013)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2412)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2154)
at com.mysql.jdbc.ConnectionImpl.(ConnectionImpl.java:792)
at com.mysql.jdbc.JDBC4Connection.(JDBC4Connection.java:47)
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.google.appengine.tools.development.agent.runtime.Runtime.newInstance_(Runtime.java:112)
at com.google.appengine.tools.development.agent.runtime.Runtime.newInstance(Runtime.java:120)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:381)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
.
.
.
more
.
.
.
I created a very simple java class to test out my code to confirm that my connection syntax and use is proper, and have confirmed that syntax is not a problem because with the very same code in a simple only main method java app I can create a connection and query the database properly. I have made sure to have mysql-connector-java-5.1.16-bin.jar in the classpath as well as the /lib folder in the WEB-INF folder.
Here is the class that I am using in order to create a connection:
public class DB_Connection {
protected Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql:///",
"",
"");
}
catch (Exception ex)
{
ex.printStackTrace();
}
return conn;
}
}
public class Login extends DB_Connection {
public User getUser(String email) {
User user = new User();
user.setUserEmail(email);
String query = "";
try {
Connection conn = getConnection();
Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery(query);
while(result.next()) {
user.setUserId(result.getInt("rvuser_id"));
System.out.println(user.getUserId());
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
return user;
}
It seems my problem happens all the way at the beginning in DB_Connection. Does anyone know what is making this happen? It is strange to me, because as a standalone the code works fine.
Another thing I just realized that I am at home now and don't even have access to that database server as it is on a local network and I am not connected through VPN. So it must be failing somehow before it even attempts to make the connection.
Thanks!
com.google.appengine ..
Does it means you are deploying on Google App Engine?
If so, MySQL,JDBC and many other things are restricted.
This is the connection string that is currently working on a non-password protected MS Access database.
this code snippet is from our properity file:
db.url = jdbc:odbc:Driver\={Microsoft Access Driver (*.mdb)};Dbq\=C:\Inventory.mdb;DriverID\=22;READONLY\=true
How do I add a password to this connection string for a MS Access DB protected by a database password (Non-ULS)?
Thanks!
Referenced from here: Java Support
db.url = jdbc:odbc:Driver\={Microsoft Access Driver (*.mdb)}Dbq\=C:\Inventory.mdb;DriverID\=22;READONLY\=true; UID\=me;PWD\=secret
To work on password protected MS Access Database 2003/2007 use the below code snippet
package jdbcExample;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBCExampleOfMSAccess2007
{
public static void main(String[] args)
{
System.out.println("Start of Program");
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String url=null,userID=null,password=null;
String dbFileName=null;
String sql=null;
dbFileName = "C:\\temp\\MYTestDatabase.accdb";
userID = "Admin";
password = "Ganesh#123";
<b>url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};"+
"DBQ="+dbFileName+";"+
"Uid="+userID+";"+
"Pwd="+password+";"; </b>
sql = "SELECT * FROM tblUserProfile";
System.out.println("url = "+url);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(url,userID,password);
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
if(rs!=null)
{
while(rs.next())
{
System.out.print("User ID = "+rs.getString("User ID"));
System.out.print(" User Name = "+rs.getString("User Name"));
System.out.print(" Password = "+rs.getString("Password"));
System.out.println(" Access Type = "+rs.getString("Access Type"));
}
rs.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try {
stmt.close();
con.close();
} catch (SQLException e) {
//e.printStackTrace();
}
}
System.out.println("End of Program");
}
}
My connection string url was
url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};"+
"DBQ="+dbFileName+";"+
"DriverID=22;READONLY=true;"+
"Uid="+userID+";"+
"Pwd="+password+";";
and I was facing one problem while connecting to MS Access Database the stack trace as below.
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver]General error Unable to open registry key Temporary (volatile) Ace DSN for process 0x162c Thread 0x1e98 DBC 0x38f5924 Jet'.
at sun.jdbc.odbc.JdbcOdbc.createSQLException(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.standardError(Unknown Source)
at sun.jdbc.odbc.JdbcOdbc.SQLDriverConnect(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcConnection.initialize(Unknown Source)
at sun.jdbc.odbc.JdbcOdbcDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at jdbc.JDBCForMSAccess2007.main(JDBCExampleOfMSAccess2007 .java:37)
To overcome this problem simply I removed the "DriverID=22;READONLY=true;" in url string and the problem get solved :)
The given code snippet I have tested on password protected MS Access 2003 and 2007 Database and work well.
Hope that it will helpful to do new experiment.
I know you're asking for ODBC, but is it impossible to use OLEDB, as in the connect string provided on ConnectionStrings.com:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\mydatabase.mdb;Jet OLEDB:Database Password=MyDbPassword;
I don't know that the Jet ODBC driver provides any support for database passwords, which were not introduced until Jet 4 (and are completely worthless in any version of Access/Jet/ACE).