Now Reading
SQL – JDBC connection

SQL – JDBC connection

Views  
views
14
  • JAVA code to connect to SQL
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.Statement;
    public class DbConnection {
    public static void main(String[] args) {
    Connection conn = null;
    String dbName = "< dbName >";
    String serverip="< serverip >";
    String serverport="XXXX";
    String url = "jdbc:sqlserver://"+serverip+"\SQLEXPRESS:"+serverport+";databaseName="+dbName+"";
    Statement stmt = null;
    ResultSet result = null;
    String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    String databaseUserName = "";
    String databasePassword = "";
    try {
    Class.forName(driver).newInstance();
    conn = DriverManager.getConnection(url, databaseUserName, databasePassword);
    stmt = conn.createStatement();
    result = null;
    String pa,us;
    result = stmt.executeQuery("");
    while (result.next()) {
    us=result.getString("Name");
    pa = result.getString("Description");
    System.out.println(us+"  "+pa);
    }
    conn.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
    
  • Unzip and Import this jar to your project:
    sqljdbc4-3.0
  • Parse the result as needed
View Comments (0)

Leave a Reply

Your email address will not be published.

Scroll To Top