下面对android中出现的Network error IOException: failed to connect to /127.0.0.1 (port 1433): 做一下总结:
当用android程序调用本地的sqlserver的时候,当连接ip写成127.0.0.1的时候,怎么都连不通,出现以下的错误信息:
感觉好像是代码有问题或者是清单文件中某个权限忘加了,其实不是这样的。原来模拟器默认把127.0.0.1和localhost当做本身了,在模拟器上可以用10.0.2.2代替127.0.0.1和localhost,另外如果是在局域网环境可以用 192.168.0.x或者192.168.1.x(根据具体配置)连接本机,这样应该就不会报错了。
package com.example.zhouy.mytest01; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * Created by Administrator on 2017/12/14. */ public class DBUtil { private static Connection getSQLConnection(String ip,String user,String pwd,String db) { Connection con =null; try { Class.forName("net.sourceforge.jtds.jdbc.Driver"); con = DriverManager.getConnection("jdbc:jtds:sqlserver://"+ip+":1433/"+db+";charset=utf-8",user,pwd); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return con; } public static String QuerySQL(){ String result=""; try { Connection conn = getSQLConnection("192.168.1.101","yonghuming","mima","SHUJUKU"); String sql = "select top 10 * from users"; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); while(rs.next()) { String s1 = rs.getString("USRNAM"); String s2 = rs.getString("FULLNAME"); result += s1+" - " + s2 + "\n"; System.out.println(s1+" - "+s2); } rs.close(); stmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); result += "查询数据异常!"+e.getMessage(); } return result; } public static void main(String[] args){ QuerySQL(); } }
时间: 2024-12-30 04:23:12