I installed MySQL database & JDBC. I created a database called feedback through MySQL command line client, and I want to access that database through a java program.
Here is the commands I used on MySQL command line client create the database.
create database feedback;
use feedback;
CREATE USER sqluser IDENTIFIED BY 'sqluserpw';
grant usage on *.* to sqluser#localhost identified by 'sqluserpw';
grant all privileges on feedback.* to sqluser#localhost;
CREATE TABLE COMMENTS (id INT NOT NULL AUTO_INCREMENT,
MYUSER VARCHAR(30) NOT NULL);
INSERT INTO COMMENTS values (default, 'lars');
Then, the code in Java:
package de.vogella.mysql.first;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import javax.swing.JOptionPane;
public class MYSQLACCESS {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public void readDataBase() throws Exception {
JOptionPane.showMessageDialog(null, "Before try" );
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
JOptionPane.showMessageDialog(null, "1" );
connect = DriverManager.getConnection("jdbc:mysql://localhost/feedback?"
+ "user=sqluser&password=sqluserpw");
// Statements allow to issue SQL queries to the database
statement = connect.createStatement();
// Result set get the result of the SQL query
resultSet = statement.executeQuery("select * from FEEDBACK.COMMENTS");
// writeResultSet(resultSet);
String my_user = resultSet.getString("MYUSER");
System.out.println(my_user);
JOptionPane.showMessageDialog(null, my_user );
} catch (Exception e) {
throw e;
}
}
}
The Main Class:
package de.vogella.mysql.first;
import de.vogella.mysql.first.MYSQLACCESS;
public class Main {
public static void main(String[] args) throws Exception {
MYSQLACCESS first_access = new MYSQLACCESS();
first_access.readDataBase();
}
}
However, I get the following exception:
Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
Access denied for user 'sqluser'#'localhost' to database 'feedback'
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:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4237)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4169)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:928)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1750)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1290)
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(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:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:416)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:347)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at de.vogella.mysql.first.MYSQLACCESS.readDataBase(MYSQLACCESS.java:30)
at de.vogella.mysql.first.Main.main(Main.java:7)
I am following the tutorial in the following link
Any help?
The user sqluser does not have the privileges to access database feedback on the localhost.
Use the mysql command line tool and grant the privileges to the user.
Do not forget to flush privileges
usually when having this exception:
Access denied for user 'sqluser'#'localhost' to database 'feedback'
means that this user don't have enough privileges to access the Database, what I would suggest you to do is to go to your SQL shell and write this command:
show grants;
it would show you which users has access to the Database and with their level of privilege
if this user don't seem to have the necessary privilege to access the DB you can grant it to him by writing this query in your SQL Shell
GRANT ALL PRIVILEGES ON *.* TO 'sqluser'#'localhost' WITH GRANT OPTION;
Good Luck;
Related
This question already has an answer here:
java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)
(1 answer)
Closed 7 years ago.
I am using the fllowing code and get this error:
Access denied for user 'root'#'localhost' (using password: YES)
java.lang.NullPointerException
I used several solutions from the stackoverflow. But the problem is not resolved! Please provide your solution.
Inserts only once, but then I came across the above error.
My Java code:
package DBConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import com.mysql.jdbc.PreparedStatement;
public class Main {
public static void main(String[] args) throws Exception {
insert();
}
public static void insert() throws Exception{
final String var1 = "test1";
final String var2 = "تست2";
final String var3 = "test.com";
try{
Connection conn = getConnection();
PreparedStatement inserted = (PreparedStatement) conn.prepareStatement("INSERT INTO wpsjim_target_sites (site_name_en,site_name_fa,site_address) VALUES('"+var1+"','"+var2+"','"+var3+"')");
inserted.execute();
}catch(Exception e){
System.out.println(e);
}finally{
System.out.println("Insert Completed!");
}
}
public static Connection getConnection() throws Exception{
try{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/simjin";
String username = "root";
String password = "rootpass";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println("Connected");
return conn;
} catch(Exception e){
System.out.println(e.getMessage());
}
return null;
}
}
Update:
When i use e.printStackTrace(System.out); display the fllowing messages on console:
java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3878)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:871)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1694)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1215)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2255)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2286)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2085)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:795)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:44)
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.ConnectionImpl.getInstance(ConnectionImpl.java:400)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:327)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at DBConnection.Main.getConnection(Main.java:34)
at DBConnection.Main.insert(Main.java:17)
at DBConnection.Main.main(Main.java:9)
java.lang.NullPointerException
i think there is nothing in your code that will cause this type error, as you can see in error
Access denied for user 'root'#'localhost' (using password: YES)
it shows that problem is with your user or password, so check once again that your user and password is correct if you are using password for database user.
Incorrect username or password causes the problem.
Normally the default password is null. If you are using a root password it means you should have put like this:
String username = "root";
String password = "";//without space
I do not want to install a database server on target machine. It is possible that we can simply ship a jar file with the database embedded in it, and not worry about installing a database server separately?
I created one application in netbeans using derby and it is working fine in my pc but when i am running on other machine it is giving me an Exception
My code is
System.setProperty("derby.drda.startNetworkServer", "true");
try {
NetworkServerControl serverControl = new NetworkServerControl();
serverControl.start(new PrintWriter(System.out, true));
} catch (Exception e) {
e.printStackTrace();
}
For connection i wrote this code
public static Connection getderbyConnection() throws ClassNotFoundException, SQLException
{
String url = "jdbc:derby://localhost:1527/XLS_Uniquewordlist;create=true";
String user = "root";
String password = "mantra";
Class.forName("org.apache.derby.jdbc.ClientDriver");
return (Connection) DriverManager.getConnection(url, user, password);
}
I am getting this exception
Exception in thread "DRDAConnThread_2" java.lang.NoSuchMethodError:
org.apache.derby.iapi.jdbc.EnginePreparedStatement.getVersionCounter()J
at org.apache.derby.impl.drda.DRDAStatement.prepare(Unknown Source)
at org.apache.derby.impl.drda.DRDAStatement.explicitPrepare(Unknown
Source)
at org.apache.derby.impl.drda.DRDAConnThread.parsePRPSQLSTT(Unknown
Source)
at org.apache.derby.impl.drda.DRDAConnThread.processCommands(Unknown
Source)
at org.apache.derby.impl.drda.DRDAConnThread.run(Unknown Source)
May 12, 2015 5:17:59 PM xls_parser.Main_panel btnokActionPerformed
SEVERE: null
java.sql.SQLSyntaxErrorException: DERBY SQL error: SQLCODE: -20001, SQLSTATE: 42X05, SQLERRMC: APP.UNIQUEWORDLIST42X05
at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown
Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown
Source)
at org.apache.derby.client.am.Connection.prepareStatement(Unknown Source)
I'm trying to connect to HSQL using java. I'm using a tutorial to work with JDBC and hibernate. It's the lynda tutorials. Anyway, here's the code below:
package com.lynda.javatraining.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
private static final String USERNAME = "dbuser";
private static final String PASSWORD = "dbpassword";
private static final String CONN_STRING =
"jdbc:hsqldb://data/explorecalifornia";
public static void main(String[] args) throws SQLException {
//Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
System.out.println("A");
System.out.println(conn == null);
System.out.println(CONN_STRING);
try {
System.out.println("B1");
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("B1-2");
System.out.println("Connected!");
} catch (SQLException e) {
System.out.println("B2");
System.err.println(e);
} finally {
System.out.println("B3");
if (conn != null) {
conn.close();
}
}
System.out.println("C");
}
}
Here's the error I'm getting:
A
true
jdbc:hsqldb://data/explorecalifornia
B1
2014-06-27T15:26:27.430-0400 SEVERE could not reopen database
org.hsqldb.HsqlException: Database lock acquisition failure: lockFile: org.hsqldb.persist.LockFile#76d682a[file =/data/explorecalifornia.lck, exists=false, locked=false, valid=false, ] method: openRAF reason: java.io.FileNotFoundException: /data/explorecalifornia.lck (No such file or directory)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.persist.LockFile.newLockFileLock(Unknown Source)
at org.hsqldb.persist.Logger.acquireLock(Unknown Source)
at org.hsqldb.persist.Logger.openPersistence(Unknown Source)
at org.hsqldb.Database.reopen(Unknown Source)
at org.hsqldb.Database.open(Unknown Source)
at org.hsqldb.DatabaseManager.getDatabase(Unknown Source)
at org.hsqldb.DatabaseManager.newSession(Unknown Source)
at org.hsqldb.jdbc.JDBCConnection.<init>(Unknown Source)
at org.hsqldb.jdbc.JDBCDriver.getConnection(Unknown Source)
at org.hsqldb.jdbc.JDBCDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at com.lynda.javatraining.db.Main.main(Main.java:24)
B2
java.sql.SQLException: Database lock acquisition failure: lockFile: org.hsqldb.persist.LockFile#76d682a[file =/data/explorecalifornia.lck, exists=false, locked=false, valid=false, ] method: openRAF reason: java.io.FileNotFoundException: /data/explorecalifornia.lck (No such file or directory)
B3
C
Can anyone tell e what I"m doing wrong? Thanks.
A database has a lock file explorecalifornia.lck that prevents communication. You should delete lock file and restart the database. This may happens from time to time when you accidentally shutdown the database or system.
See the syntax of the command used from the command line to invoke shutdown. There's also an option how to shutdown server in Java.
I've been looking over StackOverflow for the last two days for similar problems and have found many people with the same issue, however, nothing suggested has worked for me so I figured I would post my exact question here in case I'm missing something obvious. I've noticed the connection refused causation, however, I know exactly what my username and password is as well as the dbname, so I know it's not an authentication problem.
After much frustration, I have found a class that simply checks the version of MySQL running on my machine. I am running MySQL using XAMPP as well. However, no matter what I try to do, I get the following error:
Apr 26, 2014 7:29:37 PM Version main
SEVERE: 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.
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.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1127)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:356)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2502)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2539)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2321)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:832)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:409)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:417)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:344)
at java.sql.DriverManager.getConnection(DriverManager.java:579)
at java.sql.DriverManager.getConnection(DriverManager.java:221)
at Version.main(Version.java:23)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:241)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:258)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:306)
... 15 more
And here is my Version class:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Version {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/dbname";
String user = "username";
String password = "password";
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT VERSION()");
if (rs.next()) {
System.out.println(rs.getString(1));
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
}
I was able to get this working.
I had to reinstall XAMPP and recreate the Database from scratch from the Exported SQL.
You have no idea how annoyed I was to do this. Lots of wasted time. Thanks for the help.
On ubuntu i work with MySQL and tried to edit a file with terminal
sudo nano /etc/mysql/my.cnf
find the line that contains:
bind-address
just edit this line
bind-address = 0.0.0.0
save the file and restart mysql with
sudo service mysql restart and try again
it worked for me, good luck!
You missed some code pal! try adding Class.forName(com.mysql.jdbc.Driver); in your try catch block. hope it helps
I'm trying to make a java desktop database application, using the derby embedded database, I'm having some issues that I can't quite fix, and I've searched (a lot) for the answers, found some, but they couldn't solve my problem, so I decided to make a question myself. I made the database on netbeans, jut like a whole bunch of tutorials teach, downloaded the derby.jar and added to the library on the project, but then when I try to insert some data in the database's table that I created is says that the table doesn't exist.
I'm pretty sure i'm missing something really stupid, but I can't figure it out by myself, so any help will be very much appreciate. I'm new to all this java database development, I had only created local databases on c#
PS: The schema is the 'APP' one, I tried using "INSERT INTO APP.PACIENTE (ID, NOME) VALUES (1, 'victor')" but that didn't work either
public class BancoDados {
private static String url = "jdbc:derby:MeuBancoDados;create=true";
private static String driver = "org.apache.derby.jdbc.EmbeddedDriver";
static Connection conn;
static Statement sta;
public static void insert() throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
conn = null;
sta = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url);
sta = conn.createStatement();
sta.executeUpdate("INSERT INTO PACIENTE (ID, NOME) VALUES (1, 'victor')");
sta.close();
conn.close();
System.out.println("Inserido com sucesso!");
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
}
}
}
I get This error:
Exception in thread "main" ERROR 42X05: Table 'PACIENTE' does not exist.
at org.apache.derby.iapi.error.StandardException.newException(Unknown Source)
at org.apache.derby.impl.sql.compile.DMLModStatementNode.verifyTargetTable(Unknown Source)
at org.apache.derby.impl.sql.compile.InsertNode.bind(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepMinion(Unknown Source)
at org.apache.derby.impl.sql.GenericStatement.prepare(Unknown Source)
at org.apache.derby.impl.sql.conn.GenericLanguageConnectionContext.prepareInternalStatement(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedStatement.execute(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedStatement.executeUpdate(Unknown Source)
at projcad.BancoDados.insert(BancoDados.java:31)
at projcad.projcad.main(projcad.java:8)
Java Result: 1
Table 'PACIENTE' does not exist.
This is because in database you have not created the PACIENTE table.
Create it.