从网上有看到,在Xamarin下连接操作数据库的各个方法如下:
1.直接操作 类似于C#中操作数据中的方法,不作详细说明。然愚在实测过程中总会有各种问题,目前此咱仍未完全走通。
2.借助于JTDS 也未完全走通,在实测过程中会出现报错。
3.借助于WebService 此可以完全实现。
开发环境:
VS2017 Xamarin SQLSever2012
APP测试环境:
蓝叠4.1
webservice的建立步骤
1.新建一个Web应用程序,填入一个你需要的项目名称,然后确定。

2.选择空模板,然后点击确定。

3.右键项目名称,添加一个新建项。

4.然后选择web服务(ASMX),并填写上你想要的名称,然后确定。

5.进入代码区后(如下紫色框,其为一个WebMethod;红色框中可以修改为你想要的),写入你需要的WebMethod.

6.下为一些简单的WebMethod,仅作参考。
string connstring = @"server=yourserver;database=TEST2;uid=yourID;pwd=yourPassWord";
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod(Description ="查询")]
public DataSet query()
{
DataSet ds = new DataSet();
SqlConnection mycn = new SqlConnection(connstring);
mycn.Open();
SqlDataAdapter mda = new SqlDataAdapter("select * from apptest", mycn);
mda.Fill(ds, "InsDtt");
int i = ds.Tables[0].Rows.Count;
string str = ds.Tables[0].Rows[0][2].ToString();
return ds;
}
[WebMethod(Description = "参数查询")]
public DataTable quertable(int id) {
DataTable dt = new DataTable(); ;
dt.TableName ="test";
SqlConnection conn = new SqlConnection(connstring);
conn.Open();
string sql = "select * from apptest where ID=@id";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter IntId = new SqlParameter("@id", id);
cmd.Parameters.Add(IntId);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
return dt;
}
[WebMethod(Description = "增加")]
public int InsertData(int id,string Num ) {
SqlConnection conn = new SqlConnection(connstring);
conn.Open();
string sql = "insert into apptest(ID,Num) values(@ID,@Num)";
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter d = new SqlParameter("@ID", id);
cmd.Parameters.Add(d);
SqlParameter n = new SqlParameter("@Num", Num);
cmd.Parameters.Add(n);
int result = cmd.ExecuteNonQuery();
conn.Close();
cmd.Dispose();
return result;
}
7.调试OK后,需要发布你的WebService,其步骤如下。
7.1右键方案名称,找到发布后点击

7.2 首次发布的话,进入后如下图,一般选择文件夹,并在右侧设置其存储路径(请选择文件夹位置),然后点击发布即可。

7.3 最后在IIS中,添加一个应用,并设置其别名(Alice)与物理路径后确定。


8.然后在刚刚的应用中,查看其内容(Content),找到asmx文件,右键后点击Browse(浏览)。

其在浏览器中如下图,记住其浏览器中的地址,后续在你的Xamarin中需要引用它。

Xamarin中引用WebService步骤
1.右键引用,添加Web引用。

2.填写上URL,点击 右侧的 箭头,然后在左下角就能看到你刚才发布的webService,然后在Web引用名中填上你希望的名称,再点击添加引用。

3.添加引用后如下,在引用下方会出现一个WebReference文件夹,文件夹内会有你刚刚添加的webService.

4.在Xamarin中引用如下(myWebService为下图中右侧引用中名称,myService为WebService网页名;另若有必要可以用webservice.url="your webservice url"指定一下你的webservice的网络地址),然后在下方的代码(紫色框中)中即可使用webService上的方法了(因愚webService上QueryTable返回值是一个DataTable,故需用DataTable接收)。

废话这么多,只为记录整个过程,也许对其他人在使用xamarin时会有一定帮助吧,那是最好不过。
|