MySQL server connection error? - java

My program is able to connect to localhost MySQL server to get the data from it. But when I uploaded the database onto a server I'm not able to connect any more.
final static String db_url = "jdbc:mysql://***.***.***.***:3306/oyutan";
String card = cardnumber.getText();
String pinn = pincode.getText();
String pindb = null;
String pinsql = "SELECT * FROM `card` WHERE `card_number`=" + card + ";";
try {
Class.forName(jdbc_driver);
con = DriverManager.getConnection(db_url, "bilig", "199108");
ps = con.prepareStatement(pinsql);
rs = ps.executeQuery();
if (rs.next()); {
pindb=rs.getString("code")+"";
cardnumber.setText(" ");
pincode.setText(" ");
}
}
catch(Exception g) {
System.out.println("Not Found!");
g.printStackTrace();
}
I can access the database with Command line, but this gives me error "Host '...' is not allowed to connect to this MySQL server". I gave myself all the privileges I need. Do I need another program such as Tomcat, Apache, etc?

i gave myself all the privileges i need.
Apparently MySQL disagrees with you.
You GRANT permission to particular users on particular machines. Here's an example:
create database contacts;
create user contacts identified by 'contacts';
-- this next one is what you're probably missing.
grant all on contacts.* to 'contacts'#'%';
grant select on `mysql`.`proc` to 'contacts'#'%';
use contacts;
Every use of the string "contacts" above is for an example of mine that happens to use a database with that name. I created a user named 'contacts' with password 'contacts'. (Not the most imaginative naming scheme.)
Adjust the values to meet you situation.

is the database server local?
i mean is it localhost to your code?
if not, you need to add a Host to the username you are using, which is the IP your code will be running from, so the db-server allows this user to connect from remote machine.

Related

How do I avoid an 'unknown database' error when using a custom database directory?

I'm working on a project and I have put my database folder in project folder. How can I make a database connection to any directory rather than just default MySQL dir in Java?
String MySQLURL = "jdbc:mysql://localhost:3306/C:\\Program Files\\SnakeGame";
String UserName = "root";
String Password = "admin";
Connection con = null;
try {
con = DriverManager.getConnection(MySQLURL,UserName,Password);
if (con != null) {
System.out.println("Database connection is successful !!!!");
}
} catch (Exception e) {
e.printStackTrace();
}
When doing this, I get this error:
java.sql.SQLSyntaxErrorException: Unknown database 'c:\program files\snakegame'
Your connection URL is wrong
String MySQLURL = "jdbc:mysql://localhost:3306/C:\\Program Files\\SnakeGame";
I am not sure why your MySQLURL contains C:\Program Files\SnakeGame
The connection URL for the mysql database is
jdbc:mysql://localhost:3306/[DatabaseName]
Where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running (we may also use the server's IP address here), 3306 is the port number, and [DatabaseName] is the name of the database created on the MySQL server.
Replace the [DatabaseName] name accordingly after creating the database in MySQL server
Combining localhost:3306/ with C:\\Program Files\\SnakeGame makes little sense for any database - either you're trying to connect to a file-based database (in which case the localhost... part makes no sense) or you're working with a server-based one (in which case the C:\... part makes no sense.
Also, this connection string would make little sense for a file-based database either because you didn't specify a specific file, just a path.
Incidentally, MySQL is server-based, not file-based. It's expecting a database name after the localhost:3306/ part, not a path (hence the error). The physical location of the actual database program is an installation/configuration issue - it has nothing to do with how you actually connect to the database server once it's already running.
Think about it this way: when you call an external database, web service, or web site, do you need to know which physical folder it's deployed to? Obviously not. The physical folders involved are completely irrelevant when calling MySQL or another database like this.
One of the comments pointed this out, but did you intend to use SQlite or some other file-based database here instead?

Mysql in localhost

I have already installed Mysql on my computer and I have already created my database.
I have also created a Java program that connects to the database using the code attached below.
If I publish the program, will the connection to the database work correctly on other users' computers?
Will it be a problem if the code is in "localhost"?
Thanks to everyone who will help me!
public static Connection getConnection() throws Exception{
try {
String url = "jdbc:mysql://localhost:3306/mybooks?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
String username = "root";
String password = "mypassword";
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
} catch (Exception e) {
System.out.println(e);
}
return null;
}
You will need to put a MySQL server on a machine that's accessible to all your users via a LAN or the internet. That machine will need to have a usable internet address, either a hostname like database.rich05.example.com or some IP address like 192.0.2.123.
Then you'll need to create an accounts and passwords on the MySQL server for your users. You may choose to create just one account for all your users, or a separate one for each user. (I suggest the latter approach.)
Then you'll need to change your connection string from
jdbc:mysql://localhost:3306/mybooks?whatever=val&whatever=val
to
jdbc:mysql://192.0.2.123:3306/mybooks?whatever=val&whatever=val
or
jdbc:mysql://database.rich05.example.com:3306/mybooks?whatever=val&whatever=val
or whatever the internet address is. Then you'll configure your program to use the correct usernames and passwords.
In Java programs, connection strings and usernames are often stored in properties files.
Explaining all this in detail is too much for a Stack Overflow answer. Give it a try and ask more specific questions if you need to.

java.sql.SQLException: Access denied for user 'root'#'remotehost' (using password: YES)

I'm trying to write a sample jdbc program to connect to mysql db which is in the remote machine
// JDBC driver name and database URL
String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String DB_URL = "jdbc:mysql://<remote machine>/<database>"
// Database credentials
String USER = "root";
String PASS = "mnlinux";
Class.forName(JDBC_DRIVER);
Connection con = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = con.createStatement();
String sql = "SELECT x FROM t";
ResultSet resultSet = stmt.executeQuery(sql);
while(resultSet.next()){
//Retrieve by column name
int id = resultSet.getInt("x");
//Display values
System.out.print("ID: " + id);
}
resultSet.close();
stmt.close();
con.close();
*Its returning Exception in thread "main" java.sql.SQLException: Access denied for user 'root'#'CurrentMachine' (using password: YES)*
while executing DriverManager.getConnection(DB_URL, USER, PASS);
Please help me to connect to the db.
My MySQL is up & running. Both dbserver & currentmachine are in same network (i'm able ping).
Thanks in advance.
Allow full access to database from any ip OR replace % with your IP from where do you want to access database and try.
GRANT ALL PRIVILEGES ON *.* TO '<mysql user>'#'%' WITH GRANT OPTION;
FLUSH PRIVILEGES ;
You need to give permission for that user
GRANT ALL PRIVILEGES ON *.* TO 'USERNAME'#'%' IDENTIFIED BY 'PASSWORD' WITH GRANT OPTION;
MySql requires permission user as well as connecting remote address.
Normally the root MySQL user can't connect from a remote machine, unless you edit it.
If you have MySQL Workbench running on current machine, try connecting over the network with the credentials you are using in your java. If it doesn't work from Workbench, it obviously won't work from java.
You can use the following SQL to create a new user:
CREATE USER 'someuser'#'%' IDENTIFIED BY 'somepassword';
GRANT ALL PRIVILEGES ON yourdatabase.* TO 'someuser'#'%' WITH GRANT OPTION;
or use Workbench to do it (on the MySQL machine). Connecting as root is generally not advised, but it's ok for getting things up and running. Eventually you should switch to a dedicated user and depending on your application, implement proper security.
PLEASE NOTE: some answers above suggest adding privileges... however, the root user already has these privileges and failure connecting with root is not a privilege issue. It's because root can't connect from a remote machine. SO... add a new user and grant that user permissions.

How to connect to a database using a distributed API?

I'm having trouble with my distributed application in java netbeans the program is running perfectly on the original machine where i created it. but when i build it and make a distribute folder and follow the instructions and try to run it, I got an error that localhost on port 1527 has been refused.
here is my code on my do connect function
public void DoConnect()
{
String host = "jdbc:derby://localhost:1527/KempDB";
String uName = "main";
String uPass = "admin";
try
{
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "select cv.checkvouchernumber, c.checknumber, paytoorder, bankcode, dateissued, amount from checkvoucher cv, checks c where cv.checkvouchernumber = c.checkvouchernumber and cv.checknumber = c.checknumber";
rs = stmt.executeQuery(sql);.....
..........
}
catch(SQLException err){
.......
}
so this is the code I used to connect with the database server, the database server I used is built-in with java. Its a apache derby...
like I said in the original machine where I created the program runs ok without errors but when I distribute the program to another machine there's an error refusing the connection.
How can I connect to the local machine where my database is? maybe you can help me on this.
Are the database Servers running on these machines?
Are u starting the database server programmatically?
If you try to connect a database Server with:
jdbc:derby://localhost:1527/KempDB
This Server needs to be up and running.
For your case you should use an embedded Database.
For the case your Database is already an embedded Database, then you can try using this URL:
jdbc:derby:KempDB
instead of:
jdbc:derby://localhost:1527/KempDB
Hav a look on this one

error connecting to mysql using java

i ran into a weird problem when connecting to mysql using java.
i'm running xampp with tomcat
i tried connecting to mysql from java. on my machine it works fine, but on a friends machine i get an error: access denied for user 'tomcat'#'localhost'
thing is - i managed to connect with the exact same info using php.
the java code for the connection is:
String url = "jdbc:mysql://localhost:3306/";
String dbName = "mta_db";
String driver = "com.mysql.jdbc.Driver";
String userName = "tomcat";
String password = "tomcat";
try {
Class.forName(driver).newInstance();
_conn = DriverManager.getConnection(url + dbName, userName, password);
} catch (Exception e) {
e.printStackTrace();
}
port is fine
any idea what could be the cause?
The error is probably on the MySQL side, that is, the tomcat user doesnt have privileges to connect from non-localhost.
For simplicities sake you can first create an account that is able to connect from anywhere, via the MySQL GRANT statement like so:
GRANT ALL ON mta_db.* to tomcat#'%' identified by 'yourpassword';
In this case the % is a wildcard for any host.
If you know the actual IPs of your connecting clients you can later crack it down, to be more security conscious.

Categories