android通过.net连接远程pc数据库

我学到了android连接远程数据库,下面我是通过sql数据库来举例

testWebService.java:

package com.testWebService;


import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;


import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;


public class TestWebService extends Activity {





private TextView tv;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);


tv = (TextView) findViewById(R.id.tv);
tv.setText(ws());
}
//登陆

private String CheckLog(String UserName,String UserPwd)
{
String NameSpace = "http://tempuri.org/";// 这里和asmx中的NameSpace属性保持一致,这里我记得是可以更改的,但是两者要一样(没有试过,感兴趣的朋友可以试试)
String u = "http://192.168.0.121:8013";// 请更换成你要访问的服务器地址
String webService = "/WebServiceForAndroid.asmx";// webService目录
String MethodName = "GetCount";// 要调用的webService方法
String soapAction = NameSpace + MethodName;
String url = u + webService;// 最终要访问的网址  这里也可以直接url="http://192.168.0.121:8013/WebServiceForAndroid.asmx"两个效果都是一样的


String result = "";
try {
SoapObject request = new SoapObject(NameSpace, MethodName);// NameSpace
request.addProperty("name", UserName);//这里的name名称必须和asmx中xml节点名称保持一致(这里是重点,不然传值传不过去)下面有图,请看图
request.addProperty("pass", UserPwd);
// webService方法中的参数,这个根据你的webservice来,可以没有。
// 请注意,参数名称和参数类型,客户端和服务端一定要一致,否则将可能获取不到你想要的值
// request.addProperty("x",5);
// request.addProperty("y", 6);


SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);


envelope.dotNet = true;// 访问.NET的webservice


envelope.setOutputSoapObject(request);


HttpTransportSE ht = new HttpTransportSE(url);


ht.call(soapAction, envelope);// 调用call方法,访问webservice


if (envelope.getResponse() != null) {
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
// 如果要返回对象集合,在服务端可以将对象或集合序列化成json字符串返回,这边再反序列化成对象或集合
result = response.toString();// 这里获得了webService的返回值
}


} catch (Exception e) {
result = e.getMessage();
}
return result;
}

// webService操作要访问网络,所以最好是使用线程来做,这里只是示例,所以就不考虑了
private String ws() {
String NameSpace = "http://tempuri.org/";// 这个是web中asmx中的NameSpace 保持一致,这里可以选择另外一种方式,这里就不举例了
String u = "http://192.168.0.121:8013";// 请更换成你要访问的服务器地址
String webService = "/WebServiceForAndroid.asmx";// webService目录
String MethodName = "HelloWorld";// 要调用的webService方法
String soapAction = NameSpace + MethodName;
String url = u + webService;// 最终要访问的网址


String result = "";
try {
SoapObject request = new SoapObject(NameSpace, MethodName);// NameSpace
// webService方法中的参数,这个根据你的webservice来,可以没有。
// 请注意,参数名称和参数类型,客户端和服务端一定要一致,否则将可能获取不到你想要的值
// request.addProperty("x",5);
// request.addProperty("y", 6);


SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);


envelope.dotNet = true;// 访问.NET的webservice


envelope.setOutputSoapObject(request);


HttpTransportSE ht = new HttpTransportSE(url);


ht.call(soapAction, envelope);// 调用call方法,访问webservice,必须将防火墙关闭,不然这里就直接闪退了,如果是远程服务器,要看防火墙或者是否给你配有对外端口


if (envelope.getResponse() != null) {
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
// 如果要返回对象集合,在服务端可以将对象或集合序列化成json字符串返回,这边再反序列化成对象或集合
result = response.toString();// 这里获得了webService的返回值
}


} catch (Exception e) {
result = e.getMessage();
}
return result;
}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  android:id="@+id/tv"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello" //到string中注册,可也不要,这里是如果没有从远程服务器上获取返回值显示hello world

    />
</LinearLayout>

web端:

WebServiceForAndroid.asmx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.Web.Services.Protocols;


namespace WebService
{
    /// <summary>
    /// WebServiceForAndroid 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    //[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    //[System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    [SoapDocumentService(RoutingStyle = SoapServiceRoutingStyle.RequestElement)] 
    public class WebServiceForAndroid : System.Web.Services.WebService
    {
        private static string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["WebService"].ToString();//在config中添加节点:

<connectionStrings>
    <add name="WebService" connectionString="server=.;database=StockManage;uid=sa;pwd=123456;" providerName="System.Data.SqlClient" />
  </connectionStrings>
        SqlConnection myStr = new SqlConnection(connStr);


        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World  你已经成功连接到pc额";
        }
        /// <summary>
        /// 判断登录
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        [WebMethod]
        public int Verdict(string name, string pass)
        {
            int b = 0;
            try
            {
                #region 查询
              
                string sql = "select * from [User] where UserName='" + name + "' and UserPass='" + pass + "'";
                SqlCommand MyCommand = new SqlCommand(sql, myStr); //定义一个数据库操作指令
                SqlDataAdapter SelectAdapter = new SqlDataAdapter();//定义一个数据适配器
                SelectAdapter.SelectCommand = MyCommand;//定义数据适配器的操作指令
                DataSet MyDataSet = new DataSet();//定义一个数据集
                myStr.Open();//打开数据库连接
                SelectAdapter.SelectCommand.ExecuteNonQuery();//执行数据库查询指令
                myStr.Close();
                SelectAdapter.Fill(MyDataSet);
                int n= MyDataSet.Tables[0].Rows.Count;
                if (n!= 0)
                {
                    b = 1;
                }
               
                #endregion




            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString()); 
            }
            return b;
           
        }


        /// <summary>
        /// 注册写入
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        [WebMethod]
        public int InserValue(string name, string pass, string email, string remrk)
        {
            int n = 0;
            string sql = "insert into [User](UserName,UserPass,UserEmail,Remark,AddTime)values('" + name + "','" + pass + "','" + email + "','" + remrk + "','" + DateTime.Now + "')";
            SqlCommand MyCommand = new SqlCommand(sql, myStr);
            try
            {
                myStr.Open();
                n = Convert.ToInt32(MyCommand.ExecuteNonQuery());
                myStr.Close();


            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }


            return n;
        }


        /// <summary>
        /// 查询账号
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        [WebMethod]
        public int GetCount(string name)
        {
            int n = 0;
            SqlCommand cmd = new SqlCommand(@"select count(*) from [User] where UserName='" + name + "'", myStr);
            try
            {
                myStr.Open();
                n = Convert.ToInt32(cmd.ExecuteScalar());
                myStr.Close();


            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
            }
            return n;
        }
    }
}

数据库:

名:user

字段:UserName,UserPass,UserEmail,Remark,AddTime

这里例子我只做了访问hello world,将java中:MethodName改成asmx中的方法名称,如果返回的是web中的返回值,说明远程访问已经成功。

最后,在libs目录下导入ksoap2-android-assembly-2.4-jar-with-dependencies.jar包,没有libs创建一个,要吧jar包copy进去,不要导进去,导进去有时候不行

注意:在本机发布到IIS中时,访问必须在同一网段,并且关闭本机防火墙。防火墙关闭方法:控制面板--》windows防火墙--》打开或关闭windows防火墙

希望对菜鸟们有用,在远程获取数据时,不可用主线程去操作,要新建一个线程去处理,这里建议看看线程的运行原理和顺序

后期的删除等,我会更新上去,不过这些原理都是一样的,只要懂的增删改查都行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值