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;
}
Related
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.
I am trying to connect MySQL database remotely from my local pc since 2 weeks but I failed . www.hdvoiz.com this is where I created my database and I am using Cpanel admin panel . please help me .
here is the Error msg
java.sql.SQLException: Access denied for user 'hdvoiz_user'#'95.218.172.137' (using password: YES)
here is my code
package rmotedb;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
System.out.println("-------- MySQL JDBC Connection Testing ------------");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your MySQL JDBC Driver?");
e.printStackTrace();
return;
}
System.out.println("MySQL JDBC Driver Registered!");
Connection connection = null;
try {
String url = "jdbc:mysql://hdvoiz.com:3306/hdvoiz_loy";
String username = "hdvoiz_user";
String password = "**********";
connection = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
}
You are using cPanel so you will have to add your ISP ip in remote mysql access list to access your mysql databases from your local PC.
Login your cPanel >> Database >> Remote MySQL >> Add your ISP IP
If you are still facing same issues then contact your hosting provider and ask them to enable mysql port in server firewall.
Verify that mysql are hearing to internet. From you local server 95.218.172.137 run telnet remote_server_or_remote_ip 3306. If telnet show timeout, your server block 3306 (Put 3306 or Port used by mysql if you are changed this port) port. It's a firewall question.
If point 1 show a "Connected to " but can't work your program verify that user are on mysql.user table, with permission for acces from local server IP. You can see this on shell with mysql command.
$ mysql
mysql> SELECT Host,user FROM mysql.user WHERE User LIKE 'user_mysql';
On Cpanel user, you must see, edit or add, GLOBAL permision for all users of this account to access mysql server, usin IP, or IP plus comodin %. If you add a IP or wildcard IP all your user on this account has permission to access remotely orm this Ip or one IP of range wildcard. Also you can verify this with
$ mysql
mysql> SELECT Host,user FROM mysql.user WHERE `Host` LIKE 'IP';
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".
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();
}
}
}
we are trying to connect to the host using the code shown below:
Connection con=null;
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://sql3.000webhost.com/a17644_cc","chat_cc", "pass");
ResultSet rs;
if(!con.isClosed())
{
Statement st = con.createStatement();
rs= st.executeQuery("SELECT * FROM user_info");
while(rs.next()){
t1.append(rs.getString(3));
}
}
} catch(Exception e) {
t1.setText(e.toString());
//e.printStackTrace();
} finally {
try {
if(con != null)
con.close();
}catch (java.sql.SQLException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
t1.setText(e.toString());
}
we have given internet permission also in the manifest file.
But getting the following error:
java.sql.exception: data source rejected establishment of connection, message from server:"Host '182.71.248.226. is not allowed to connect to this MySQL server"
This is the following details i got: please tell which name we must give in the connection
string
Domain chitchat.site90.net
Username a1740644
Password *
Disk Usage 0.14 / 1500.0 MB
Bandwidth 100000 MB (100GB)
Home Root /home/a1740644
Server Name server19.000webhost.com
IP Address 31.170.160.83
Apache ver. 2.2.19 (Unix)
PHP version 5.2.
MySQL ver. 5.1
Activated On 2012-05-01 02:14
Status Active
That error is telling you that the user does not have rights to connect and select the database. You need to either grant rights to all hosts, or hosts from the specific IP address you are using. To grant to all hosts, you'd have to issue this as an administrative user:
GRANT ALL ON a17644_cc.* TO 'chat_cc'#'%'
or alternatively
GRANT ALL ON a17644_cc.* TO 'chat_cc'#'182.71.248.226'
Assuming that the IP in question is static, and you want to constrain the connection by IP.
As pointed out by https://stackoverflow.com/a/1559992/700926 this is probably a security precaution. Check out the accepted answer to that question.
What is the port number of MySQL server?Maybe you left it away.
Alternitavely to the answer from gview you can set priviliges in MySQL Workbench.Navigate to Security -> Users and Priviliges.