• 0

[ASP] - Problem with connection string


Question

Heya all

I have a website that has been fully developed in asp. The website is database driven (sql) and is working fine. The website has a search feature that works fine however we are looking to re-build it to make it more user friendly. Not being very good at asp i am begining my experimentation with connecting to the database however it does not want to play ball.

I am using the following ConnectionString

ConnString="Driver={SQL Server};Server=server\server;Database=databasename;Uid=server\Administrator;Pwd=ourpassword;"

Obviously the various areas in the string are filled in properly as best i know (we were never provided with the full details) but i am getting the following message / error when i run the page.

Microsoft OLE DB Provider for ODBC Drivers error '80040e4d'

[Microsoft][ODBC SQL Server Driver]

Login failed for user 'server\Administrator'.

/connect7.asp, line 19

After getting this message i done some research and many people are saying that the user does not have access to the sql database or something like that however the developed website is working without any problems and it must be connecting somehow.

The questions i have are:

  1. Am i doing something stupid and is there a simple solution i have missed?
  2. If i am not doing something stupid how do the current pages connect to the database?

I am looking forward to any replies. Thanks in advance :)

Ludz~

Link to comment
https://www.neowin.net/forum/topic/649621-asp-problem-with-connection-string/
Share on other sites

17 answers to this question

Recommended Posts

  • 0

Antaris, Thank you

I have managed to create a connection and extract the information via a .asp page. After doing so i realise it would be a better idea to use .aspx (asp.net) in the long run however i am having issues finding some code examples to help me through. Im looking for something that connects to the database, and lists all information from a specific table, maybe using a repeater from what im reading.

Anyone have any ideas or examples i could use?

Ludz~

  • 0

Update: Below i have provided the asp code i use to connect to the our current database and extract the information. What i would like is a replication of this that works with asp.net (.aspx). If anyone could point me in the right direction or provide some code snipets for me it would be a great help.

<%

'declare the variables

Dim Connection

Dim ConnString

Dim Recordset

Dim SQL

'define the connection string, specify database driver

ConnString="connection string code removed"

'declare the SQL statement that will query the database

SQL = "SELECT * FROM AllJobs"

'create an instance of the ADO connection and recordset objects

Set Connection = Server.CreateObject("ADODB.Connection")

Set Recordset = Server.CreateObject("ADODB.Recordset")

'Open the connection to the database

Connection.Open ConnString

'Open the recordset object executing the SQL statement and return records

Recordset.Open SQL,Connection

'first of all determine whether there are any records

If Recordset.EOF Then

Response.Write("No records returned.")

Else

'if there are records then loop through the fields

Do While NOT Recordset.Eof

Response.write Recordset("JobID")

Response.write "<br>"

Response.write Recordset("UserID")

Response.write "<br>"

Response.write Recordset("Title")

Response.write "<br>"

Response.write Recordset("PostedDate")

Response.write "<br>"

Response.write Recordset("LastUpdated")

Response.write "<br>"

Response.write Recordset("ValidTo")

Response.write "<br>"

Response.write Recordset("Description")

Response.write "<br>"

Response.write Recordset("CountryID")

Response.write "<br>"

Response.write Recordset("Location")

Response.write "<br>"

Response.write Recordset("ExperienceID")

Response.write "<br>"

Response.write Recordset("NoOfVaccancies")

Response.write "<br>"

Response.write Recordset("JobTypeID")

Response.write "<br>"

Response.write Recordset("JobRoleID")

Response.write "<br>"

Response.write Recordset("JobDurationID")

Response.write "<br>"

Response.write Recordset("SalaryTypeID")

Response.write "<br>"

Response.write Recordset("MinimumEducationID")

Response.write "<br>"

Response.write Recordset("ActiveFlag")

Response.write "<br>"

Response.write Recordset("Validity")

Response.write "<br>"

Response.write Recordset("HotJob")

Response.write "<br>"

Response.write "<br>"

Recordset.MoveNext

Loop

End If

'close the connection and recordset objects to free up resources

Recordset.Close

Set Recordset=nothing

Connection.Close

Set Connection=nothing

%>

Ludz~

  • 0

Ad

I am generaly using notepad to develop the files, is there something you would reccomend to make it easier? Also as far as the connection to the database i like to work from a flat file to begin with so i can keep all the errors / issues in one place. As i said earlier parts of the site are already working and the parts i am re-making i would to keep seperate until completed.

So any ideas?

Ludz~

  • 0

This is how I generally prepare connection strings in ASP.NET:

&lt;appSettings&gt;
	&lt;add name="SqlServer" value="Development" /&gt;
&lt;/appSettings&gt;
&lt;connectionStrings&gt;
	&lt;add name="Development" providerName="SqlClient" connectionString="DEVELOPMENT_SERVER_CONNECTION_STRING"/&gt;
	&lt;add name="Production" providerName="SqlClient" connectionString="PRODUCTION_SERVER_CONNECTION_STRING"/&gt;
&lt;/connectionStrings&gt;

public SqlConnection GetConnection()
{
	string server = WebConfigurationManager.AppSettings["SqlServer"];
	string connection = WebConfigurationManager.ConnectionStrings[server].ConnectionString;

	SqlConnection conn = new SqlConnection(connection);
	return conn;
}

public DataSet GetSomeDataFromServer()
{
	using (SqlCommand command = new SqlCommand("TABLE/VIEW/PROCEDURE", conn))
	{
		SqlDataAdapter adapter = new SqlDataAdapter(command);
		DataSet data = new DataSet(); adapter.Fill(data);

		return data;
	}
}

Your choice in .NET control varies, depending on the level control you want. Although you can use DataGrids, I prefer to do the construction manually through Repeaters, e.g.:

&lt;asp:Repeater ID="repeat_Data" runat="server"&gt;
	&lt;ItemTemplate&gt;
		&lt;asp:Literal ID="lit_Name" runat="server" Text='&lt;%# Bind("FIELD_FROM_DATASET") %&gt;' /&gt;
	&lt;/ItemTemplate&gt;
&lt;/asp:Repeater&gt;

public void Page_Load(object sender, EventArgs e)
{
	DataSet data = GetSomeDataFromServer();
	repeat_Data.DataSource = data;
	repeat_Data.DataBind();
}

This of course is my personal preference, a lot of people enjoy the fidelity you get from using the VS designer to manage all of this.

I did this as a C# example, because (although I know VB.NET), I prefer C# :p

  • 0

Ant

Thanks again for the information however is there any chance you could post the code for one full .aspx page that connects to the database at the top and displays information from the database that is being connected to? I am trying to use the code snippets you have provided but do not seem to be having much luck.

A full working page would be a great help

Ludz~

  • 0

Ant

I have been playing with the pages and code you sent over however i am having real issues getting it working. The server already has a website as stated before and the web.config file must be different to the one you provided as i cannot make it work.

Is there anyway to do this in one flat file? Just one file that connects to the database at the top, runs an sql query and then displays the results of that on the page? All being done in asp.net (.aspx)? Please tell me there is a way..

Any help is much apreciated and an example page would be a great help if its possible.

Ludz~

  • 0

&lt;%@ Page Language="C#" %&gt;

&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

&lt;script runat="server"&gt;
	protected void Page_Load(object sender, EventArgs e)
	{
		string connection = "&lt;connection string here&gt;";
		System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connection);
		conn.Open();

		using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand("SELECT * FROM AllJobs", conn))
		{
			System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter(command);
			System.Data.DataSet data = new System.Data.DataSet(); adapter.Fill(data);

			repeat_Data.DataSource = data;
			repeat_Data.DataBind();
		}

		conn.Close();
	}
&lt;/script&gt;

&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head runat="server"&gt;
	&lt;title&gt;Untitled Page&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
	&lt;form id="form1" runat="server"&gt;
	&lt;div&gt;
		&lt;asp:Repeater ID="repeat_Data" runat="server"&gt;
			&lt;ItemTemplate&gt;
				&lt;asp:Literal ID="lit_Title" runat="server" Text='&lt;%# Bind("Title") %&gt;' /&gt;
			&lt;/ItemTemplate&gt;
		&lt;/asp:Repeater&gt;
	&lt;/div&gt;
	&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;

Many (including myself) feel its bad design and bad practice to code pages like this. Seperating code from presentation is a key goal you will come to realise ;)

  • 0

Thank you for the code Ant it has been a great help. However guess what! I have run into another little hitch....

For the connection string i have inputer the exact string used in the current web.config file so i figure that it is correct as it is powering the rest of the website. When i run the page however i get this error.

Compiler Error Message: CS1009: Unrecognized escape sequence

After looking up the error online it seemed it was caused by the "\" in the servername.

string connection = "Server=S15273662\S15273662;UID=....

So i changed it to..

string connection = "Server=S15273662;UID=....

In hope that it would work however it now throws a new error and when i look that up most people are saying that the error is because the connection string is wrong.

Am i displaying the server name wrong or is there something small i need to tweak to have it work? Or could it be something completly different?

Ludz~

  • 0

In C# (like many other C-like languages), it doesn't accept the slash '\' character on it's own, unless its an escaped string.

You can do 1 of 2 things:

string connection = "SERVER=&lt;servername&gt;\\&lt;instance&gt;;DATA...

or

string connection = @"SERVER=&lt;servername&gt;\&lt;instance&gt;;DATA...

  • 0

This is slightly off topic but related to some posted code.

Antaris, as far as this example is concerned, why are you using a DataAdapter/DataSet instead of just a DataReader which is much faster and requires much less overhead for a read-only scenario.

&lt;%@ Page Language="C#" %&gt;

&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;

&lt;script runat="server"&gt;
	protected void Page_Load(object sender, EventArgs e) {

		using (SqlConnection Conn = new SqlConnection(&lt;connection string here&gt;)) {
			using (SqlCommand Cmd = new SqlCommand("SELECT Title FROM AllJobs", Conn)) {
				Conn.Open();
				repeat_Data.DataSource = Cmd.ExecuteReader();
				repeat_Data.DataBind();
			} //end using sqlcommand
		} //end using sqlconnection

	}

&lt;/script&gt;

&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head runat="server"&gt;
	&lt;title&gt;DataReader&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
	&lt;form id="form1" runat="server"&gt;
	&lt;div&gt;
		&lt;asp:Repeater ID="repeat_Data" runat="server"&gt;
			&lt;ItemTemplate&gt;
				&lt;%# Eval("Title") %&gt;&lt;br /&gt;
			&lt;/ItemTemplate&gt;
		&lt;/asp:Repeater&gt;
	&lt;/div&gt;
	&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;

  • 0

Okey dokey. I figured as much, but wanted to ask.

For the OP... Using the DataReader for read-only parts of large applications makes a HUGE difference in page load times, especially when binding data to multiple bound controls in a page. You'll also want to steer away from "SELECT * FROM..." statements if you're actually using the data being returned from the database for similar reasons.

  • 0

Ant

Thanks for the help mate it has worked perfectly, now that i have a foundation i can see without getting a load of errors i hope i can construct the rest of the page myself. It has given me a great boost, Thanks again.

Josh

Thanks for the advice, after i get something together that i am happy with i will work on optimizing it.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Microsoft finally admits its default Windows 11 25H2, 24H2 action broke key legacy component by Sayan Sen Microsoft last week released Windows 11 KB5094126 and KB5093998 as the latest Patch Tuesday updates. Following that the company also published the accompanying dynamic updates under KB5094149, KB5095971, and KB5094156. So far the company has acknowledged two known issues that have popped up after the release which include bugged-out Office apps as well as the Recycle Bin; though there could be more at play too. Speaking of bugs and issues, Microsoft seems to have finally acknowledged a problem that probably has been around for close to a year. That's because back in July of 2025 the company made a default change to the latest Windows 11 versions, wherein it switched to JScript9Legacy on Windows 11 24H2 and later releases. Hence following the release of version 25H2 in October 2025, JScript9Legacy also remained default-enabled. As a result there has been a compatibility issue ever since then. For those wondering, by switching to JScript9Legacy Microsoft intended to improve the security of modern Windows PCs by reducing vulnerabilities tied to legacy scripting like cross-site scripting (XSS), among others. XSS exploits can allow cyber-attackers to attach malicious code onto legitimate websites and use them to execute the code when a potential victim loads such a website. Hence the new JScript9Legacy engine enforced stricter execution policies and improved object handling, which should help mitigate such attacks. Microsoft today has published a new support article detailing the problem. Neowin spotted it while browsing. The company says that JScript global definitions and execution context may fail to persist across scripts, potentially breaking older dependent apps and web-based components that relied on this legacy behavior. In the article Microsoft has confirmed that the issue stems from its move away from the older jscript9.dll engine in favor of jscript9legacy.dll. As mentioned above, while the newer engine was designed to address vulnerabilities and strengthen security it also changes how JScript handles execution context. As a result functions and definitions loaded by one script could no longer remain available to subsequent scripts once execution ended. The company notes that some applications worked correctly on earlier Windows versions because the older JScript engine automatically retained global definitions and execution state between scripts. Under the newer model though that behavior is disabled by default causing certain legacy workloads and polyfill-dependent scripts to fail. Microsoft says it addressed the problem via the KB5077241 update though the fix had not been enabled automatically in the following updates. As such admins must explicitly turn on persistent JScript execution context using a Registry setting that the tech giant shared today. The configuration can be applied to individual processes or system-wide through the FEATURE_ENABLE_PERSISTENCE registry key. The steps have been outlined below: Run the following command to create the feature control registry key: reg add "HKLM\Software\Policies\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_ENABLE_PERSISTENCE" Under this key, create a new DWORD (32-bit) value. Configure the value as follows: To enable persistence for specific processes only: Set the value to 1 for each target process name. To enable persistence for all processes: Add * as the key name and set its value to 1. You can find the official support article here on Microsoft's website.
    • The possibility that milk gathers back into a glass implies that gravity can be 'reversed'.
    • VidCoder 12.20 by Razvan Serea  VidCoder is a DVD/Blu-ray ripping and video transcoding application for Windows. It uses HandBrake as its encoding engine. Calling directly into the HandBrake library gives it a more rich UI than the official HandBrake Windows GUI. VidCoder can rip DVDs but does not defeat the CSS encryption found in most commercial DVDs. You’ll need the NET 8 Desktop Runtime. If you don’t have it, VidCoder will prompt you to download and install it. The Portable version is self-contained and does not require any .NET Runtime to be installed. You do not need to install HandBrake for VidCoder to work. Feature list: Multi-threaded MP4, MKV containers Completely integrated encoding pipeline: everything is in one process and no huge intermediate temporary files H.264, H.265, MPEG-4, MPEG-2, VP8, Theora video Hardware-accelerated encoding with AMD VCE, Nvidia NVENC and Intel QuickSync AAC, MP3, Vorbis, AC3, FLAC audio encoding and AAC/AC3/MP3/DTS/DTS-HD passthrough Target bitrate, size or quality for video 2-pass encoding Decomb, detelecine, deinterlace, rotate, reflect, chroma smooth, colorspace filters Powerful batch encoding with simultaneous encodes Customizable Pickers to automatically pick audio and subtitle tracks, destination, titles and more Instant source previews Creates small encoded preview clips Pause, resume encoding VidCoder 12.20 changes: Updated HandBrake core to 1.11.2. Download: VidCoder 12.20 | 47.0 MB (Open Source) Download: Portable VidCoder 12.19 | 89.3 MB Link: VidCoder Home Page | Github | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Week One Done
      Jordan Smith earned a badge
      Week One Done
    • Reacting Well
      BizSAR earned a badge
      Reacting Well
    • First Post
      AndreaB earned a badge
      First Post
    • Week One Done
      Huge Trailer earned a badge
      Week One Done
    • Week One Done
      Classifyskilleducation earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      590
    2. 2
      +Edouard
      185
    3. 3
      PsYcHoKiLLa
      76
    4. 4
      Michael Scrip
      73
    5. 5
      Steven P.
      66
  • Tell a friend

    Love Neowin? Tell a friend!