1

I am trying to connect to Microsoft SQL Server on localhost. My code is as follows.

public SqlConnection con;

// To Handle connection related activities
private void connection()
{
    string constr = ConfigurationManager.ConnectionStrings["Data Source = MACHINE-VOIV7EH\\SQLEXPRESS; Initial Catalog = geolog; Persist Security Info = False; "].ToString();
    con = new SqlConnection(constr);
}

public List<Bob> GetAllBobs()
{
    try
    {
        connection();
        con.Open();

        IList<Bob> EmpList = SqlMapper.Query<Bob>(con, "GetBobs").ToList();
        con.Close();

        return EmpList.ToList();
    }
    catch (Exception)
    {
        throw;
    }
}

con return null

SQL Server settings:

enter image description here

Configuration from Pyton (try, but another database):

conn = pypyodbc.connect('DRIVER={SQL Server};'
                        r'SERVER=MACHINE-VOIV7EH\SQLEXPRESS;'
                        r'DATABASE=vibori;'
                        r' autocommit=True'
                        )

2 Answers 2

3

The Problem is with your connection string. You should reference your connection string from the web.config file.

Web.Config

<connectionStrings>
    <add name="master" providerName="System.Data.SqlClient" connectionString="Data Source=ACHINE-VOIV7EH\\SQLEXPRESS;Initial Catalog=geolog;Integrated Security=False;User Id=your_user_id;Password=xxxxxx;MultipleActiveResultSets=True" />
  </connectionStrings>

C# File

 SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["master"].ConnectionString);

Or you can just send a connection string as follows

private void connection()
{
   string constr = "Data Source=MACHINE-VOIV7EH\\SQLEXPRESS; Initial Catalog = geolog; Persist Security Info = False;";
   con = new SqlConnection(constr);
}
Sign up to request clarification or add additional context in comments.

Comments

1

The string index of ConfigurationManager.ConnectionStrings[string] is the connection name, not the connection string which is what it returns. Use your web configuration file (web.config) to add one or more named connection strings which can be returned by this indexer.

Example:

string constr = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString

and partial web.config content

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <connectionStrings>
    <add name="MyConnection" connectionString="Data Source=MACHINE-VOIV7EH\SQLEXPRESS;Initial Catalog=vibori" providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.