Cannot connect to Mysql database using Java - java

I am running the following code on a Windows Server box using Java on Eclipse.
Connection conn = null; // connection object
Statement stmt = null; // statement object
ResultSet rs = null; // result set object
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/errorcodes", "myusername", "mypassword");
System.out.println ("Database connection established");
}catch (Exception e){
System.err.println ("Cannot connect to database server");
}
And i keep seeing the "Cannot connect to database server error". Any ideas what i might be doing wrong?
I have tried netstat -an and i see :
TCP 127.0.0.1:4464 127.0.0.1:3306 Established

My guess? You haven't got the mysql jdbc connector jar in your classpath. It should be called something like mysql-connector-java-5.1.16-bin.jar, depending on your version of mysql
If you don't have that jar, visit here

Do you sure that it is mysql running on port 3306 and that it's version is supported by your connector/j?

i think you did not start the MySql server in your PC.before running your application

Try the followings:
Clean and rebuild the project in eclipse.
Try to access the mysql database using the username and password in command prompt to ensure the username and password are correct.
If you want to ensure the username and password , you have to query the user table in mysql table again to need another mysql admin account to query.

It is simple .. you need .jar file called mysql-connector-java-5.1.16-bin.jar ,,, download it and add it to your libs ...
good luck !!!

Related

My java connection returns a connection to server failure

Below is my connection to the server
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:81/user", "root", "");
JOptionPane.showMessageDialog(null, "Connection Established");
return conn;
}catch (Exception e){
JOptionPane.showMessageDialog(null, e);
return null;
}
The actual connection can be found on this line:
DriverManager.getConnection("jdbc:mysql://localhost:81/user", "root", "");
am using port 81 for mysql database because port 80 is being used by another program.
Please I need help solving this problem. And thanks in advance.
am using port 81 for mysql database because port 80 is being used by
another program.
The default TCP/IP port on which the MySQL server is listening is 3306 not 80.
MySQL defaults to port 3306 unless you specify another one in the "my.cnf" config file . Then it is very likely you are using the default 3306 port.
Try using the default port unless you changed it.
Try Below steps to find possible reason
1.Manually Ping and connect to Mysql Database from command line and check if you are able to connect or not.
2.Handle Java Exception in your code and print Exception Object.
3.Check if your server /Database is up and running.
4.Also if you have a MYSQl Client first try to connect from front end ,if you are able to connect then we you need to look into the JDBC Api Code and print the Exception and put System.out after each line of code.

How to connect to MySQL database using Java on another PC?

I have made a simple program that uses the connectivity String:
Class.forName("java.sql.DriverManager");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3305/project", "root", "xxxx");
Statement st = conn.createStatement();
Here 'project' is my database name and 'xxxx' is the password.
I have then created an .exe file that works fine on my own computer.
But how can other people on another computer use my program? Do they have to install MySQL? Or Can they access my computer's database on their computer?

Java connection string for sqlserver for localdb

I have done Java application using Netbeans and Sqlserver 2012.
So for developing the application i ran Sqlserver in particular port and used the below string for connecting.
public static Connection connectDB(){
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection("jdbc:sqlserver://localhost\\SQLEXPRESS:1433;databaseName=DB1;user=zubair;password=zubair1234");
//JOptionPane.showMessageDialog(null,"Connection established");
return conn;
}catch (Exception ex){
JOptionPane.showMessageDialog(null,ex);
return null;
}
}
Now for delivering the java application , I need to make the sqlserver db to be run locally within the application. Iam not an expert in java so little help i require to change the connection string.
For access db i know we can use "jdbc:odbc:DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ="+accessFileName+".accdb;";" this string and give the filename of the Db.
Is there any similar string for sqlserver db. I have copied the DB to my project folder.?
Connect to the database on the local computer by using a username and password:
jdbc:sqlserver://localhost;databaseName=DbName;user=MyUserName;password=*****;
Please read Building the Connection URL and follow the guidelines.
I don't have any running example with me.
But will surely post after trying it myself.
Secondly, I strongly recommend using properties files to store connection details.
Prefer XML over prop files.

JDBC connection to MSSQL server in windows authentication mode

In my following programme I am trying to connect MSSQL Server using jdbc in windows authentication. But getting following error
import java.io.*;
import java.sql.*;
import java.util.GregorianCalendar;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
class Cms_truncate
{
public static void main(String[] args)
{
Calendar cal = new GregorianCalendar();
//String name="cmscim";
//String filename = "D:\\programs\\Tomcat 6.0\\webapps\\timescape\\canteen_scheduller\\CMS_CSV\\cms_cim\\"+ name+"-"+cal.get(Calendar.YEAR) +"-" +(cal.get(Calendar.MONTH)+1) + "-"+cal.get(Calendar.DATE)+".csv";
Connection conn = null;
String url = "jdbc:sqlserver://localhost:1433;databasename=CMS_TIMES_MAIN;integratedSecurity=true";
String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String userName = "";
String password = "";
Statement stmt;
try
{
Class.forName(driver);//.newInstance();
conn = DriverManager.getConnection(url,userName,password);
String query = "select * from cim where sapId=10025331";
stmt = conn.createStatement();
int flag = stmt.executeUpdate(query);
System.out.println("flag = "+flag);
conn.close();
System.out.println("");
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am using SQL Server in windows authentication mode.
Do I need to do set up other things to connect MSSQL using jdbc in windows authentication.
ERROR:
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:241)
at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2243)
at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:491)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1309)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at Cms_truncate.main(Cms_truncate.java:28)
Using windows authentication:
String url ="jdbc:sqlserver://PC01\inst01;databaseName=DB01;integratedSecurity=true";
Using SQL authentication:
String url ="jdbc:sqlserver://PC01\inst01;databaseName=DB01";
Try following these steps:
Add the integratedSecurity=true to JDBC URL like this:
Url: jdbc:sqlserver://<<Server>>:<<Port>>;databasename=<<DatabaseName>>;integratedsecurity=true
Make sure to add the sqljdbc driver 4 or above version (sqljdbc.jar) in your project build path:
java.sql.DatabaseMetaData metaData = connection.getMetaData();
System.out.println("Driver version:" + metaData.getDriverVersion());
Add the VM argument for your project:
Find the sqljdbc_auth.dll file from DB installed server (C:\Program Files\sqljdbc_4.0\enu\auth\x86), or download from this link.
Place the dll file in your project folder and specify the VM argument like this:
VM Argument: -Djava.library.path="<<DLL File path till folder>>"
NOTE: Check your java version 32/64 bit then add 32/64 bit version dll file accordingly.
You need to add sqljdbc_auth.dll in your C:/windows/System32 folder. You can download it from http://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=11774 .
From your exception trace, it looks like there is multiple possibility for this problem
1). You have to check that your port "1433" is blocked by firewall or not. If you find that it is blocked then you should have to write "Inbound Rule". It if found in control panel -> windows firewall -> Advance Setting (Option found at Left hand side) -> Inbound Rule.
2). In SQL Server configuration Manager, your TCP/IP protocol will find in disable mode. So, you should have to enable it.
You need to enable the SQL Server TCP/IP Protocol in Sql Server Configuration Manager app. You can see the protocol in SQL Server Network Configuration.
For the current MS SQL JDBC driver (6.4.0) tested under Windows 7 from within DataGrip:
as per documentation on authenticationScheme use fully qualified domain name as host e.g. server.your.domain not just server; the documentation also mentions the possibility to specify serverSpn=MSSQLSvc/fqdn:port#REALM, but I can not provide you with details on how to use this. When specifying a fqdn as host the spn is auto-generated.
set authenticationScheme=JavaKerberos
set integratedSecurity=true
use your unqualified user-name (and password) to log in
As this is using JavaKerberos I would appreciate feedback on whether or not this works from outside Windows. I believe that no .dll is needed, but as I used DataGrip to create the connection I am uncertain; I would also appreciate Feedback on this!
i was getting error as "This driver is not configured for integrated authentication" while authenticating windows users by following jdbc string
jdbc:sqlserver://host:1433;integratedSecurity=true;domain=myDomain
So the updated connection string to make it work is as below.
jdbc:sqlserver://host:1433;authenticationScheme=NTLM;integratedSecurity=true;domain=myDomain
note: username entered was without domain.
If you want to do windows authentication, use the latest MS-JDBC driver and follow the instructions here:
https://msdn.microsoft.com/en-us/library/gg558122(v=sql.110).aspx
You should copy your .dll => here "mssql-jdbc_auth-9.4.0.x64.dll" in that folder => sqljdbc_9.4\enu\auth\x64 to your Java JDK/bin.
Shortly: => sqljdbc_9.4\enu\auth\x64\mssql-jdbc_auth-9.4.0.x64.dll
to Program Files\Java\jdk-16\bin
If it doesnt work, you can open your SQL Server 2019 Configuration Manager -> SQL Server Network Configuration , all protocol's name should be Enabled. After that you should click on (TCP/IP) / IP Addresses, you will see that IPALL-> TCP PORT should be 1433.
After struggling a lot, I finally found a solution, here we go -
Download the file jtds-1.3.1.jar and ntlmauth.dll and save it in Program File -> Java -> JDK -> jre -> bin.
Then use the following code -
String pPSSDBDriverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
Class.forName(pPSSDBDriverName);
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://<ur_server:port>;UseNTLMv2=true;Domain=AD;Trusted_Connection=yes");
stmt = conn.createStatement();
String sql = " DELETE FROM <data> where <condition>;
stmt.executeUpdate(sql);
Nop, you have a connection error, please check your IP server adress or your firewall.
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
ping yourhost (maybe the ping service was blocked, but try anyway).
telnet yourhost 1433 (maybe blocked).
Contact the sysadmin with the results.

Connecting to a MySQL Database with Java

I want to connect to my MySQL database with Java.
I am using JDBC and I have the driver installed. (com.mysql.jdbc.Driver)
The only problem is that I keep getting an error:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException The last
packet sent successfully to the server was 0 milliseconds ago.
Here is my code:
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql:/mydomain.com/mydatabase", "username", "password");
I am not positive how to compose the URL (and where I get my username and password) but I have done A LOT of research.
I am the only person with acess to my database and domain, so there's no use asking the admin.
I use phpMyAdmin to create the database(s) and manage them. Do I use my phpMyAdmin username and password or what?
By the way, my site is hosted on Yahoo! Small Business.
So my questions are:
How do I make the connection URL?
What is my username and password?
I would say you are missing a forward slash on your URL.
Connection connection = DriverManager.getConnection("jdbc:mysql://mydomain.com/mydatabase", "username", "password");
Or I have a feeling that there is something wrong with your access privileges. This same thing happened to me also and it was a problem of Firewall blocking the port on the server. So verify this is not the case.
How do I make the connection URL?
Are you missing a forward slash in your URL? I would've assumed it would be something like:
jdbc:mysql://server/database
Load the drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
connect with the data base
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/widget_corp","dbuser","dbpassword");
.....jdbc:mysql://this is use as it is
.....127.0.0.1 this is the address of localhost You can use the word "localhost" insted of "127.0.0.1"
.....dbuser is the data base user
.....dbpassword is the password of the dbuser
.....3306 is the default port used for database

Categories