How to connect to Azure SQL with JDBC

前端 未结 3 1851
粉色の甜心
粉色の甜心 2020-12-12 01:16

I try to connect to Azure SQL with MS JDBC driver:

import java.sql.*;

public class ExampleSQLJDBC {

    public static void main(String[] args) {

        /         


        
3条回答
  •  暖寄归人
    2020-12-12 01:31

    Per my experience, I think the issue was caused by the connection string which is the variable connectionUrl of your code.

    Please see the completed connection string below.

    jdbc:sqlserver://.database.windows.net:1433;database=;user=@;password={your_password_here};encrypt=true;hostNameInCertificate=*.database.windows.net;loginTimeout=30;

    You can find it at the link Show connection strings of the right bar of the tab DASHBOARD on Azure old portal (see Fig 1), or see it at the link Show database connection strings on Azure new portal (see Fig 2).

    Fig 1. Show connection string on Azure old portal

    Fig 2. Show database connection strings on Azure new portal

    Hope it helps. Any concern, please feel free to let me know.


    Update

    Here is my code for connecting SQL Azure.

    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        String hostName = "xxxxx";
        String dbName = "petersqldb";
        String user = "peter@xxxx";
        String password = "xxxxxxxx";
        String url = String.format("jdbc:sqlserver://%s.database.windows.net:1433;database=%s;user=%s;password=%s;encrypt=true;hostNameInCertificate=*.database.windows.net;loginTimeout=30;", hostName, dbName, user, password);
        Connection conn = DriverManager.getConnection(url, user, password);
        Statement stat = conn.createStatement();
        ResultSet rs = stat.executeQuery("select 1+1 as sum");
        while(rs.next()) {
            System.out.println(rs.getInt("sum"));
        }
        rs.close();
        stat.close();
        conn.close();
    }
    

提交回复
热议问题