步骤如下:
1.下载jar包:jtds-1.3.1.jar;
2.将jtds-1.3.1.jar直接拷贝到项目下的app下的libs文件夹下;
3.创建java类:
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.xx","xx","xxx","DATABASE");
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();
}
}
直接运行即可测试是否连接成功;
如果出现failed to create directory错误请看上一篇博文;
如果出现android 中Network error IOException: failed to connect to /127.0.0.1 (port 1433): connect failed: ECONNREFUSED (Connection refused)错误