天天看点

Xamarin开发 Android App连接SQL Server数据库完整代码以及System.NotSupportedException,Encoding 936的异常处理

Xamarin开发 Android App连接SQL Server数据库

    • 前言
    • 数据库准备
    • 布局准备
    • 权限开启
    • 绑定布局控件
    • 数据库连接
    • 调试
    • System.NotSupportedException,Encoding 936异常处理
    • 小结
    • 代码区

前言

本人在校学生,刚接触到c#开发没多久,随着所学内容增加,渐微察觉大脑不够用,所以开通博客,一来整理学习所得,二来交流分享。小白一个,对于程序开发应用理解有很大不足,对于代码或如有引用不当之处,可以提出改正。今天整理的是Xamarin开发 Android App连接SQL Server数据库完整代码以及System.NotSupportedException,Encoding 936的异常处理,分享记录一下。

数据库准备

我使用的是SQL server 2008版本,我这里数据库随便建立了一个,对于数据库数据表的建立没有难度,所以直接贴图。这是记录演示,内容不重要hhhh~~

Xamarin开发 Android App连接SQL Server数据库完整代码以及System.NotSupportedException,Encoding 936的异常处理

布局准备

如下图所示:

Xamarin开发 Android App连接SQL Server数据库完整代码以及System.NotSupportedException,Encoding 936的异常处理

按照上图,布局内有4个TextView,2个button,3个TextInputEditText,也就是输入条。作用功能实现:

4个TextView分别显示数据库连接后的信息;2个button分别读取不同的数据表;3个TextInputEditText,较大的TextInputEditText提供异常处理中的异常信息,以及显示数据库数据,后边两个是对于CONNECTION1的查询数据库连接字符串,以及查询添加的输入。布局代码如下;

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
	<LinearLayout
		android:orientation="vertical"
		android:minWidth="25px"
		android:minHeight="25px"
		android:layout_width="match_parent"
		android:layout_height="match_parent"
		android:id="@+id/linearLayout1">
		<TextView
			android:text="data1"
			android:layout_width="match_parent"
			android:layout_height="24.0dp"
			android:layout_marginTop="7.5dp"
			android:id="@+id/datatextView1"/>
		<TextView
			android:text="data2"
			android:layout_width="match_parent"
			android:layout_height="24.0dp"
			android:layout_marginTop="7.5dp"
			android:id="@+id/datatextView2" />
		<TextView
			android:text="data3"
			android:layout_width="match_parent"
			android:layout_height="24.0dp"
			android:layout_marginTop="7.5dp"
			android:id="@+id/datatextView3" />
		<TextView
			android:text="data4"
			android:layout_width="match_parent"
			android:layout_height="24.0dp"
			android:layout_marginTop="7.5dp"
			android:id="@+id/datatextView4" />
		<android.support.design.widget.TextInputEditText
			android:layout_width="match_parent"
			android:layout_height="188.0dp"
			android:id="@+id/datatextView5" />
		<Button
			android:text="connection1"
			android:layout_width="141.5dp"
			android:layout_height="43.0dp"
			android:id="@+id/databutton1"
			android:layout_marginTop="15.0dp" />
		<android.support.design.widget.TextInputEditText
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:id="@+id/datatextInputEditText1"
			android:layout_marginTop="10.0dp" />
		<android.support.design.widget.TextInputEditText
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:id="@+id/datatextInputEditText2"
			android:layout_marginTop="8.5dp" />
		<Button
			android:text="connection2"
			android:layout_width="158.5dp"
			android:layout_height="50.0dp"
			android:id="@+id/databutton2" />
	</LinearLayout>

</LinearLayout>
           

权限开启

在资源管理器中单击项目,选择属性,在出现的安卓选项中程序清单列表下,开启网络连接权限。具体操作在网上很多这里就不在赘述惹。。

绑定布局控件

在完成上述操作后就可以在执行代码里绑定控件了:

class Media : AppCompatActivity
    {
        Button Bt1,Bt2;
        TextView Tv1, Tv2, Tv3, Tv4, Tv5;
        TextInputEditText textInputEditText1, textInputEditText2;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.media);
            Bt1 = FindViewById<Button>(Resource.Id.databutton1);
            Bt2 = FindViewById<Button>(Resource.Id.databutton2);
            textInputEditText1 = FindViewById<TextInputEditText>(Resource.Id.datatextInputEditText1);
            textInputEditText2 = FindViewById<TextInputEditText>(Resource.Id.datatextInputEditText2);
            Tv1 = FindViewById<TextView>(Resource.Id.datatextView1);
            Tv2 = FindViewById<TextView>(Resource.Id.datatextView2);
            Tv3 = FindViewById<TextView>(Resource.Id.datatextView3);
            Tv4 = FindViewById<TextView>(Resource.Id.datatextView4);
            Tv5 = FindViewById<TextView>(Resource.Id.datatextView5);
            Bt1.Click += Bt1_Click;
            Bt2.Click += Bt2_Click;
            textInputEditText1.Text = "2016100477";
            textInputEditText2.Text = "192.168.23.1";
        }
      }
           

数据库连接

数据库的连接和C#窗体程序开发步骤类似。首先,创建数据库连接,使用数据库连接字符串,使用SqlConnection对象创建数据库连接,打开数据库。

string s = "Server=/*主机名或主机IP地址*/;Database=net;User ID=sa;Password=/*此处为数据库连接密码*/";
 SqlConnection mycon = new SqlConnection(s);
 mycon.Open();
           

接下来是使用数据库命令语句操作数据库,使用SqlCommand对象执行SQL语句。其中SqlCommand对象后面两个参数“sql, mycon”,sql为SQL语句、表或存储过程,mycon为一个SqlConnection对象,它表示SQL Server的实例连接。

string sql = "select account,姓名,性别,工作证号 from [manager login] where account ='" + textInputEditText1.Text.Trim() + "'";
//account,姓名,性别,工作证号分别是对于数据库的列,[manager login]是表名
SqlCommand com = new SqlCommand(sql, mycon);
           

再接下来使用DataReader对象从数据库检索只读、只向前进的数据流。这里使用DataReader的Read()方法逐行读取数据。

SqlDataReader read = com.ExecuteReader();
while (read.Read())
 {
   Tv1.Text = "您好,管理员:";
   string s1 = read["姓名"].ToString();
   Tv2.Text = "姓名: " + s1;
   string s2 = read["性别"].ToString();
   Tv3.Text = "性别: " + s2 ;
   string s3 = read["工作证号"].ToString();
   Tv4.Text = "工作证号: " + s3 ;
  }
           

调试

Xamarin开发 Android App连接SQL Server数据库完整代码以及System.NotSupportedException,Encoding 936的异常处理

System.NotSupportedException,Encoding 936异常处理

在之前的调试过程中反复出现:

Encoding 936 data could not be found. Make sure you have correct international codeset assembly installed and enabled.

我以为是数据库连接字符串有问题,后面通过异常处理,在加百度各种折腾后发现:出现这样的问题是因为在引用中没有启用可识别的国际代码集程序集。只要在引用中右击,出现添加引用,将下面的几个代码集打钩添加即可。

Xamarin开发 Android App连接SQL Server数据库完整代码以及System.NotSupportedException,Encoding 936的异常处理

小结

因为Encoding 936 的原因,折腾了我一整个下午加一个晚上,其实它的连接和C#无异。目前这种连接只能在手机网络与电脑网络在同一个局域网的条件下使用,我使用的是校园网。虽然是初学,但是凭自己努力攻克一个小难题,我还是感觉很开心的哈哈哈。

补充一下:为了资源能够更好利用,在所有连接对象使用完一次后,应该尽快关闭。

read.Close();

mycon.Close();

mycon.Dispose();

代码区

using System;
using System.Data.SqlClient;
using System.IO;
using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Widget;
using Android.Support.Design.Widget;
using System.Data;
using Mono.Data.Sqlite;
using Mono.Data.Tds;

namespace Shutao
{
    [Activity(Label = "@string/media_name", Theme = "@style/AppTheme")]
    class Media : AppCompatActivity
    {
        Button Bt1,Bt2;
        TextView Tv1, Tv2, Tv3, Tv4, Tv5;
        TextInputEditText textInputEditText1, textInputEditText2;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.media);
            Bt1 = FindViewById<Button>(Resource.Id.databutton1);
            Bt2 = FindViewById<Button>(Resource.Id.databutton2);
            textInputEditText1 = FindViewById<TextInputEditText>(Resource.Id.datatextInputEditText1);
            textInputEditText2 = FindViewById<TextInputEditText>(Resource.Id.datatextInputEditText2);
            Tv1 = FindViewById<TextView>(Resource.Id.datatextView1);
            Tv2 = FindViewById<TextView>(Resource.Id.datatextView2);
            Tv3 = FindViewById<TextView>(Resource.Id.datatextView3);
            Tv4 = FindViewById<TextView>(Resource.Id.datatextView4);
            Tv5 = FindViewById<TextView>(Resource.Id.datatextView5);
            Bt1.Click += Bt1_Click;
            Bt2.Click += Bt2_Click;
            textInputEditText1.Text = "2016100477";
            textInputEditText2.Text = "192.168.23.1";
        }
        private void Bt2_Click(object sender, EventArgs e)
        {
            try
            {
            string s = "server="+ textInputEditText2.Text.Trim() + ";database=BMS;uid=sa;pwd=17379011996";
            SqlConnection mycon = new SqlConnection(s);
            mycon.Open();
            string sql = "select account,姓名,性别,工作证号 from [manager login] where account ='" + textInputEditText1.Text.Trim() + "'";
            SqlCommand com = new SqlCommand(sql, mycon);
            SqlDataReader read = com.ExecuteReader();
            while (read.Read())
            {
                Tv1.Text = "您好,管理员:";
                string s1 = read["姓名"].ToString();
                Tv2.Text = "姓名: " + s1;
                string s2 = read["性别"].ToString();
                Tv3.Text = "性别: " + s2 ;
                string s3 = read["工作证号"].ToString();
                Tv4.Text = "工作证号: " + s3 ;
            }
            read.Close();
            mycon.Close();
            mycon.Dispose();
            }
            catch (Exception excption) { Tv5.Text = excption.ToString(); }
        }
        private void Bt1_Click(object sender, EventArgs e)
        {
            try
            {
                string s = "Server=" + textInputEditText2.Text.Trim() + ";Database=net;User ID=sa;Password=17379011996";
                SqlConnection mycon = new SqlConnection(s);
                mycon.Open();
                string sql = "select title,fangwen from jilu";
                SqlCommand com = new SqlCommand(sql, mycon);
                SqlDataReader read = com.ExecuteReader();
                Tv5.Text = "  title\t\tfangwen\t\n";
            while (read.Read())
            {
                    Tv5.Text += string.Format("  {0}\t\t{1}",
                    read[0].ToString(),
                    read[1].ToString());
                }
                read.Close();
                mycon.Close();
                mycon.Dispose();
            }
            catch (Exception excption) { Tv5.Text = excption.ToString(); }
        }
    }
}
           

继续阅读