I'm trying to connect to a Sql Server database called "Shipworks1". This installation of SQL Server was installed by a shipping software called Shipworks. I cannot get the authentication to work for some reason. Here is my code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package daily.sales.report;
/**
*
* #author Line Computer
*/
import java.sql.*;
public class DailySalesReport {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Connection con = null;
String conUrl = "jdbc:sqlserver://LINECOMPUTER\\SHIPWORKS; databaseName=ShipWorks1; user=sa; password=XXXXXXXXXXXXXXX;";
try {
// ...
con = DriverManager.getConnection(conUrl);
// ...
} catch (Exception e) { e.printStackTrace(); }
finally {
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
}
And my error:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'sa'. ClientConnectionId:916f2fe6-49c3-475f-bb09-f2ff14cd92c9
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:217)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:279)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:99)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:4346)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:3160)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$100(SQLServerConnection.java:43)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:3123)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7505)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2445)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1981)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:1628)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1459)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:773)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1168)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at daily.sales.report.DailySalesReport.main(DailySalesReport.java:27)
BUILD SUCCESSFUL (total time: 0 seconds)
I can connect to the DB in my db manger like so:
Any help would be appreciated. Thanks!
You should decide, which type of authentication you want to use: Windows authentication or SQL authentication.
Perhaps it will work for you:
String userName ="username";
String password ="password";
String url ="jdbc:sqlserver://myDB\\SQLServer;databaseName=name";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(url, userName, password);
Also, take a look on this - https://thusithamabotuwana.wordpress.com/2012/07/19/connecting-to-sql-server-from-java/
Related
I am trying to connect to my database by JDBC on localhost. Connecting via windows authentication is no problem, but I want to connect via SQL authentication. Therefore, I created a login and a user corresponding to this login in my database. I can normally log in SSMS:
My connection string for JDBC:
jdbc:sqlserver://localhost:1433;databaseName=TestBazyDanych;user=doszke;password=doszke123
Thrown exception:
com.microsoft.sqlserver.jdbc.SQLServerException: Login failed for user 'doszke'. ClientConnectionId:b7005fe3-904d-40c5-a89e-af0cb61250d6
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:254)
at com.microsoft.sqlserver.jdbc.TDSTokenHandler.onEOF(tdsparser.java:258)
at com.microsoft.sqlserver.jdbc.TDSParser.parse(tdsparser.java:104)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.sendLogon(SQLServerConnection.java:4772)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.logon(SQLServerConnection.java:3581)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.access$000(SQLServerConnection.java:81)
at com.microsoft.sqlserver.jdbc.SQLServerConnection$LogonCommand.doExecute(SQLServerConnection.java:3541)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7240)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2869)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:2395)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:2042)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectInternal(SQLServerConnection.java:1889)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:1120)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:700)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:677)
at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:251)
at main.Main.main(Main.java:38)
The username and password are the same, as those used for loging to SSMS.
Here my class code:
package main;
import java.sql.*;
public class Main {
private static ResultSet selectStan(Connection connection) throws SQLException {
String sql_stmt = "SELECT * FROM STAN;";
Statement statement = connection.createStatement();
ResultSet result = statement.executeQuery(sql_stmt);
System.out.println("Select executed");
return result;
}
public static void main(String[] args) {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String userName = "doszke";
String password = "doszke123";
String url = "jdbc:sqlserver://localhost:1433;databaseName=TestBazyDanych;user=doszke;password=doszke123";
try (Connection con = DriverManager.getConnection(url)) {
if(con != null){
System.out.println("connected");
} else {
System.out.println("unable to connect");
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
As Mark Rotteveel pointed out, I was trying to connect to a LocalDB instance with JDBC, which seemed undoable. (ref: here)
However, I installed jTDS and added to my classpath, changed my connection string to
jdbc:jtds:sqlserver://./TestBazyDanych;instance=LOCALDB#EB7165FD;namedPipe=true
create a connection by the use of this connection string, username and password and it worked. The instance pipe number was taken from cmd line via
sqllocaldb i MSSQLLocalDB
There are few things need to check:
Did you create doszke user under the database and SSMS?
Are you able to login with doszke/doszke123 credentials in SSMS?
Please check 1433 port are open or not in your inbound and outbound firewall.
Trying to telnet on localhost 1433. If it's getting failed change below setting:
Go to Configuration tools -> SQL Server Configuration Manager Select SQL Server Network Configuration -> Select protocol in the right side window enable tcp/ip and restart the services in services.
everyone!
I'm using the free account of OpenShift by RedHat PaaS to host my java aplication. For tests, I created an aplication that just get two user info (login and password) in the index.jsp, then it search into database and redirect to the success page(message "Good morning/afternoot/night, ${user.name}") or a failure page (message "You're not registred"). I also created a database, called autenticacao, with one table called usuario (user) in phpMyAdmin and this works well in localhost. But in the openshift, my servlet receives a null 'usuario' (user) object from the method obter(String login, String senha), that should get a result of one select query. I think it doesnt create a database connection. I've really tried so hard to make it works, and seen too many solutions in foruns (also here in stackoverflow) and nothing works.
Im using some design patterns but I think it's not a problem.
This is my DatabaseLocator.java:`
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
*
* #author Luiz
*/
public class DatabaseLocator {
private static DatabaseLocator instance = new DatabaseLocator();
public static DatabaseLocator getInstance() {
return instance;
}
private DatabaseLocator() {
}
public Connection getConnection() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
String user = System.getenv("OPENSHIFT_MYSQL_DB_USERNAME");
String password = System.getenv("OPENSHIFT_MYSQL_DB_PASSWORD");
String url = System.getenv("OPENSHIFT_MYSQL_DB_URL");
String host = System.getenv("OPENSHIFT_MYSQL_DB_HOST");
String port = System.getenv("OPENSHIFT_MYSQL_DB_PORT");
Connection conn
= DriverManager.getConnection(host+port+"/autenticacao",user,password);
return conn;
}
}
The error happens when I try create a connection in st = conn.createStatement(); part.
public Usuario obterUsuario(String login, String password) {
Usuario usuario = null;
Connection conn = null;
Statement st = null;
try {
conn = DatabaseLocator.getInstance().getConnection();
st = conn.createStatement();
ResultSet rs = st.executeQuery("select * from usuario where login='" + login + "' and senha='" + password + "'");
rs.first();
usuario = instanciar(rs);
} catch (ClassNotFoundException cnf) {
} catch (SQLException ex) {
System.out.println(ex.getCause());
}
return usuario;
}
public static Usuario instanciar(ResultSet rs) throws SQLException, ClassNotFoundException {
Usuario usuario = new Usuario();
usuario.setLogin(rs.getString("login"));
usuario.setSenha(rs.getString("senha"));
//other rs fields that would be setted to user object
return user;
}
}
This code is in portuguese, so if any word doesnt make sense, you can ask me. I have some other classes, I can show it if you want.
So, how can I connect to my database? Can you help me? Thanks.
Are you still facing this problem? If yes then try to make your openshift application non-scalable if it's set to scalable and vise versa if not. I've encountered this before I just don't remember exactly. In your case, port-forwarding in openshift will help if you don't want to change the scalability of your application. I use Jboss Dev Studio for creating my jboss app in openshift, in case you also want jboss.
You need to change the line:
Connection conn = DriverManager.getConnection(host+port+"/autenticacao",user,password);
It should be:
Connection conn = DriverManager.getConnection("jdbc:mysql:"+host+":"+port+"/autenticacao",user,password);
I am trying to connect to Derby database on my locahost using JDBC.
I have started the database using the command: java -jar lib;derbyrun.jar server start, which starts successfully on port 1527.
On another command terminal, I use the command: java -classpath .;lib;derbyclient.jar testsqldatabase.TestSQLDatabase but I get the error below:
java.sql.SQLException: No suitable driver found for jdbc:postgresql:COREJAVA
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at testsqldatabase.TestSQLDatabase.getConnection(TestSQLDatabase.jav
)
at testsqldatabase.TestSQLDatabase.runTest(TestSQLDatabase.java:39)
at testsqldatabase.TestSQLDatabase.main(TestSQLDatabase.java:26)
My datatbase.properties file contains the following lines:
jdbc.drivers=org.postgresql.Driver
jdbc.url=jdbc:postgresql:COREJAVA
jdbc.username=dbuser
jdbc.password=secret
The java program is is listed below:
public class TestSQLDatabase
{
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException
{
try
{
runTest();
}
catch(SQLException ex)
{
for(Throwable t: ex)
t.printStackTrace();
}
}
/*Runs a test by creating a table, adding a value,
showing the table contents, removing the table*/
public static void runTest() throws SQLException, IOException
{
try(Connection conn = getConnection())
{
Statement stat = conn.createStatement();
stat.executeUpdate("CTEATE TABLE Greetings (Message CHAR(20))");
stat.executeUpdate("INSERT INTO Greetings VALUES ('Hello, World!')");
try(ResultSet result = stat.executeQuery("SELECT * FROM Greetings"))
{
if(result.next())
System.out.println(result.getString(1));
}
stat.executeUpdate("DROP TABLE Greetings");
}
}
/*
* Gets a connection from the properties specified in the
* file database.properties. #return the database connection
*/
public static Connection getConnection() throws SQLException, IOException
{
Properties props = new Properties();
try(InputStream in = Files.newInputStream(Paths.get("database.properties")))
{
props.load(in);
}
String drivers = props.getProperty("jdbc.drivers");
if(drivers != null) System.setProperty("jdbc.drivers", drivers);
String url = props.getProperty("jdbc.url");
String username = props.getProperty("jdbc.username");
String password = props.getProperty("jdbc.password");
return DriverManager.getConnection(url, username, password);
}
}
Can anyone figure out why I am getting that error from the second command terminal?
Thanks, much appreciated
Derby is a database. PostgreSQL is a different database. You're running a Derby database and you need the corresponding Derby JDBC driver to talk to it - not the PostgreSQL one.
You want to connect to Derby by using the PostgreSQL driver (in the properties file); also the URL of the database is no written well; it should be: jdbc:${dataBaseVendor}:${server}:${port}/${databaseName} where in your case databaseVendor=derby.
And also make sure you have the Derby JDBC driver jar on your classpath.
below is my simple program of JDBC Oracle Connectivity. Please see and tell me why could I possibly get the error of driver not loading. I have put odbc14.jar in libraries.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package databaseconnect;
/**
*
* #author compaq
*/
import java.sql.*;
public class Education1 {
public static void main(String[] args) {
try{
Class.forName("oracle:jdbc:driver:OracleDriver");
}catch( Exception e ) {
System.out.println("Failed to load Oracle driver.");
}
try{
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","system");
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into Education(name,rollno) VALUES ('alankrit',1000)");
System.out.println("Data inserted");
con.close();
} catch(Exception e){
// System.out.println(e);
}
}
}
You need to pass the class name as below, replace : with .
Class.forName("oracle.jdbc.driver.OracleDriver");
Driver Implementation class with complete packages name in String format.
So that reflection api can load this class during run time
instead of
Class.forName("oracle:jdbc:driver:OracleDriver");
use
Class.forName("oracle.jdbc.OracleDriver");
and make sure you have odbc14.jar file in your classpath.
/**
*
*/
package ORM;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* #author Gwilym
* #version 0.0
*/
public class DatabaseConnection {
private String userName="";
private String password="";
private String host="";
Connection conn;
/**
* #param userName
* #param password
* #param host
*/
public DatabaseConnection(String userName, String password, String host) {
this.userName = userName;
this.password = password;
this.host = host;
}
public DatabaseConnection(String userName, String password, String host,boolean autoConnect) {
this.userName = userName;
this.password = password;
this.host = host;
if (autoConnect)
{
try {
Connect();
} catch (DatabaseConnectionException e) {
e.printStackTrace();
}
}
}
/**
* #return the connection
*/
public Connection getConn() {
return conn;
}
/**
* #param userName the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* #param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* #param host the host to set
*/
public void setHost(String host) {
this.host = host;
}
/**
* Connect, attempts to connect to the MySQL database
* with sun JDBC
* & MySQL driver
* #param none
* #return True iff connected;
* #return False for all else;
* #throws DatabaseConnectionException
*/
public boolean Connect() throws DatabaseConnectionException
{
// Attempt to load database driver
try
{
String url = "jdbc:mysql:"+host;
System.out.println(url);
//Load driver
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);
}
catch (ClassNotFoundException cnfe) // driver not found
{
conn=null;
System.err.println ("Unable to load database driver");
throw new DatabaseConnectionException(cnfe);
}
catch(InstantiationException ie)
{
conn=null;
System.err.println ("Unable to Create database driver");
throw new DatabaseConnectionException(ie);
}
catch (IllegalAccessException iae)
{
conn=null;
System.err.println ("Unable to Create database driver");
throw new DatabaseConnectionException(iae);
} catch (SQLException sqle) {
conn=null;
System.err.println ("SQL error");
throw new DatabaseConnectionException(sqle);
}
if (conn!=null)
{
System.out.println ("Database connection established");
return true;
}
else
{
System.out.println ("Database connection Failed");
return false;
}
}
/**
* Disconnects the System from the mySQL database
*
* #param none
* #return true, if successful
* #return false if not connection in existance
*/
public boolean Disconnect()
{
if (conn != null)
{
try
{
conn.close ();
conn=null;
System.out.println ("Database connection terminated normally");
return true;
}
catch (Exception e) {
//Ignore these errors as they all result in conn.close anyway
}
finally
{
conn=null;
System.gc();
// my removing the refrance to conncetion all calling the Garbage collecter we insure it is destoryed.
}
System.out.println ("Database connection terminated with errors");
return true;
}
else
{
System.out.println ("No Database connection present");
return true;
}
}
}
The above code is called by
DatabaseConnection db =new DatabaseConnection("USERNAME","PASSWORD","//tel2.dur.ac.uk:3306/dcs8s07_SEG",true);
for obvious reasons I have removed the user name and password , but they can be aassumed to be correct.
Right down to the problem its self I get a com.mysql.jdbc.exceptions.jdbc4.CommunicationsException when ever this code is run with the details "The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server."
My main problem at the moment is trying to discover what is actually going wrong.
In so far as I can tell the driver is being loaded correctly as my code does not throw a ClassNotFoundException, rather a SQLException of some kind.
So the problem is almost certainly the connection in some way. I can connect and query this database though a phpMyadmin located on the same server so I can assume that
1)The server is online
2)mySQL is working
3)the Username and password are correct
4) the database is present and i have the name correct
From this and "The driver has not received any packets from the server." I am wondering if the URL malformed?
URL= jdbc:mysql://tel2.dur.ac.uk:3306/dcs8s07_SEG
or there a simple setting that is incorrect on the server whihc is not allowing me to connect?
I have pondered on this problem and attempted several googles to no avail, so any idea would be of great help
thanks in advance SO!
This is a wrapped exception. What's the root cause of this exception? Look further in the stacktrace.
A very common root cause is java.net.ConnectException: Connection refused. I've seen this in almost 99% of the cases. If this is true in your case as well, then all the possible causes are:
IP address or hostname in JDBC URL is wrong.
Hostname in JDBC URL is not recognized by local DNS server.
Port number is missing or wrong in JDBC URL.
DB server is down.
DB server doesn't accept TCP/IP connections.
Something in between Java and DB is blocking connections, e.g. a firewall or proxy.
To solve the one or the either, follow the following advices:
Verify and test them with ping.
Refresh DNS or use IP address in JDBC URL instead.
Verify it based on my.cnf of MySQL DB.
Start it.
Verify if mysqld is started without the --skip-networking option.
Disable firewall and/or configure firewall/proxy to allow/forward the port.
The username and password are irrelevant in this problem. At this point the DB can't even be reached. You would have gotten a "Login failed" or "Not authorized" SQLException otherwise.
In addition to the last post you should also do a low-level telnet test, this is the best way to verify connectivity. This test will tell you if there is a firewall or other software blocking access to that port.
telnet tel2.dur.ac.uk 3306