Im new to java programming.
I want to establish a connection to
my MS-sql database using java.
How do i do it?

Dani AI

Generated

As started this thread, and given 's and 's early notes, here is a short, modern, practical approach that avoids the legacy bridge and covers common pitfalls.

Use the vendor JDBC driver (Microsoft) rather than the old JDBC‑ODBC bridge; it is actively supported and works with current JDKs. The driver exposes a DataSource implementation you can configure in code or via your container. Example (DataSource + try‑with‑resources):

import com.microsoft.sqlserver.jdbc.SQLServerDataSource;
import java.sql.*;

SQLServerDataSource ds = new SQLServerDataSource();
ds.setServerName("localhost");
ds.setPortNumber(1433);
ds.setDatabaseName("MyDatabase");
ds.setUser("sa");
ds.setPassword("secret");

try (Connection conn = ds.getConnection();
     PreparedStatement ps = conn.prepareStatement("SELECT TOP 1 * FROM MyTable");
     ResultSet rs = ps.executeQuery()) {
    while (rs.next()) {
        System.out.println(rs.getString(1));
    }
}

Quick troubleshooting checklist:

  • Put the Microsoft driver JAR (mssql-jdbc) on the application classpath; missing JAR causes ClassNotFoundException.
  • Ensure SQL Server allows TCP/IP, the correct port (default 1433) is open, and named instances may require SQL Server Browser or an explicit port.
  • For Windows Integrated Authentication, the driver needs the native auth DLL that matches JVM bitness; see Microsoft docs for setup details.
  • Prefer connection pooling (HikariCP, container DataSource) in production and always close JDBC resources (try‑with‑resources is concise and safe).

See the Microsoft JDBC driver documentation for driver download and connection properties and the Java try‑with‑resources guide for safe cleanup:

Recommended Answers

All 2 Replies

First declare your URL (in string format of cours
Remember your URL is
1 a String
2 "jdbc:odbc:"+dataSourceName;

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")//often the standard;
Connection con = DriverManager.getConnection(url,"username","password");
Statement stmt = con.createStatement();

this is as far as connection goes

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")//often the standard;

Case Sensitive

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.