Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JDBC Example for java

Tags:

java

sql

I have downloaded JDK 6 and also I have sqljdb4.jar and I have database.properties file that content the following data

database.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
database.url=jdbc:sqlserver://.;databaseName=UserInfo;integratedSecurity=true; 
database.username=sa
database.password=admin

B.N : I'm installing the server on my machine and the server name = . , also I'm using Windows Authontication

My problem now is when I try to create connection I have the following error

com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: Connection refused: connect. Please verify the connection properties and check that a SQL Server instance is running on the host and accepting TCP/IP connections at the port, and that no firewall is blocking TCP connections to the port. at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:130)

I don't know what is the exact problem here

If any one can help I will be appreciated

Thanks in Advance

like image 886
Amira Elsayed Ismail Avatar asked May 04 '11 15:05

Amira Elsayed Ismail


1 Answers

That's caused by many probabilities like 1- IP is worong 2- Port is wrong 3- There is firewall prevent machine to go out and connect to another IP 4- SQL server down .

try to use

    public class JdbcSQLServerDriverUrlExample
{
  public static void main(String[] args)
  {
    Connection connection = null;
    try
    {
      // the sql server driver string
      Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

      // the sql server url
      String url = "jdbc:microsoft:sqlserver://HOST:1433;DatabaseName=DATABASE";

      // get the sql server database connection
      connection = DriverManager.getConnection(url,"THE_USER", "THE_PASSWORD");

      // now do whatever you want to do with the connection
      // ...

    }
    catch (ClassNotFoundException e)
    {
      e.printStackTrace();
      System.exit(1);
    }
    catch (SQLException e)
    {
      e.printStackTrace();
      System.exit(2);
    }
  }
}

What i need to explain is there is very good technology called " Persistence " is better than JDBC and is more than brilliant and easy to use .

like image 90
Amr Salah Avatar answered Oct 13 '22 12:10

Amr Salah