The steps are as follows:
1. Download the jar package: Jtds-1.3.1.jar;
2. Copy the Jtds-1.3.1.jar directly to the Libs folder under the app under the project;
3. Create a Java class:
Packagecom.example.zhouy.mytest01;Importjava.sql.Connection;ImportJava.sql.DriverManager;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjava.sql.Statement;/*** Created by Administrator on 2017/12/14.*/ Public classDbutil {Private StaticConnection 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 (); } returncon; } Public Staticstring Querysql () {string result=""; Try{Connection conn= Getsqlconnection ("192.168.1.xx", "xx", "xxx", "DATABASE"); String SQL= "SELECT Top Ten * 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+ = "Query data Exception!" "+E.getmessage (); } returnresult; } Public Static voidMain (string[] args) {querysql (); }}
Run directly to test whether the connection is successful;
If a failed to create directory error appears, see a blog post;
If there is an Android network error ioexception:failed to connect to/127.0.0.1 (port 1433): Connect failed:econnrefused (Connect Ion refused) error please see a blog post;
How Android connects to SQL Server database