سؤال

I've recently found some very old server control code and need to up and running. The problem is I don't know how to connect it to the database. Below is the SQL connection:

  SqlConnection sqlConnection = new SqlConnection(this.Page.Application["AuctionDbase"].ToString());
        SqlCommand sqlCommand = new SqlCommand();
        StringBuilder stringBuilder = new StringBuilder();

My question is do I need a web.config file where it can grab the connection string? I've placed the database on a local SQL server but I don't know if that's the right approach. I've never worked with Server Controls before and trying to get this deployed has been difficult!

Thank you in advance!!

هل كانت مفيدة؟

المحلول

Are you looking at the code snippet and trying to locate where the existing connection string is? Judging by the code snippet, it doesn't look like it's in the web.config. If it was then i would expect a call to the ConfigurationManager, not Page.Application.

Search the code to see if "AuctionDbase" is being set anywhere. It's possible that it's being set in the global.asax file if you have one.

Another possibility is in the Project options under Settings.

نصائح أخرى

There are various ways of storing/retrieving connection details.

The connectionStrings element would be the most straightforward way to handle connection strings. The connectionStrings section is dedicated to connection strings and was introduced in .NET 2.0.

If the privacy of your connection credentials is of concern: you should use the connectionStrings section, as it can also be encrypted separately from any other settings.

In the Web.config file you can add:

<configuration>
  ...
  <configSections>
    <connectionStrings>
      <add name="connectionStringName" connectionString="Data Source=(local);Initial Catalog=DBNAME;User Id=XXX;Password=XXX;" providerName="System.Data.SqlClient" />
    </connectionStrings>
  <configSections>
  ...
<configuration>

for more information on connection strings you can learn more here: https://www.connectionstrings.com/sql-server/

and in your code you can get the connection string like this:

string connectionString = System.Configuration.ConfigurationManager.
    ConnectionStrings["connectionStringName"].ConnectionString;
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top