本周的一个项目中,需要在安卓APP上连接一个远程的SQL Server,先在电脑上用Java尝试,然后复制到Android中,使用的是数据库驱动是jtds.
一番折腾之后,测试成功。步骤如下:
1. 在SQL Server上新建一个用户(使用SQL Server认证)
2. 代码
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance(); String URL = "jdbc:jtds:sqlserver://111.1.111.11:1433/ReportData;instance=evrcc\\wincc;"; String USER = "kitty"; String PASS = "12345"; Connection DbConn = DriverManager.getConnection(URL, USER, PASS); System.out.println("连接成功》》"); Statement stmt = DbConn.createStatement(); ResultSet reset = stmt.executeQuery(" select top 5 * from dbo.AlarmInfo "); if( reset.next()) { String str1 = reset.getString(1); String str2 = reset.getString(2); String str3 = reset.getString(3); String str4 = reset.getString(4); System.out.println(str1 + " " +str2 + " " +str3 + " " +str4 + " "); }else { System.out.println("结果为空:"); } DbConn.close();
运行程序,输出: