Java Database mySQL access denied - java

So I am trying to connect to my database and display an item from the table.
The error I am getting is: SQL Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Access denied for user 'Bob'#'%' to database 'TEST'
Is this connecting properly, and if so is the error that the credentials are wrong? And if they are wrong how is it connecting? Thank you
try
{
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://THISISTHEHOSTNAME";
String username = "Bob";
String password = "password";
Connection connection = DriverManager.getConnection(url, username, password);
Statement stmt = null;
ResultSet rs = null;
//SQL query command
String SQL = "SELECT * FROM TEST";
stmt = connection.createStatement();
rs = stmt.executeQuery(SQL);
while (rs.next())
{
System.out.println(rs.getString("ProductName") + " : " + rs.getString("UnitPrice"));
}
}
catch (SQLException e)
{
System.out.println("SQL Exception: "+ e.toString());
}
catch (ClassNotFoundException cE)
{
System.out.println("Class Not Found Exception: "+ cE.toString());
}

You need to grant the proper privileges to the user that is connecting to the mysql db.
The message you are getting is informing you that while your user was able to connect to the database server, it was not allowed to access the database TEST.
Running the following command in the mysql console would grant such access:
GRANT ALL ON TEST.* TO 'BOB'#'%'
This is extremely permissive and you should keep in mind that db users should have the minimal amount of privileges possible and be restricted to the smallest range of hosts.

I used ShowIP Firefox add on and used the IP instead and didn't get any errors but I'm wondering if should return access granted and I'm unable to find an answer at the moment.

Here's a few things to do:
Check to see if your username and password are correct.
Did you add the username to the correct database? (This needs to be done in CPanel SQL)
Did you allow your database to get connection access from your IP address? (This also needs to be done in CPanel SQL)

create a new user in mysql check all global privileges > go to service in netbeans > database > mysql server at localhost > right click connect and fill username password
this work for me

Please try the code below:
import java.sql.*;
public class InsertPrepared {
public static void main(String[] args)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306//test","sanjib","");
PreparedStatement stmt=con.prepareStatement("insert into employee values(???)");
stmt.setInt(1,101);
stmt.setString(2,"Sampa");
int i=stmt.executeUpdate();
System.out.println(i+"Records is inserted");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Related

Java connection to a SQL Server Login failed for user

I want to connect to sql server 2017
I try without error to connect to sql server using sql server management studio
and I execute some query like :
SELECT fullname
FROM [AssetInst.Integ].[dbo].[Employee]
my problem now is to connect using java hibernate.
I use sqljdbc4.jar and jdk 1.6
first I try with this java class to test connexion:
public static void main(String[] args)
{
try
{
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
Connection con = DriverManager.getConnection("jdbc:sqlserver://192.168.0.12\\MSSQLSERVER2017:1433;databaseName=AssetInst.Integ","Test_user","P#ssw0rd123#");
String query =" select * FROM [AssetInst.Integ].[dbo].[Employee]";
Statement statement = con.createStatement();
ResultSet resultSet = statement.executeQuery(query);
while(resultSet.next())
{
System.out.print("fullname: " + resultSet.getString("fullname"));
}
}catch(Exception ex)
{
ex.printStackTrace();
}
}
but I have this error :
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'Test_user'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:197)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:246)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:83)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:2529)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:1905)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:41)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:1893)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:4575)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1400)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1045)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:817)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:700)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:842)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:215)
at com.dq.hibernate.generator.Snippet.main(Snippet.java:27)
this is work for me
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
connectionMsSQl = DriverManager.getConnection(jdbc:sqlserver:/192.168.0.12;instanceName=AssetInst.Integ, "Test_user", "P#ssw0rd123#");
check name and password. try this one hope its works for you

How to connect a Java application to db4free.net using JDBC?

I'm doing a college project where we have to build a fully functioning Java application, complete with a basic user login system using JDBC.
The basic user login system works fine when used on XAMPP's MariaDB MySQL branch via localhost.
Obviously, the system wouldn't work outside of this particular network, so I looked around for ways to allow me to host a MySQL database online at all times so regardless of where I go, this basic user login system works and can be shown to anyone who's interested.
I then found db4free.net, and so far everything looks in order - PHPMyAdmin works, and I managed to successfully export and import the database with the usernames and passwords from the localhost version to db4free's version.
But I'm having trouble on how to actually point my application to connect to db4free's systems so the login system works as intended.
Here's the "connection module" Java class that handles the connection:
package com.fixer.dal;
import java.sql.*;
public class Connection_Module {
public static Connection connector(){
java.sql.Connection cnx = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://db4free.net:3306/db_fixer";
String user = "myuser";
String password = "mypassword";
try {
Class.forName(driver);
cnx = DriverManager.getConnection(url, user, password);
return cnx;
} catch (Exception e) {
return null;
}
}
}
And here's the function that checks with the database to see if the username and password match with the recorded data (and if it does, it closes the login screen and opens the "main" screen):
Connection cnx = null;
PreparedStatement pst = null;
ResultSet rs = null;
public void login(){
String sql = "select * from usertable where username=? and password=?";
try {
pst = cnx.prepareStatement(sql);
pst.setString(1, Screen_Login_Username_Field.getText());
pst.setString(2, Screen_Login_Password_Field.getText());
rs = pst.executeQuery();
if(rs.next()){
Screen_Main Main = new Screen_Main();
Main.setVisible(true);
this.dispose();
cnx.close();
}else{
JOptionPane.showMessageDialog(null, "Invalid user or password.");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
And that's mostly my problem. db4free.net gave me a host ("db4free.net") and a port ("3306"), but I don't know exactly where do they go. I've tried some methods to get it to work based off other questions here but none successfully connected me to my database on their systems.
What am I doing wrong?
I just created a database (for the first time) in db4free.com and I used:
MySQL 8.x JDBC driver (I used the JDBC driver 8.0.11).
The URL is:
jdbc:mysql://db4free.net:3306/database-name
In MySQL 8.x, however, it's better to add the following parameters to avoid dealing with tons of warnings:
jdbc:mysql://db4free.net:3306/database-name?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false
It worked like a charm at once. Did you confirm the email they sent? Is your account active? Are you using the JDBC driver 8.x?

Create connection to SQL database using JDBC Driver- SQLException [duplicate]

I am trying to connect to my database by JDBC on localhost. Connecting via windows authentication is no problem, but I want to connect via SQL authentication. Therefore, I created a login and a user corresponding to this login in my database. I can normally log in SSMS:
My connection string for JDBC:
jdbc:sqlserver://localhost:1433;databaseName=TestBazyDanych;user=doszke;password=doszke123
Thrown exception:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'doszke'. ClientConnectionId:b7005fe3-904d-40c5-a89e-af0cb61250d6
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:254)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:258)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:104)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:4772)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:3581)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:81)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:3541)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7240)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2869)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:2395)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2042)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1889)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1120)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:700)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:251)
at main.Main.main(Main.java:38)
The username and password are the same, as those used for loging to SSMS.
Here my class code:
package main;
import java.sql.*;
public class Main {
private static ResultSet selectStan(Connection connection) throws SQLException {
String sql_stmt = "SELECT * FROM STAN;";
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(sql_stmt);
System.out.println("Select executed");
return result;
}
public static void main(String[] args) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String userName = "doszke";
String password = "doszke123";
String url = "jdbc:sqlserver://localhost:1433;databaseName=TestBazyDanych;user=doszke;password=doszke123";
try (Connection con = DriverManager.getConnection(url)) {
if(con != null){
System.out.println("connected");
} else {
System.out.println("unable to connect");
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
As Mark Rotteveel pointed out, I was trying to connect to a LocalDB instance with JDBC, which seemed undoable. (ref: here)
However, I installed jTDS and added to my classpath, changed my connection string to
jdbc:jtds:sqlserver://./TestBazyDanych;instance=LOCALDB#EB7165FD;namedPipe=true
create a connection by the use of this connection string, username and password and it worked. The instance pipe number was taken from cmd line via
sqllocaldb i MSSQLLocalDB
There are few things need to check:
Did you create doszke user under the database and SSMS?
Are you able to login with doszke/doszke123 credentials in SSMS?
Please check 1433 port are open or not in your inbound and outbound firewall.
Trying to telnet on localhost 1433. If it's getting failed change below setting:
Go to Configuration tools -> SQL Server Configuration Manager Select SQL Server Network Configuration -> Select protocol in the right side window enable tcp/ip and restart the services in services.

How can the java SQL connector be used to connect to a database on a different computer

I have a simple database on my computer for testing purposed, and I'm trying to retrieve some information from the database, from my laptop. So I want my laptop to make a request to see the information inside my computers MySQL database. Below shows the java code I'm trying to run on my laptop to collect the first entry in the students table, which is located on my computer.
I have MySQL workbench installed on both my laptop and computer, is it necessary to be on both machines if the computer will store the data and the laptop only extracts data.
What I've learnt so far from researching is that the public ip should be used in the url instead of the ip for the computer, so I added that in but I received a CommunicationsException along with "Connection timed out" in the stack trace. I've read through this answer and this answer to a similar problem, but I'm having difficulty understanding both solutions, could someone refer me to a beginners guide to remotely accessing data from a database using MySQL.
public class TestRemote{
//JDBC variables
Connection connection;
Statement statement;
ResultSet resultSet;
//String variables
String url;
String user;
String password;
public static void main(String[] args) {
TestRemote sql = new TestRemote();
ArrayList<String> firstnames = sql.getColumn("students", "firstname", "studentid=4");
System.out.println(firstnames.get(0));
}
// Constructor
public TestRemote()
{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("couldnt find class");
}
url = "jdbc:mysql://81.159.3.167:3306/test"; //?autoReconnect=true&useSSL=false";
user = "user";
password = "pass123";
connection = null;
statement = null;
resultSet = null;
}
private void closeConnection(){
try{
if(connection != null)
connection.close();
if(statement != null)
statement.close();
if(resultSet != null)
resultSet.close();
connection=null; resultSet=null; statement=null;
}catch(Exception e){
e.printStackTrace();
}
}
public ArrayList<String> getColumn(String table, String column, String where) {
ArrayList<String> resultsArray = new ArrayList<String>();
try {
connection = DriverManager.getConnection(url, user, password);
statement = connection.createStatement();
if(!where.equals(""))
resultSet = statement.executeQuery("SELECT "+column+" FROM "+table + " WHERE "+where);
else
resultSet = statement.executeQuery("SELECT "+column+" FROM "+table);
while(resultSet.next()) {
String val = resultSet.getString(1);
if(val==null)
resultsArray.add("");
else
resultsArray.add(val);
}
//resultsArray = (ArrayList<String>) resultSet.getArray(column);
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Model.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
}
closeConnection();
return resultsArray;
}
}
Your Java code is probably fine. But the question is, is on the other machine a MySQL server running and listening on port 3306 on the public IP? By default it should only listen on localhost, so you need to change your MySQL installation so that it listens to the public IP. Also make sure that no Firewall is blocking the access. Try connecting with the Workbench on the Laptop to reach the MySQL server on the other box. If you got this running, try your Java code again.
I have MySQL workbench installed on both my laptop and computer, is it
necessary to be on both machines if the computer will store the data
and the laptop only extracts data.
No what you call the "Computer" is your server here. it doesn't need mysql workbench. it only needs mysql server
the public ip should be used in the url instead of the ip for the
computer
A database should almost never be exposed on the public IP address. If you are having both computers on the LAN, the private network IP is what the server should listen on and that's what you should use on the connection string.
CommunicationsException along with "Connection timed out" in the stack
trace
Because the server is not running, not listening on that ip:port or firewalled to drop packets.

Java Wont connect to database no matter what driver

import java.sql.*;
public class Connect
{
public static void main (String[] args)
{
Connection conn = null;
try
{
String userName = "root";
String password = "password123!";
String url = "jdbc:oracle:thin:#localhost:3306:procomport";
//Class.forName ("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, userName, password);
//Connection connection = DriverManager.getConnection(url , userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
finally
{
if (conn != null)
{
try
{
conn.close ();
System.out.println ("Database connection terminated");
}
catch (Exception e) { /* ignore close errors */ }
}
}
}
}
This is my code I have multiple different databases but it wont connect to any of them what's the problem with this? I keep getting the error it cannot connect to the database. Although I can connect to it using other management tools is it a driver issue? How would I be able to tell if I had the drivers necessary?
The code you've provided to connect to the database won't connect to either MySQL nor Oracle as it stands because it's a mish-mash of attempts to connect to both.
For Oracle, the code should look something like:
String userName = "root";
String password = "password123!";
String url = "jdbc:oracle:thin:#localhost:1521:procomport";
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, userName, password);
(assuming you have a user called root on Oracle, and the Oracle SID is procomport). Note in particular the change of port number: MySQL typically uses 3306, Oracle uses 1521.
For MySQL the connection code should look like:
String userName = "root";
String password = "password123!";
String url = "jdbc:mysql://localhost:3306/procomport";
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, userName, password);
(assuming your MySQL database is called procomport). Note the different style of connection URL and the driver class name.
The Oracle driver is typically in a JAR file named ojdbc6.jar, and the MySQL in a JAR named something like mysql-connector-java-5.1.18-bin.jar.
Finally, when you write something like
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
}
you really aren't helping yourself. The exception e will almost certainly contain the reason why your database connection code isn't working, but by deliberately ignoring it you're making it much harder for yourself to figure out what has gone wrong.
To be honest with you, I'd be tempted to declare the main method throws Exception (by adding this to the end of the public static void main... line), and then you can delete your unhelpful catch block. If an exception is thrown and not handled within main, the JVM will print the stack trace for you before it exits.
After your:
System.err.println();
Place a:
e.printStacktrace();
Then you will see real error message. Probably the driver classes are not in the classpath.
Hope this will help you
Uncomment the line Class.forName("oracle.jdbc.driver.OracleDriver");
Make sure you have the Oracle dirver "oracle.jdbc.driver.OracleDriver" in the classpath

Categories