使用Xamarin无法连接Sqlserver,try-catch捕获错误【Snix_Connect (provider: SNI_PN7, error: 40 - SNI_ERROR_40)】,无前人指点,毕竟用C#开发安卓真是少见。各方查找,头疼的问题总算解决好了,赶紧记录一波。
1.启用TCP/IP
2.启用所有TCP/IP地址
双击上图红框中的TCP/IP,进入设置属性。点击IP地址,把所有地址都启用。
3.重启服务
4.检查连接字符串
在安卓里要使用10.0.2.2来访问你的本地主机,可别使用localhost,端口和ip之间用逗号隔开,而不是冒号。
附上一段代码希望能帮到你
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace App1.Model
{
public class GoodsService
{
string sqlserver_connstr = "Server=10.0.2.2,1433;Database=fl_goods;uid=sa;Password=123;";//pooling=false;
public void test() {
//安卓连接数据库属于耗时操作,不能在主线程操作
Task task = new Task(() =>
{
try {
SqlConnection mycon = new SqlConnection(sqlserver_connstr);
mycon.Open();
string sql = "select * from users";
SqlCommand com = new SqlCommand(sql, mycon);
SqlDataReader read = com.ExecuteReader();
while (read.Read())
{
string s1 = read["username"].ToString();
string s2 = read["sex"].ToString();
string s3 = read["age"].ToString();
}
read.Close();
mycon.Close();
mycon.Dispose();
}catch (Exception err) {
string errmsg = err.Message;
}
});
task.Start();
}
}
}
5.希望你别犯这种低级错误