I am exploring ways to connect to a SQL database using JDBC in Java and interact with it. Problem is no matter how I follow the syntax to make such connection it does not let me to connect to that instance of SQL Server on my laptop. I have seen other people being able to run such instances on their localhost instead and be able to connect to it via JDBS but I could not find any walkthroughs as how I can do the same. Any help with it will be greatly appreciated. Here is the connection I have on my laptop:
And here the JDBC connection URL that I try to make based on this on my code:
package helpers;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbHandler {
private static final String connectionUrl = "jdbc:sqlserver://LAPTOP-KAQ3H6IG//SQLEXPRESS:1433;database=pub;user=MyUserName;password=MyPassword";
public static void addNewJobWithName(String jobName) {
try (Connection connect = DriverManager.getConnection(connectionUrl)) {
connect.createStatement().execute("INSERT INTO [pub].[dbo].[jobs] (job_id, job_desc, min_lvl, max_lvl) VALUES (2,'QA3', 50, 100);");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
And the error I receive:
The TCP/IP connection to the host LAPTOP-KAQ3H6IG//SQLEXPRESS, port 1433 has failed. Error: "LAPTOP-KAQ3H6IG//SQLEXPRESS. 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:237)
Thanks in advance for your help
Did a combination of things based on the comments made here and some other posts I read on stack overflow regarding other things to do to fully solve this problem here are the things that I did:
Changed my connection URL string to this:
"jdbc:sqlserver://localhost:1433;database=pub;user=MyUserName;password=MyPassword;encrypt=true;trustServerCertificate=true";
On SQL Server configuration manager clicked on 'SQL Server Network Configuration' and enabled 'Named Pipes' and 'TCP/IP' in 'Protocols for SQLEXPRESS' (where my local MSSQL instance is setup).
Clicking on TCP/IP in the same window, switched to the IP Address tab and entered '1433' as the port number for the IPAII section right at the end of the list (Leave the other port sections empty).
Restarted SQL Server (SQLEXPRESS) from the list of services in Windows.
Hope it can help other people having the same problem as well.
Related
Dear StackOverFlowers,
I was trying event-driven LISTENER/NOTIFY on Postgres 9.6 (Windows 10).
I followed PGJDBC example given by Steve Taylor at https://www.openmakesoftware.com/postgresql-listen-notify-events-example/.
I started by downloading pgjdbc-ng-0.7-complete.jar and have put that in my CLASSPATH replacing standard JDBC driver.
When I am trying to connect to Postgres database using pgjdbc driver, I am getting an error:
connection received: host=127.0.0.1 port=50325
connection authorized: user=postgres database=scott
could not receive data from client: An existing connection was forcibly closed by the remote host.
Here are my system variables:
DBHost: localhost
DBName: scott
DBPort: 5432
DBUserName: postgres
DBPassword: postgres
I am not getting past the first hurdle, rest looks like Mount Everest. Please help me. Should you be needing the code, I am following Steve's code ditto.
Further to Joseph Larson's answer, the database is always running. I have connected to Postgres database from PGADMIN and Java successfully. I think issue is with the connect string. From Java when I am using standard JDBC which is provided by Postgres I am using URL like jdbc:postgresql://localhost:5432/dbname but PGJDBC suggests a different connect string like JDBC:PGSQL://localhost:5432/dbname. I tried to connect with that string (forcibly), it did not work. There is no method in PGJDBC PGDataSource for providing URL directly. I had to go through:
dataSource.setHost(DBHost);
dataSource.setPort(5432);
dataSource.setDatabase(DBName);
dataSource.setUser(DBUserName);
dataSource.setPassword(DBPassword);
And what URL it is sending to Database I am not able to figure out. Please suggest me a connect string and this problem is solved.
thanks
Thanks very much for asking me to post error messages:
Exception in thread "main" java.lang.NullPointerException
at com.impossibl.postgres.system.BasicContext.loadLocale(BasicContext.java:294)
at com.impossibl.postgres.system.BasicContext.init(BasicContext.java:273)
at com.impossibl.postgres.jdbc.PGConnectionImpl.init(PGConnectionImpl.java:251)
at com.impossibl.postgres.jdbc.ConnectionUtil.createConnection(ConnectionUtil.java:182)
at com.impossibl.postgres.jdbc.AbstractDataSource.createConnection(AbstractDataSource.java:723)
at com.impossibl.postgres.jdbc.PGDataSource.getConnection(PGDataSource.java:66)
at com.impossibl.postgres.jdbc.PGDataSource.getConnection(PGDataSource.java:58)
at PGListenNotify.<init>(PGListenNotify.java:26)
at PGListenNotify.main(PGListenNotify.java:37)
Here is source code:
import java.sql.SQLException;
import java.sql.Statement;
import com.impossibl.postgres.api.jdbc.PGConnection;
import com.impossibl.postgres.jdbc.PGDataSource;
public class PGListenNotify
{
PGConnection connection;
public PGListenNotify()
{
String DBHost = System.getenv("DBHost");
String DBName = System.getenv("DBName");
String DBUserName = System.getenv("DBUserName");
String DBPassword = System.getenv("DBPassword");
try
{
PGDataSource dataSource = new PGDataSource();
dataSource.setHost(DBHost);
dataSource.setPort(5432);
dataSource.setDatabase(DBName);
dataSource.setUser(DBUserName);
dataSource.setPassword(DBPassword);
connection = (PGConnection) dataSource.getConnection();
Statement statement = connection.createStatement();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
PGListenNotify ln = new PGListenNotify();
}
}
This looks like the Windows locale bug in pgjbdc-ng. It has been addressed, try the latest version 0.8.1.
The latest releases have detailed documentation related to asynchronous notifications here.
If it still fails to execute on your Windows system, please create an issue here.
Did you actually start a database server? I didn't know PostgreSQL server could run on Windows, but I've never tried.
I would simplify your problem a little. I know nothing about psql on Windows, but on Mac, I would start the server and then use the psql command (it's part of PostgreSQL) to ensure the server was up and running.
If you're to connecting, then the problems can be:
-There is no server at all
-The server isn't running on the port you're attempting
-The server isn't listening for connections on host 127.0.0.1 but could be listening on the actual IP address of your machine
-I'm not sure about that particular error, but username, password, or database may not exist.
I'd use psql to figure out which of those possible reasons is the real problem. That isolates out your program as being part of the problem, and it becomes entirely one of managing your database server.
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;
public class Database {
public static Connection con = null;
public static Connection connectDB() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://192.168.1.8:3306/registerdb", "root", "");
//JOptionPane.showMessageDialog(null, "Connection Successful");
return con;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
How I make my finish program share to others locally or using the internet and how to use the IP address for it? I'm using NetBeans for my java programming and XAMPP for my database.
Please help me.. THanks
Install db server on any computer, get servers IP address and port and pass that information to DriverManager.getConnection("jdbc:mysql://IP:port/dbname")
Its best to use property file to store IP and port and read it when creating connection so it can be easily changed without changing the code.
Your program should work as it is on multiple machines as long as they are in the same local network (as you are using local IP address).
If they are not able to connect to DB, following can be the possible reasons:
DB is not configured to allow connection from another machine. You
can grant it using following syntax:
grant all on db-name.* to username#'%' identified by 'password'
Your firewall is blocking income 3306 port requests. Open the port
for incoming requests.
I have created a database in cpanel using MySQL® Database Wizard. I have created a java class to access the database. For remote access I've added my IP to Remote MySQL® allow section & I have also allowed all privileges to a specific username with a password. Keeping all that settings, from my home computer I still can not access the database. I am running this java application in NetBeans. As the errors say:
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.
The source code goes like this:
package remoteserverconnection;
import java.sql.Connection;
import java.sql.DriverManager;
public class RemoteServerConnection {
public static void main(String[] args) {
Connection conn = null;
try
{
String url = "jdbc:mysql://domainIP:3306/DBNamne";
Class.forName ("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection (url,"UserName","password");
System.out.println ("Database connection established");
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Am I doing it in wrong way? Or is there any other way to connect that database from home pc?
It's possible that your host (judging from cPanel in the title) has a firewall rule set up that may be blocking access. That's very likely the case if it's a shared host which is the sort of service that typically uses cPanel.
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.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
This is an issue that has really been killing me, so I figured I would take it to you fine gentlemen/women to see if we can get a solution.
I am trying to connect to a SQL server 2005 (MSSQLSERVER, not SERVEREXPRESS or anything like that) I have set up on a machine running Windows Server from my labtop. My labtop is using a java connection string with JDBC 4.0 (via Netbeans IDE) JDK 1.7. It uses windows authentication. The connection code is the following:
String url;
url = "jdbc:sqlserver://[Server IP Address]\\[Instance Name]:1433;integratedSecurity=true";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url);
Instance name = UB-TCMG
Note: After [Server IP Address] there are two backslashes. If there is only one backslash, it is counted as an escape character. Two seems to only count as one.
Unfortunately, I don't have the error with me at this moment. Basically, it said "Connection refused: connection"
On the server side, I have done the following based upon online research. Enabled the TCP/IP port in SQL Server Configuration Manager. Erased all Dynamic TCP Ports. TCP Ports are 1433. VIA is enabled.
As well, surface area connection has been used to activate the SQL browser.
Using telnet from the laptop does not allow any connection.
Using telnet on the server works when:
telnet [Server Instance Name] 1433
Both firewalls have been shut off.
logs say "Server is listening on [ 'any' 1433]"
There's more I tried to solve this issue, but I'm literally falling asleep and can't remember. Anything you can suggest to help would be great.
This is the way how you will do connection in Java
import java.sql.*;
public class testConnection
{
public static void main(String[] args)
{
DB db = new DB();
db.dbConnect(
"jdbc:jtds:sqlserver://localhost:1433/tempdb","sa","");
}
}
class DB
{
public DB() {}
public voidn dbConnect(String db_connect_string,
String db_userid, String db_password)
{
try
{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
Connection conn = DriverManager.getConnection(
db_connect_string, db_userid, db_password);
System.out.println("connected");
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
This article might help please visit this link: http://www.java-tips.org/other-api-tips/jdbc/how-to-connect-microsoft-sql-server-using-jdbc.html
Found the solution.
The problem was two-fold. One, my laptop was accessing the internet via a static IP address. When I changed it to dynamic, I was able to connect to the server via land-line using a derivative of the above connection string.
The second problem has to do with the network I am using. For some reason, it blocks wireless access to the server. This is something I will resolve with the IT of the network. Still, I can access it through land-line since the IT has not blocked the relevant ports/addresses.
Try this might work for You..
String connectionUrl = "jdbc:sqlserver://localhost;databaseName=dbname;user=uname;password=pass";