SQL Server 2012为JDBC驱动配置XA

想要在项目中使用sqlserver的xa datasource就必须先配置sql server使其可以支持jdbc xa连接。微软doc中给出了详细的配置步骤和注意事项,请参考https://msdn.microsoft.com/en-us/library/aa342335.aspx
大致分为以下几步:

  1. 确保sqlserver所在机器的MSDTC服务可用
  2. 下载并安装SQL Server JDBC Driver http://go.microsoft.com/fwlink/?LinkId=245496
  3. copy sqljdbc_xa.dll至sqlserver的Binn目录(需重启sqlserver)
  4. 以sa的身份登陆SSMS执行xa_install.sql
  5. 执行下面的sql给login授权使用XA
USE master  
GO  
EXEC sp_grantdbaccess 'login_name', 'login_name'  
GO  
EXEC sp_addrolemember [SqlJDBCXAUser], 'login_name'  

还可以用下面这个java class测试配置是否成功

import java.net.Inet4Address;  
import java.sql.*;  
import java.util.Random;  
import javax.transaction.xa.*;  
import javax.sql.*;  
import com.microsoft.sqlserver.jdbc.*;  

public class testXA {  

   public static void main(String[] args) throws Exception {  

      // Create variables for the connection string.  
      String prefix = "jdbc:sqlserver://";  
      String serverName = "localhost";  
      int portNumber = 1433;  
      String databaseName = "AdventureWorks";   
      String user = "UserName";   
      String password = "*****";  
      String connectionUrl = prefix + serverName + ":" + portNumber  
         + ";databaseName=" + databaseName + ";user=" + user + ";password=" + password;  

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

         // Create a test table.  
         Statement stmt = con.createStatement();  
         try {  
            stmt.executeUpdate("DROP TABLE XAMin");   
         }  
         catch (Exception e) {  
         }  
         stmt.executeUpdate("CREATE TABLE XAMin (f1 int, f2 varchar(max))");  
         stmt.close();  
         con.close();  

         // Create the XA data source and XA ready connection.  
         SQLServerXADataSource ds = new SQLServerXADataSource();  
         ds.setUser(user);  
         ds.setPassword(password);  
         ds.setServerName(serverName);  
         ds.setPortNumber(portNumber);  
         ds.setDatabaseName(databaseName);  
         XAConnection xaCon = ds.getXAConnection();  
         con = xaCon.getConnection();  

         // Get a unique Xid object for testing.  
         XAResource xaRes = null;  
         Xid xid = null;  
         xid = XidImpl.getUniqueXid(1);  

         // Get the XAResource object and set the timeout value.  
         xaRes = xaCon.getXAResource();  
         xaRes.setTransactionTimeout(0);  

         // Perform the XA transaction.  
         System.out.println("Write -> xid = " + xid.toString());  
         xaRes.start(xid,XAResource.TMNOFLAGS);  
         PreparedStatement pstmt =   
         con.prepareStatement("INSERT INTO XAMin (f1,f2) VALUES (?, ?)");  
         pstmt.setInt(1,1);  
         pstmt.setString(2,xid.toString());  
         pstmt.executeUpdate();  

         // Commit the transaction.  
         xaRes.end(xid,XAResource.TMSUCCESS);  
         xaRes.commit(xid,true);  

         // Cleanup.  
         con.close();  
         xaCon.close();  

         // Open a new connection and read back the record to verify that it worked.  
         con = DriverManager.getConnection(connectionUrl);  
         ResultSet rs = con.createStatement().executeQuery("SELECT * FROM XAMin");  
         rs.next();  
         System.out.println("Read -> xid = " + rs.getString(2));  
         rs.close();  
         con.close();  
      }   

      // Handle any errors that may have occurred.  
      catch (Exception e) {  
         e.printStackTrace();  
      }  
   }  
}  

class XidImpl implements Xid {  

   public int formatId;  
   public byte[] gtrid;  
   public byte[] bqual;  
   public byte[] getGlobalTransactionId() {return gtrid;}  
   public byte[] getBranchQualifier() {return bqual;}  
   public int getFormatId() {return formatId;}  

   XidImpl(int formatId, byte[] gtrid, byte[] bqual) {  
      this.formatId = formatId;  
      this.gtrid = gtrid;  
      this.bqual = bqual;  
   }  

   public String toString() {  
      int hexVal;  
      StringBuffer sb = new StringBuffer(512);  
      sb.append("formatId=" + formatId);  
      sb.append(" gtrid(" + gtrid.length + ")={0x");  
      for (int i=0; i<gtrid.length; i++) {  
         hexVal = gtrid[i]&0xFF;  
         if ( hexVal < 0x10 )  
            sb.append("0" + Integer.toHexString(gtrid[i]&0xFF));  
         else  
            sb.append(Integer.toHexString(gtrid[i]&0xFF));  
         }  
         sb.append("} bqual(" + bqual.length + ")={0x");  
         for (int i=0; i<bqual.length; i++) {  
            hexVal = bqual[i]&0xFF;  
            if ( hexVal < 0x10 )  
               sb.append("0" + Integer.toHexString(bqual[i]&0xFF));  
            else  
               sb.append(Integer.toHexString(bqual[i]&0xFF));  
         }  
         sb.append("}");  
         return sb.toString();  
      }  

      // Returns a globally unique transaction id.  
      static byte [] localIP = null;  
      static int txnUniqueID = 0;  
      static Xid getUniqueXid(int tid) {  

      Random rnd = new Random(System.currentTimeMillis());  
      txnUniqueID++;  
      int txnUID = txnUniqueID;  
      int tidID = tid;  
      int randID = rnd.nextInt();  
      byte[] gtrid = new byte[64];  
      byte[] bqual = new byte[64];  
      if ( null == localIP) {  
         try {  
            localIP = Inet4Address.getLocalHost().getAddress();  
         }  
         catch ( Exception ex ) {  
            localIP =  new byte[] { 0x01,0x02,0x03,0x04 };  
         }  
      }  
      System.arraycopy(localIP,0,gtrid,0,4);  
      System.arraycopy(localIP,0,bqual,0,4);  

      // Bytes 4 -> 7 - unique transaction id.  
      // Bytes 8 ->11 - thread id.  
      // Bytes 12->15 - random number generated by using seed from current time in milliseconds.  
      for (int i=0; i<=3; i++) {  
         gtrid[i+4] = (byte)(txnUID%0x100);  
         bqual[i+4] = (byte)(txnUID%0x100);  
         txnUID >>= 8;  
         gtrid[i+8] = (byte)(tidID%0x100);  
         bqual[i+8] = (byte)(tidID%0x100);  
         tidID >>= 8;  
         gtrid[i+12] = (byte)(randID%0x100);  
         bqual[i+12] = (byte)(randID%0x100);  
         randID >>= 8;  
      }  
      return new XidImpl(0x1234, gtrid, bqual);  
   }  
}  
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
支持的操作系统: Linux, Unix, Windows 7, Windows Server 2008 R2, Windows Vista 上面的列表是某些受支持的操作系统的示例。JDBC 驱动程序可在任何支持使用 Java 虚拟机 (JVM) 的操作系统上工作。但是,只有 Sun Solaris、SUSE Linux 以及 Windows 操作系统经过了测试。 Java 开发工具包:5.0 和 6.0 受支持的 SQL Server 版本: Microsoft® SQL Server® 2012 Microsoft® SQL Server® 2008 R2 Microsoft® SQL Server® 2008 Microsoft® SQL Server® 2005 Microsoft® SQL Azure 返回页首返回页首 说明 JDBC Driver 的 Microsoft Windows 版本安装说明 注意:下载 Microsoft JDBC Driver 4.0 for SQL Server 则表明您接受此组件的《最终用户许可协议》(EULA) 的条款和条件。请查看此页上的《最终用户许可协议》(EULA) 并打印一份 EULA 以供备案。 1.将 sqljdbc_<版本>_<语言>.exe 下载到一个临时目录。 2.运行 sqljdbc_<版本>_<语言>.exe. 3.按照提示输入安装目录。我们建议您将此 zip 文件解压缩到 %ProgramFiles% 中的默认目录下:"Microsoft JDBC Driver 4.0 for SQL Server"。 4.在软件包解压缩之后,通过打开 %InstallationDirectory%\Microsoft JDBC Driver 4.0 for SQL Server\sqljdbc_<版本>\<语言>\help\default.htm 以打开 JDBC 帮助系统。此时将在 Web 浏览器中显示帮助系统。 JDBC Driver 的 UNIX 版本安装说明 1.将 sqljdbc_<版本>_<语言>.tar.gz 下载到一个临时目录。 2.若要解压缩此压缩的 tar 文件,请导航至要解压缩驱动程序的目录中,然后键入 gzip -d sqljdbc_<版本>_<语言>.tar.gz. 3.若要解压缩 tar 文件,请将其移至您要安装驱动程序的目录中,然后键入 tar –xf sqljdbc_<版本>_<语言>.tar. 。 4.在软件包解压缩之后,通过打开 %InstallationDirectory%/Microsoft JDBC Driver 4.0 for SQL Server/sqljdbc_<版本>/<语言>/help/default.htm 以打开 JDBC 帮助系统。此时将在默认的 Web 浏览器中显示帮助系统。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值