Connecting to MySQL Server JDBC - java

I am trying to connect to a MySQL Server using JDBC tool in java (using eclipse). I was just wondering how to enter 2 user/password combinations. The first one is the one I use to connect to the server(for example when I ssh into the server) and the second one I enter into phpmyadmin. As of now, I am putting in the phpmyadmin password only into the jdbc connection properties and it's not connecting. This is my current statement:
conn = DriverManager.getConnection("jdbc:mysql://[IP of server]:3306/[Database Table name]", "[UserName (same as phpmyadmin)]","[Password (same as phpmyadmin)]");
I am getting a
java.sql.SQLException: null, message from server: "Host '[My computer's full host name]' is not allowed to connect to this MySQL server"
I was just wondering if I needed to enter my server login/password (the one I use for ssh) as well in addition to the phpmyadmin username/pwd. I am new to JDBC and MySQL server, so I would appreciate any tips.
Just for background, I am able to connect successfully through ssh and I can login to the server through phpmyadmin.

Here's how you can create an account that can access your server from another client machine:
CREATE USER 'bobby'#'localhost' IDENTIFIED BY 'some_password';
That creates the user, and says he can connect from localhost.
If he is on the machine 192.168.0.5, you'd do something like this:
CREATE USER 'bobby'#'192.168.0.5' IDENTIFIED BY 'some_password';
Then of course, you have to grant privileges appropriately:
GRANT ALL PRIVILEGES ON databasename.* TO 'bobby'#'localhost' WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON databasename.* TO 'bobby'#'192.168.0.5' WITH GRANT OPTION;
That's been my experience anyway.
You're probably better off reading this section on how to specify MySQL accounts.

When you log in from PHPMyAdmin, the web server is located on the same server that hosts the Mysql database (in your case). Mysql, by default, does not allow connections from remote hosts; only the local machine may access the database.
I'll take a shot in the dark and say that the computer you're running the java code on is not the same machine that is hosting the mysql server. You must configure Mysql to allow connections from remote hosts via the config file and then change the Host row of the mysql.users table for the specified user to allow connection from your IP address (or, if security isn't your concern, any IP address.)
To configure mysql to allow connections from remote hosts you must remove the "bind-address=" line from the configuration file.
To allow any host to log on to a specific mysql user, you must set the mysql.users Host` column to "%".
Both of these must be done.

public class MysqlConnect{
public static void main(String[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}

Related

Connect to a remote database server instead of localhost

I'm trying to connect to my WAMP sever by using its IP address in my LAN. So far I have written the following code, and I don't understand why it does not establish the connection.
public class DBConnect {
public static Connection connect()
{
Connection con=null;
try {
Class.forName("com.mysql.jdbc.Driver");
con=(Connection) DriverManager.getConnection("jdbc:mysql://192.168.1.2:3306/employee101?","root","");
JOptionPane.showMessageDialog(null, "Connection Success");
} catch (Exception e) {
System.out.println("inter.DBConnect.connect()");
}
return con;
}
}
The root mysql account is configured to only allow a connection from the PC running the MySQL Server. For obvious security reasons.
I suggest you go to the WAMPServer machine and login to MySQL as root, then create a new account, that is NOT a Super User account and HAS password. Using phpMyAdmin for this is probably easiest.
Then configure the domain for this account to allow connections from your network only (192.168.1) note only 3 of the 4 quartiles used will allow access from any IP in your network, but only from within your network. Allocate only the required privileges on the specific databases required, to the new account.
Then use this new account in your Java code.

Acess denied for user connecting Mysql java

When I'm trying to get connetcion with online mysql database I get this error:
java.sql.SQLException: Access denied for user ''#'89.229.59.50' (using password: NO)
My code is:
public static Statement stmt = null;
public static Connection conn = null;
private static final String dbURL ="jdbc:mysql://db4free.net:3306/dolar;user=neir#localhost&password=password";
private static void createConnection() {
try {
conn = DriverManager.getConnection(dbURL);
} catch (Exception except) {
except.printStackTrace();
}
}
And yes, I've added mysql connector to my project.
You have to make sure the user (neir) has remote access privileges.
If your using a hosting service make sure they allow your remote IP (89.229.59.50) to connect to MySQL Server.
If you're managing the MySQL Server make sure that it's configured to be accessed remotely, that's done in the my.cnf file, search and comment the line:
bind-address = 127.0.0.1
Hope this helps.
From the error you can already see that the user and password parameters are not used. This might give you a clue that there is something wrong with the JDBC connection URL.
You cannot put the user and password parameters in the connection URL.
You should use: getConnection(String url, String user, String password)
See: https://docs.oracle.com/javase/8/docs/api/java/sql/DriverManager.html#getConnection-java.lang.String-java.lang.String-java.lang.String-
This might be for user has not access privileges so you should do this.
CREATE USER 'enterusername'#'xxx.xxx.xxx.xxx' IDENTIFIED BY 'enterpassword';
Where xxx.xxx.xxx.xxx is you IP or if you want to do this for any IP then just write '%' instead 'xxx.xxx.xxx.xxx'
To grant privileges
GRANT ALL PRIVILEGES ON mor.* TO 'enterusername'#'xxx.xxx.xxx.xxx' WITH GRANT OPTION ;

is it possible to connect java application to online database

hello i am trying to connect my application to online database using the following code
import javax.swing.*;
import java.sql.*;
public class javacon {
Connection con = null;
private static final String url ="jdbc:mysql:\\sql204.byethost9.com:3306\\";
private static final String dbName = "b9_16134488_db";
private static final String userName = "b9_16134488";
private static final String password = "123.321";
public static Connection connectDB(){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://sql204.byethost9.com:3306/b9_16134488_db/",userName,password);
JOptionPane.showMessageDialog(null, "connection is succseful");
return con;
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
but i am getting error says the driver has not received any packet
from the server
i found one answer this one says i have to go to my cpanel in my host and add my ip address there but i need every user to be connect to the database to login and logout
Mysql database has file my.cnf where bind-address might be specified. If that is not there, then mysql bind itself to all interfaces, otherwise only to specified one. More about this Bind-address
Also I guess user must have permissions to connect to database. 'user'#'ipaddress'. And more you can read here Connection access
Your code seems fine, your problem probably is related with your MySQL database not allowing connections from your host. The easiest way to find if this is the problem is trying to connect to the database from the same machine with the same credentials with MySQL Workbench.
There are three main things that can block your MySQL from receiving external connections:
1) Configuration
Edit my.cnf removing the following line:
bind-address = 127.0.0.1
2) User Host
In MySQL all users have defined from which host the connection can home from. 'user'#'%' would allow you to connect from any host.
3) Firewall
Make sure that the port 3306 is open.

MySQL denied access in java, workbench access granted

I've been using java on a computer (lets call it PC1) to connect to a database on a server, and until recently it was working with no errors.
By working, I mean I could connect to the server using java on PC1, and access the info I needed from the tables using select statements.
The only changes that have been made are the ip addresses on PC1 and the server.
After changing the IP addresses, I then updated the grant table in mysql, and yet, I get the following error:
java.sql.SQLException: Access denied for user 'robot'#'aa-PC' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:946)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:885)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3421)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1247)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2775)
at com.mysql.jdbc.Connection.<init>(Connection.java:1555)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at WriteToMySql.connection1(WriteToMySql.java:26)
at WriteToMySql.main(WriteToMySql.java:259)
The strange part however, is that I am able to connect to the server's database using the mySQL workbench and access all data on them.
here's the java code:
String host = "jdbc:mysql://PC1IPAdress:3306/users";
String user= "robot";
String password="mypassword";
public void connect()
{
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("worked"); //this gets printed
connect = DriverManager.getConnection(host, user, password);
System.out.println("works"); // this does not get printed due to error
stmt = connect.createStatement();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
note: "users" is the name of the database
Any help will be greatly appreciated.
Thank you.
EDIT:
for testing purposes I tried turning off the firewall, but it did not help.
I think there may be an error in the code sample - it connects to PC1IPAddress when you mention that PC1 should be connecting to a server earlier in the post. Just want to make sure before we continue that it was a typo, as otherwise PC1 would be connecting to itself.
If you have administrative access to the server, connect to MySQL as root and use this query to show configured users and ensure the host field is correct: SELECT user, host FROM mysql.user WHERE user='robot';
If the above checks out, I would suggest looking into Windows user authentication. The fact that MySQL returned the Windows computer name ('aa-PC') and not its IP address seems to indicate it may be attempting to authenticate using Windows domain credentials: http://dev.mysql.com/doc/refman/5.5/en/windows-authentication-plugin.html
If you change the ip address of the client (PC1) make sure that you updated the host field as well when granting new rights to user "robot". Check the table "db", "user" and "host".

How to connect Java to Microsoft SQL server

I made a Java application to connect to a MySQL database.
The connection was made ​​in this way:
public class Connection {
public static Connection getConexao() throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
//System.out.println("Conectado");
return DriverManager.getConnection("jdbc:mysql://localhost/world","root", "rootadmin");
} catch (ClassNotFoundException e) {
throw new SQLException(e.getMessage());
}
}
}
Now I needed to change the connection from MySQL to Microsoft SQL Server 2012.
Can anyone help me change the connection to the database?
Thank you all very much.
First of all you will need JDBC drivers for MS SQL Server. Either from Microsoft or there are other options like jTDS.
Then you should use a connection string like jdbc:sqlserver://ServerName:Port;databaseName=;user=username;password=password;
Of course your SQL Server should be in mixed mode so you can connect with username and password created on server.
Applets run on users' computer, therefore you should open your SQL Server ports to all visitors which is a BAD idea.
Make database URL like :
jdbc:mysql://IP address:DatabasePort/DatabaseName,username, password
public class Connection {
public static Connection getConexao()throws SQLException{
try{
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/world","root", "rootadmin");
}catch(ClassNotFoundException e) {
throw new SQLException(e.getMessage());
}
}
}
This answer is presented for next visitors on this kind of question. Configuring the java driver connection for SQL Server can
be quite confusing for new users. I'll guide you here through SQL Management Studio (SMSS):
There're 2 kinds of authentification accepted on SQL Server. They are Windows & SQL Server authentification.
In this answer I'll active "sa" (syst. administrator) account for quick setup demonstration over the connection.
To enable the "sa" account (you can skip this if it had already been there):
Login as usual using default window authentification mode
Right click on the server name (i.e MYCOMPUTER223\SQLEXPRESS) > Security > go enable the SQL Server & Window authentification mode > ok
On the left tree menu, click Security > Logins > right click that "sa" > Properties > set up your "password" for this "sa" account
and then on the left menu there is the "Status"> enable the "Login:"
restart the SQL Server service
now login as "sa" through "SQL Server authentification mode" on the SMSS . Using the password we've just set up.
Enable the TCP/IP for the conn. instance (this is by default is disabled particularly on sql express editions):
Open "Sql Server Configuration Manager". This is installed along the installation of SQL Server engine.
"SQL Server Network Configuration" > "Protocol for SQLExpress" > enable the "TCP/IP"
right click that "TCP/IP" > "IP Address" > scroll down till you find "IPAll" and then just fill the "port" field with 1433
You can now use this credential for the SMSS:
username : sa
password : ...the password you've just set up above..
Or you can now use this credential on your external java based clients/data or BI tools/sql management tools such as Pentaho, Heidi SQL, DB Weaver or any particular java framework conn. manager descriptor, etc. :
hostname : localhost (or any custome host domains)
database name : your database name..
instance name : i.e SQLEXPRESS (this can be found through the SMSS, right click the server name > view connection properties)
port : 1433
username : sa
password : ...the password you've just set up above..
or via url/uri for the Java connection manager/factory:
String Connectionurl="jdbc:sqlserver://localhost:1433;DatabaseName=Yourdatabasename;user=sa;password=yourSApassword";
public Connection createConnection() throws NoSuchAlgorithmException {
System.out.println("Creating SQL Server DataBase Connection");
Connection connection = null;
try {
// Provide the java database driver
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// Provide URL, database and credentials according to your database
// .getConnection ("url/namadatabase, user, password")
String Connectionurl="jdbc:sqlserver://localhost:1433;DatabaseName=DummyDatabase;user=sa;password=YourSAaccountpassword";
connection = DriverManager.getConnection(Connectionurl);
} catch (Exception e) {
e.printStackTrace();
return null;
}
if (connection != null) {
System.out.println("Connection created successfully..");
}
return connection;
}

Categories

Resources