MAUI安卓应用无法连接SQL Server问题排查求助
我正在使用Visual Studio 2022、MAUI和.NET 8.0开发安卓及Windows桌面测试应用,采用SQL Server 2022作为数据库,数据库与桌面应用部署在同一局域网PC上,安卓应用通过Wi-Fi连接数据库。Windows端应用可正常连接SQL Server并执行DML语句,但在Android模拟器(Pixel 5 - API 30)运行时,打开连接时报错:
建立与SQL Server的连接时发生与网络相关或特定于实例的错误。找不到服务器或无法访问服务器。请验证实例名称是否正确,并且SQL Server配置为允许远程连接。(provider: TCP Provider, error: 26 - Error Locating Server/Instance Specified)
以下是XAML页面中用于添加新记录的按钮点击事件代码:
private async void btnSave_Clicked(object sender, EventArgs e) { try { string connectionString = @"Data Source=SANDEEP-PC\SQL_SANDEEP;Initial Catalog=TestDB;Integrated Security=True;Pooling=False;Trust Server Certificate=True"; SqlConnection cn = new SqlConnection(connectionString); SqlCommand cmd = cn.CreateCommand(); cmd.CommandText = $"INSERT INTO Users (UserID, UserName, UserPwd) VALUES ({txtUserId.Text},'{txtUserName.Text}','{txtUserPassword.Text}')"; cn.Open(); int i = cmd.ExecuteNonQuery(); cn.Close(); CancellationTokenSource cts = new CancellationTokenSource(); var toast = Toast.Make($"{i.ToString()} User Saved", ToastDuration.Short, 20); await toast.Show(cts.Token); txtUserId.Text = txtUserName.Text = txtUserPassword.Text = null; txtUserId.Focus(); } catch (Exception ex) { await DisplayAlert("Error..", ex.Message, "OK"); } }
我已检查SQL Server属性→连接→远程服务器连接,“Allow remote connections to this server”选项已勾选,请问是什么原因导致无法连接?
从你的场景来看,主要有几个核心原因会导致Android模拟器无法连接局域网内的SQL Server,逐一排查:
1. 模拟器网络无法识别主机名称
Android模拟器默认使用虚拟网络,无法直接解析主机的局域网名称(如SANDEEP-PC),需要:
- 将连接字符串中的主机名替换为主机的局域网IP地址(比如
192.168.x.x),同时指定SQL Server的TCP端口(默认1433),修改后的示例:Data Source=192.168.1.100,1433;Initial Catalog=TestDB;Integrated Security=True;Pooling=False;Trust Server Certificate=True - 若使用的是命名实例(SQL_SANDEEP),需通过SQL Server配置管理器确认该实例的TCP端口(不一定是1433)。
2. SQL Server TCP/IP协议未启用
即使开启了远程连接,若TCP/IP协议未启用,模拟器仍无法建立连接:
- 打开SQL Server配置管理器,找到
SQL Server网络配置→SQL_SANDEEP的协议,确保TCP/IP状态为启用。 - 双击TCP/IP,在
IP地址标签页的IPAll节点,确认TCP端口设置,同时将所有IP地址的已启用设为是。
3. Windows防火墙拦截端口请求
主机的Windows防火墙可能拦截了SQL Server的端口访问:
- 打开Windows Defender防火墙,添加入站规则,允许TCP端口1433(或你的实例自定义端口)的访问。
- 可临时关闭防火墙测试,确认是否为防火墙导致的问题。
4. 集成身份验证不支持Android平台
Android系统无法识别Windows的Integrated Security=True(NTLM/Kerberos身份验证),这是关键问题:
- 改用SQL Server身份验证:在SQL Server中创建一个SQL登录账号(如
testuser),修改连接字符串:Data Source=192.168.1.100,1433;Initial Catalog=TestDB;User ID=testuser;Password=yourpassword;Pooling=False;Trust Server Certificate=True - 确保该SQL账号拥有TestDB数据库的读写权限。
5. 代码SQL注入风险提示(额外优化)
你的代码直接拼接用户输入到SQL语句中,存在严重的SQL注入风险,建议改用参数化查询:
cmd.CommandText = "INSERT INTO Users (UserID, UserName, UserPwd) VALUES (@UserID, @UserName, @UserPwd)"; cmd.Parameters.AddWithValue("@UserID", txtUserId.Text); cmd.Parameters.AddWithValue("@UserName", txtUserName.Text); cmd.Parameters.AddWithValue("@UserPwd", txtUserPassword.Text);
内容的提问来源于stack exchange,提问作者sandeep jakhotya

