Java JDBC to Azure

摘要:Java JDBC to Azure

參考此篇文章

http://msdn.microsoft.com/zh-tw/library/windowsazure/gg715284.aspx

並下載

Microsoft JDBC Driver 4.0 for SQL Server

windows執行sqljdbc_<version>_<language>.exe

解壓縮後

到此資料下

Microsoft JDBC Driver 4.0 for SQL Server\sqljdbc_4.0\enu

取得

sqljdbc.jar,sqljdbc4.jar

引用至自己的lib下。

 

然後我改寫了一下範例中程式碼做測試


package test;

import java.sql.*;

public class ConnectToSQLAzure {
   private String server_name = " ";
   private String database_name = "";
   private String user_name = "";
   private String password = "";
   private String schema = "";
   private String table_name = "";

   public ConnectToSQLAzure()
   {

   }

   public void start(){

      // Create a variable for the connection string.
      String connectionUrl = "jdbc:sqlserver://"+this.server_name+".database.windows.net;" +
      "databaseName="+database_name+";user="+this.user_name+"@"+server_name+";password="+this.password+"";
      
      // Declare the JDBC objects.
      Connection con = null;
      Statement stmt = null;
      ResultSet rs = null;

      try {
         // Establish the connection.
         Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
         con = DriverManager.getConnection(connectionUrl);

         // Create and execute an SQL statement that returns some data.
         String SQL = "SELECT TOP 10 * FROM "+schema+"."+table_name;
         stmt = con.createStatement();
         rs = stmt.executeQuery(SQL);

         // Iterate through the data in the result set and display it.
         while (rs.next()) {
            System.out.println(rs.getString(2) + " " + rs.getString(3));
         }
      }
      // Handle any errors that may have occurred.
      catch (Exception e) {
         e.printStackTrace();
      }
      finally {
         if (rs != null) try { rs.close(); } catch(Exception e) {}
         if (stmt != null) try { stmt.close(); } catch(Exception e) {}
         if (con != null) try { con.close(); } catch(Exception e) {}
      }
   }
}

 

備註:

sqljdbc.jar & sqljdbc4.jar,只要放sqljdbc4.jar

因為兩個都放的話,可能會發生

此驅動程序不支持Java Runtime Environment (JRE) 1.6 版。請使用支持JDBC 4.0 的sqljdbc4.jar 類庫

錯誤。