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

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.

Related

Postgres JDBC driver not returning error line number as shown in PGAdmin

Postgres JDBC driver not returning the exact error line number as shown in PGAdmin. When I run the below program :
import java.sql.*;
public class Test {
public static void main(String[] args) {
String query = "SELECT table_name, table_type\n" +
" FROM information_schema.tabls\n" +
" WHERE table_schema='public'\n" +
" AND table_type in ('BASE TABLE','VIEW') ORDER BY table_type, table_name;";
try (Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "postgres")) {
System.out.println("Connected to PostgreSQL database!");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
while (resultSet.next()) {
System.out.printf("%-30.30s %-30.30s%n", resultSet.getString("table_name"), resultSet.getString("table_type"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I am getting the following error :
org.postgresql.util.PSQLException: ERROR: relation "information_schema.tabls" does not exist
Position: 38
But when I run the same query on pgadmin4, I receive the following error :
ERROR: relation "information_schema.tabls" does not exist
LINE 2: FROM information_schema.tabls
^
SQL state: 42P01
Character: 38
I want the line number in java program as well. How can I get it?
PGAdmin4 is a node.js backend that uses Python driver psycopg2. This driver is nothing more than a wrapper for C driver named libpq, created by the PostgreSQL team.
JDBC driver communicates with database and uses responses received from the server. org.postgresql.core.v3.QueryExecutorImpl#receiveNoticeResponse private method responsible for parsing server errors and it just creates new org.postgresql.util.ServerErrorMessage instance. So, the response given by the server is equal to the response shown by the JDBC driver.
But as for libpq, messages received from the server, and shown on client-side aren't the same. There is reportErrorPosition method in libpq sources exactly for adding line information. Here is reference for reportErrorPosition sources for PostgreSQL 13.3. Here is place where LINE: x is added to the client error.
Summary
You need to calculate the line number by yourself when using the JDBC driver. Or use C library which does it for you.

arabic data problem when it inserts from the java application (mysql , javafx)

I have a problem when I enter data from the application to mysql database, it appears in the form of "????" However, when I enter data via "phpmyadmin" the data appears normally
well the problem is when i enter data via application ,
not related with database
any way i tried to change the encode of database and the table and the fields inside the tables
here the insert query in my application
public static void dbConnect() {
try{
Class.forName(DRIVER);
connector = DriverManager.getConnection(DATA_BASE_BATH, "root", "");
insert = connector.prepareStatement("INSERT INTO students VALUES (?,?,?,?)");
}
public static void insert(int id , String name , String special , double gpa){
dbConnect();
try{
insert.setInt(1, id);
insert.setString(2, name);
insert.setString(3,special);
insert.setDouble(4,gpa);
insert.execute();
}
catch(SQLException e){
System.out.println(e.getMessage());
}
}
here the image to understand the problem
-the first row is the data entry from the application
-and the second row is the data entry manually from the phpmyadmin
Your application isn't properly handling the data.
You need to set the charset during the connection to the MySQL server.
Perhaps by running the command SET NAMES 'UTF8'; as part of your connection script.
This answer states that you can even make it part the JDBC connection string in DATA_BASE_BATH when referenced in your getConnection() function call, as does this one.

How to access a database from a specific server using Java?

I am trying to access a database from a different server , but no success so far. The event is, when I choose the object "ALL" in my combobox, the table will load all data from different servers.
The current code, which I only connected to the localhost, works fine. However, when I try to connect another server to load both of their data, I get a syntax error when trying to put 192.168.1.51.sales.items in the String sqlall. Also, I tried modifying the prepareStatement by writing cn.prepareStatement(sqlall) + cn1.prepareSatement("union Select * from 192.168.1.52.sales.items); I have no more idea on how to connect on both servers.
I would like to apologize beforehand if you find my coding a bit messy. Thank you. My code is as follows:
private void combobox_branchItemStateChanged(java.awt.event.ItemEvent evt) {
Object branch = combobox_branch.getSelectedItem();
try
{
// All is selected
if("All".equals(branch))
{
Connection cn = db.itemconnector.getConnection();
String sqlall = " Select * from sales2.items union Select * from sales1.items union Select * from sales.items " ; //I tried accessing multiple databases in my own localhost and worked.
PreparedStatement ps = cn.prepareStatement(sqlall);
ResultSet rs = ps.executeQuery();
DefaultTableModel tm = (DefaultTableModel)itemTable.getModel();
tm.setRowCount(0);
while(rs.next())
{
Object o[] = {rs.getInt("id"), rs.getString("location"), rs.getString("product_name"),rs.getString("product_category"),rs.getString("product_description"),rs.getInt("product_stock"), rs.getFloat("product_price"), rs.getString("product_status")};
tm.addRow(o);
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Connection Error", JOptionPane.ERROR_MESSAGE);
}
}
And I have a class in a different package and this is its code:
package db;
import java.sql.*;
public class itemconnector {
public static Connection getConnection() throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:mysql://192.168.1.50:3306/sales","root","");
return cn;
}
It is not possible to query different databases on different servers in a single SQL query.
It is also not possible to get around this by "concatenating" prepared statements. (For a start, that is nonsensical Java!)
You need to open a separate Connection to each separate database server and query the relevant tables on that server. Then combine the information from the separate ResultSet objects in Java code.
The "combining" will be something like iterating the results in each result set and adding them to a Java data structure ...

SQL Server settings

I have a SQLServer database named : EventConsumerDB.
I have created Login, Password and User for this Login :
CREATE LOGIN EventConsumer WITH PASSWORD = 'EventConsumer', DEFAULT_DATABASE = EventConsumerDB;
CREATE USER EventConsumer FOR LOGIN EventConsumer;
Granted ROLE is : db_accessadmin
From Eclipse, I try to create the connection to this DataBase :
URL : jdbc:sqlserver://MyPC:1433;DATABASE_NAME=EventConsumerDB
Username : EventConsumer
Password : EventConsumer
Drive classname = com.microsoft.sqlserver.jdbc.SQLServerDriver
The result is always the same :
It's the first time I install a SQL Server at home, it's quiet complicated...
Is there anything I've forgotten ?
Thanx by advance.
Have you tried this: Connection-URL - Example ?
It shows you how to connect to an sql server via an URL:
public class ConnectURL {
public static void main(String[] args) {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://<server>:<port>;databaseName=AdventureWorks;user=<user>;password=<password>";
try (Connection con = DriverManager.getConnection(connectionUrl); Statement stmt = con.createStatement();) {
String SQL = "SELECT TOP 10 * FROM Person.Contact";
ResultSet rs = stmt.executeQuery(SQL);
// Iterate through the data in the result set and display it.
while (rs.next()) {
System.out.println(rs.getString("FirstName") + " " + rs.getString("LastName"));
}
}
// Handle any errors that may have occurred.
catch (SQLException e) {
e.printStackTrace();
}
}
}
OK, thanx to those who've tried to help me.
The problem was the following : When I installed the product (Windows 10 platform), Windows Authentication was the default authentication mode.
Solution found on MS page : "Change Server Authentication Mode"
In the SSMS, right-click on the server name > properties > security.
Then in the "server authentication" block, replace Windows Authentication Mode by SQL Server and Windows Authentication Mode.
Restart the server.
Note : don't forget to activate the TCP-IP protocol if needed. To turn it ON, you'll have to use the SQL Server Configuration console or PowerShell

"Could not create connection to database server" netbeans google cloud sql error

I am trying to create my first API using java httpServlet and netbeans which will be connected to a database on google cloud based its examples and documentations. I have not created the database, but I was given the necessary credentials and vars to create the connection. So I have downloaded the project from github, and when I tried to open it from netbeans there was some issues concerning dependencies ... So I resolved them, I replaced the credentials with their values and run the project; Unfortunately an error was thrown: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server. I made some searches but did not get any result... Could it be an error from this code ? an error from database security if it was invisible on cloud? Any help is more than appreciated.
public class ListTables {
public static void main(String[] args) throws IOException, SQLException {
String instanceConnectionName = "<foo:foo:bar>";
String databaseName = "myDatabaseName ";
String username = "myUsername ";
String password = "<myPass>";
if (instanceConnectionName.equals("<insert_connection_name>")) {
System.err.println("Please update the sample to specify the instance connection name.");
System.exit(1);
}
if (password.equals("<insert_password>")) {
System.err.println("Please update the sample to specify the mysql password.");
System.exit(1);
}
String jdbcUrl = String.format(
"jdbc:mysql://google/%s?cloudSqlInstance=%s&"
+ "socketFactory=com.google.cloud.sql.mysql.SocketFactory",
databaseName,
instanceConnectionName);
try{
Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
/* try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery("select * from wf_accounts;");
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}
}*/
}catch(Exception ex){
System.out.println("Error: " + ex.toString());
}
Update
Same error was thrown when I did this:
String jdbcUrl = String.format(
"jdbc:mysql://google/%s?cloudSqlInstance=%s&"
+ "socketFactory=com.google.cloud.sql.mysql.SocketFactory",
"",
"");
Any hints?
First you have to check whether the mysql server is running on.If you are Windows user you can simply
Go to Task Manager
Go to Services
then search for your Mysql server(eg:for my case its MYSQL56)
then you will see under the status column it says its not running
by right clicking and select start
If it's already running then you have to do as in mysql Documentation,
You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property
autoReconnect=true
to avoid this problem

Categories

Resources