getting issue while conecting the MS SQL server remotely through java code - java

This is my code for connecting to the Server remotely.
One thing more i would like to tell you guys that this code works only i am within my home network (the network in which server is installed) but i am unable to access it from other network
hey guys please fix it thanks in advance
public class SQLServerDemo
{
public static void main(String[] args)
{
// TODO code application logic here
try {
System.out.println("Hello from try");
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://192.168.0.2:1433;user=demo;password=demo;databaseName=SQL_Demo";
Connection conn = DriverManager.getConnection(url);
if (conn != null)
{
System.out.println("Connected");
} else if (conn == null)
{
System.out.println("NotConnected");
}
String queryString = "select * from UserDetail";
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(queryString);
while (rs.next()) {
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
}
}
catch (Exception e)
{
System.out.println("Exception: "+e.getMessage());
e.printStackTrace();
}
}
}
Exception
com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host GAUTAM-VAIO, port 1433 has failed.
Error: "null. 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)

You cannot use 192.168.0.2:1433, it's valid only in your internal LAN network.
You have to find your external IP out of your LAN.

Related

Java client cant connect to local mysql database?

I´m using eclipse and want to connect to my mysql database. I am new to SQL and thats my first time I want to do something like this. I´ve created two methods, which should connect to a mysql database, which is running on my PC. The first method should create a connection :
public static Connection connectionSQL() {
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/example";
String username = "example";
String password = "1111";
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println("Connected!");
} catch(SQLException | ClassNotFoundException e) {
System.out.println("ERROR: Cant connect to database! "+ e);
}
return null;
}
the second should create a table :
public static void createTable() {
try {
Connection connection = connectionSQL();
PreparedStatement ps = connection.prepareStatement("CREATE TABLE IF NOT EXISTS scammerjail(id int NOT NULL AUTO_INCREMENT, Username String, Countdown int, PRIMARY KEY(id))");
ps.executeUpdate();
} catch(SQLException e) {
System.out.println("ERROR: Cant create Table! " + e);
}
finally {
System.out.println("Table created!");
}
}
But everytime I try to run my Code, I get the following message:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Client does not support authentication protocol requested by server; consider upgrading MySQL client
I´m using maven as build tool and my dependency and its version isnt wrong I think.

java web app refuses to connect to SQL Database when deployed on Tomcat

So i am facing the following problem.
I have developed an web app that has the following connection to a SQL Server database. (db connection code attached)
public class DBConnection
{
private DatabaseMetaData dma;
private static Connection con;
private static DBConnection instance = null;
private static String security = "integratedSecurity=true;";
private DBConnection()
{
try {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
} catch (Exception e) {
System.out.println("Can not find the driver");
System.out.println(e.getMessage());
}
try{
con = DriverManager.getConnection("jdbc:jtds:sqlserver://<Machine>;databaseName=<DBName>; useNTLMv2=true;");
//set autocommit
con.setAutoCommit(true);
dma = con.getMetaData(); // get meta data
System.out.println("Connection to " + dma.getURL());
System.out.println("Driver " + dma.getDriverName());
System.out.println("Database product name " + dma.getDatabaseProductName());
}
catch(Exception e){
System.out.println("Problems with the connection to the database");
System.out.println(e.getMessage());
System.out.println(con);
}
}
public static void closeConnection()
{
try{
con.close();
System.out.println("The connection is closed");
}
catch (Exception e){
System.out.println("Error trying to close the database " + e.getMessage());
}
}
public Connection getDBcon()
{
return con;
}
public static DBConnection getInstance()
{
if (instance == null)
{
instance = new DBConnection();
}
return instance;
}
public static void startTransaction()
{ try{
con.setAutoCommit(false);
}
catch(Exception e){
System.out.println("fail start transaction");
System.out.println(e.getMessage());
}
}
public static void commitTransaction()
{ try{
con.setAutoCommit(true);
}
catch(Exception e){
System.out.println("fail commit transaction");
System.out.println(e.getMessage());
}
}
public static void rollbackTransaction()
{
try
{
con.rollback();
con.setAutoCommit(true);
}
catch(Exception e){
System.out.println("fail rollback transaction");
System.out.println(e.getMessage());
}
}
I am using a Tomcat 8 on InteliJ IDE for running the app and debugging. Which works fine. (DB connection is established)
The problem is that when i take the war file and deploy it in the same Tomcat Server i get no DB Connection. (No DB connection)
I have checked all the .jar files in the tomcat and the project and I have added all the needed files.
Can't seem to find what is causing this issue. Maybe there is someone who got stuck with the same issue
I can't get a proper undertanding what is causing this issue and how to fix it
**EDIT: Following I have added the error displayed when trying to load data
type Exception report
message Request processing failed; nested exception is java.lang.NullPointerException
description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.springframework.web.util.NestedServletException: Request
processing failed; nested exception is java.lang.NullPointerException
root cause
java.lang.NullPointerException
com.lifeletapp.business.dataLayer.DbLogIn.isValidUser(DbLogIn.java:27)
com.lifeletapp.business.HelloController.verifyLogin(HelloController.java:33)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
DbLogin class:
public class DbLogIn implements ILogIn
{
private Connection conn;
public DbLogIn()
{
conn = DBConnection.getInstance().getDBcon();
}
public Staff isValidUser(String userName, String password)
{
Staff staff = new Staff();
try {
String query = "SELECT * FROM Staff WHERE userName=? AND pass=?";
PreparedStatement preparedStatement = conn.prepareStatement( query );
preparedStatement.setString(1, userName);
preparedStatement.setString(2, password);
ResultSet resultSet = preparedStatement.executeQuery();
while( resultSet.next() ) {
staff.setUserID(resultSet.getInt("userID"));
staff.setfName(resultSet.getString("fName") );
staff.setlName(resultSet.getString("lName") );
staff.setUserName(resultSet.getString("userName") );
staff.setPass(resultSet.getString("pass") );
staff.setEmail(resultSet.getString("email") );
}
resultSet.close();
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
return staff;
}
}
This is more a config or server issue. Not a code issue.
As mentioned in the comments I have tested if var conn == null -> resulted true. And the connection dose not get nulled anywhere. Please view code. Then again the above code works when run from the InteliJ debugger.
So finally figured out what was the issue.
Why was it working on my IDE config:
1. I was using java JDK 1.7 as JAVA_HOME
2. I was using an older version of Tomcat as a build
3. In order to work with JDTS you need to extract the nlmauth.dll from the .jar archive and copy it to the configured env JDK(jdk1.7-->>bin->>copy here)
Why was it not working on Tomcat server:
1.I was using Tomcat 8.xxx
2.Tomcat 8.xx require JDk 8
3. In the JDK 8 i have not past the nlmauth.dll ( once i have done this everything was working)
In order to approach this issue the first clue will be looking into the tomcat server logs.
On my presumption this issue is prom to occur only when you have an Database connection establish via Integrated Security.
My presumption is related to the fact that in the tomcat log the main error that was denying the JDBC driver was based on the integrated security credentials.
Best of luck to you all out there.

"Invalid authorization specification" error on UCanAccess connect

I am having a problem with the UCanAccess driver namely that when I attempt to connect to a database using the following code
public static void main(String[] args) {
//establish connection with database in order to execute sql queries
try {
conn = DriverManager.getConnection("jdbc:ucanaccess://H:\\IT_PAT_Program_LOCALONLY\\IT_Pat_Database.accdb;showschema=true");
System.out.println("Connection Established");
} catch (SQLException ex) {
System.out.println("Could Not Connect to database\n"+ex);
}
//closes the database connection at program shutdown
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
conn.close();
System.out.println("Shutdown Succesful");
} catch (SQLException ex) {
System.out.println("An exception occured\n"+ex);
}
}
});
}
I am met with the following error:
Could Not Connect to database
net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::3.0.0 invalid authorization specification - not found: Admin
The database is also connected as a persistence unit however since I'm unaware of any way to make use of that from within the code (Google has been no help) this method seems to be my only option.
We can not see where you are doing the authorization in your code.
user ?
password ?
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection conn=DriverManager.getConnection(
"jdbc:ucanaccess://<mdb or accdb file path>",user, password);

java.sql.SQLRecoverableException: The Network Adapter could not establish the connection

Here's the code I'm using (Oracle database connectivity):
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=DriverManager.getConnection("jdbc:oracle:thin:#loclahost:1521:XE","system","system");
System.out.println("connection is established");
Statement stmt=conn.createStatement();
int i=stmt.executeUpdate("insert table students ( name varchar2(15),mobile number(10),age varchar2(1))");
System.out.println("Save Sucessfully");
stmt.close();
conn.close();
} catch(Exception e) {
System.out.println(e);
}
this.dispose();
Getting following Error:
java.sql.SQLRecoverableException: IO Error: The Network Adapter could
not establish the connection
You've got a typo in your connection string - use localhost instead of loclahost
use localhost in DriverManager.getConnection
Here is the code :
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","system","system");
System.out.println("connection is established");
Statement stmt=conn.createStatement();
int i=stmt.executeUpdate("insert table students ( name varchar2(15),mobile number(10),age varchar2(1))");
System.out.println("Save Sucessfully");
stmt.close();
conn.close();
}
catch(Exception e) {
System.out.println(e);
}
this.dispose();
}
The error could occur if your JDBC driver is unable to connect to oracle. Check if your oracle service is running and no firewall is blocking your connection.
Check if oracle is listening in port 1521 or not, if not fix the port issue and then try connecting to your database.
Collectively the things to check ,
Check if the listener service is running
No firewall is blocking
Your service is listening on the correct port number that you
specified in your code.

How to connect to Oracle DB using JDBC connection with out opening Oracle in my machine

Hi Below is the code I wrote for connecting to Oracle DB using JDBC connection and return some values. But this code establish the connection and returns the result if I am opening the oracle toad in my machine.
But when the oracle toad is closed and try to run this code, it will not connect.
Please let me knwo how to connect to oracle DB with out opening the oracle toad manually.
package library;
import java.io.IOException;
import java.sql.*;
public class DBAutomationConnection {
public static void main(String args[]) throws ClassNotFoundException, IOException, SQLException {
DBAutomationConnection dbconn = new DBAutomationConnection();
//Connection conn = dbconn.DBConnection1();
dbconn.DBConnection1("select * from employee where empid='test123'","ROLE_NAME");
}
public void DBConnection1(String query, String colName)throws IOException, ClassNotFoundException{
Connection connection = null;
Statement stmt = null;
try {
// Load the JDBC driver
String driverName = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
connection = DriverManager.getConnection("jdbc:oracle:thin:#//testhostname:1528/ServiceName", "XXAAA_U", "Jw9S");
System.out.println("Connection successful: " +connection);
try {
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
//String UserID = rs.getString("USER_ID");
String UserID = rs.getString(colName);
System.out.println(UserID);
}
} catch (SQLException e ) {
System.out.println("Could not execute query.");
//JDBCTutorialUtilities.printSQLException(e);
} finally {
if (stmt != null) { stmt.close(); }
}
} catch (SQLException e) {
System.out.println("Could not connect to the database");
}
}
You should initialize Oracle TNS-Listener Service from your OS settings>services. You may need to check your tns configuration.
you need to install ORACLE client in your system to connect oracle remotely.
http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html
Do you have Oracle Thin driver installed in your system? This link can guide you.

Categories