Java connection to Windows SQL Server 2005 [closed] - java

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";

Related

How to setup a SQL Server instance on my localhost?

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.

PGJDBC: could not receive data from client:

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.

Connection to derby database refused

I am learning Java and trying to put together a simple App containing a few jTables connected to database that can be updated etc. To do this I have created a database with a few tables through Netbeans which I understand (and wish) to be embedded in the final distributable app.
I am following the Programming Knowledge tutorials on Youtube to create most of the GUI. Everting is OK as long as I open the Services tab on Netbeans and manually right-click my database(testDB) and click Start Server. Then when I run the following code I get a successful connection:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
//Register JDBC driver
Class.forName("org.apache.derby.jdbc.ClientDriver");
//Open a connection
String DB_URL = "jdbc:derby://localhost:1527/testDB";
String u_name = jTextField1.getText();
String p_word = jPasswordField1.getText();
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/testDB",u_name,p_word);
JOptionPane.showMessageDialog(null,"Details Correct - Connection established");
Close_me();
Open_Table_GUI(u_name,p_word);
}
catch(ClassNotFoundException | SQLException e){
System.out.println(e);
}
}
However if I run that code WITHOUT manually clicking on start server I get the following:
java.sql.SQLNonTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1,527 with message Connection refused.
I have read the apache documentation and due to my level of inexperience I am not getting anywhere.
I have also checked out the answers to similar connection questions on here but again I can't seem to relate the issue in a way that works.
The ultimate goal for me is to have an app I can distribute to run on windows machines that will have the database/tables all included individually editable etc. I would hope to eventually create a database that resides on a shared drive and each individual can connect to automatically - but that's way down the line for now.
My request here is that someone can help me understand what I need to change in my code so that the "Start Server" is automatically done.
Thanks in advance for nay response.
OK guys so I found code that seems to work for me from a question asked on here by LMS
private void setup(){
try{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
connection=DriverManager.getConnection("jdbc:derby:sheet;create=true","test","1234");
statement=connection.createStatement();
}
catch(ClassNotFoundException cnf){
System.out.println("class error");
}
catch(SQLException se){
System.out.println(se);
}
}
If anyone cares to link me to a reason why this in fact works that would be great, I'm assuming the Embedded driver doesn't go through the port and just looks within the project??
Anyway initially this seems to be solved!!
Please check your Server setting i.e.
-username and pwd in your program
and check that did you start the Derby server and is it listening at port 1527?

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".

Getting "IO Error: The Network Adapter could not establish the connection" randomly [duplicate]

This question already has answers here:
IOException: Network adapter could not establish the connection [duplicate]
(2 answers)
Closed 5 years ago.
I'm randomly getting "IO Error: The Network Adapter could not establish the connection" when trying to connect to an Oracle database through Java. Sometimes I have to run my application a couple times before it stops throwing the error.
// initializes database connection
private static Connection initializeDatabaseConnection(Properties prop) {
System.setProperty("oracle.net.tns_admin", prop.getProperty("tnsLocation"));
try {
Class.forName("oracle.jdbc.OracleDriver");
}
catch (ClassNotFoundException ex)
{
System.out.println(ex.getMessage());
}
String dbURL = "jdbc:oracle:thin:#" + prop.getProperty("serviceName");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
Connection conn = null;
try {
conn = DriverManager.getConnection(dbURL, username, password);
}
catch (SQLException ex)
{
System.out.println("Error initializing database connection. " + ex.getMessage());
System.exit(1);
}
return conn;
}
Any ideas as to why it throws that error randomly? I'm using JDK 1.7 with the ojdbc6.jar driver.
Download PingPlotter and turn it on (leave it running for 24 hours or so). Watch the historical graph, you'll likely find the IP address dropping or response times going through the roof at the same time your app can't connect to Oracle. You don't have a logic error, either the server is drastically overloaded, or you've got major congestion between you and it. Are you connecting through a VPN?
http://www.pingplotter.com/
Or just use ping from the command line in continuous mode for an hour or so:
ping -t <IP address or hostname>
Ping plotter doesn't ping as often and it creates nice graphs.
If you are working remotely, then it could be your ISP. Otherwise, talk to the network administrator or the DBA.
Obviously you can't go into production with a poor DB connection, so hopefully you just see this issue from your development environment. Try deploying to the machine where you plan to run the application eventually and see if it improves.
If there is nothing you can do to make it better, I recommend increasing your initial login timeout for your JDBC driver.
Google JDBC setLoginTimeout
Here is an example, although there are several ways to go about it, depending on your driver.
Connection timeout for DriverManager getConnection

Categories

Resources