Android Question How to connect Android to MS SQL Server with instance

jatko

Member
Licensed User
Longtime User
I used the script from post https://www.b4x.com/android/forum/threads/connect-android-to-ms-sql-server-tutorial.13166/page-6
and I have a problem with connecting to MS SQL server instance.

The error is reported in line 12

using (SqlConnection cn = new SqlConnection("Server=localhost\insertgt; Database=something; User Id=someone; password=something"))

Script:

<%@ Page Language="C#"%>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
protected void Page_Load(object sender, EventArgs ec)
{
using (SqlConnection cn = new SqlConnection("Database=Test1; User Id=UserName; password=Password")) //change as needed
{
using (StreamReader sr = new StreamReader(Request.InputStream, Encoding.UTF8))
{
Response.ContentType = "text/plain";
string c;
c = Request.QueryString["query"]; //for debugging with the browser
//you can set the query by adding the query parameter For ex: http://127.0.0.1/test.aspx?query=select * from table1
if (c == null)
c = sr.ReadToEnd();
try
{
SqlCommand cmd = new SqlCommand(c, cn);
cn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
while (rdr.Read())
{
Dictionary<string, object> d = new Dictionary<string, object>(rdr.FieldCount);
for (int i =0;i < rdr.FieldCount;i++)
{
d[rdr.GetName(i)] = rdr.GetValue(i);
}
list.Add(d);
}
JavaScriptSerializer j = new JavaScriptSerializer();
Response.Write(j.Serialize(list.ToArray()));

} catch (Exception e)
{
Response.TrySkipIisCustomErrors = true;
Response.StatusCode = 500;
Response.Write("Error occurred. Query=" + c + "\n");
Response.Write(e.ToString());

}
Response.End();
}
}
}
</script>
 

OliverA

Expert
Licensed User
Longtime User
Server=localhost\insertgt
I think that needs to be
Server=localhost\\insertgt
. See documentation here (https://msdn.microsoft.com/en-us/li...sqlconnection.connectionstring(v=vs.110).aspx), where it states:
Beginning in .NET Framework 4.5, you can also connect to a LocalDB database as follows:
server=(localdb)\\myInstance

PS: Next time use code tags to display the code.
PPS: Technically has zilch to do with connecting Android to MS SQL. You're connecting ASP to MS SQL - just saying.
 
Upvote 0

jatko

Member
Licensed User
Longtime User
the solution was a little different, but thank You very much for good direction

B4X:
using (SqlConnection cn = new SqlConnection("Data Source=.\\insertgt;Initial Catalog=database;User ID=user;Password=password"))
 
Upvote 0
Top