• 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

    • Why was it necessary to use AI to help write this article? Can we no longer do our own research or our own writing?
    • The auto industry really needs to update it's terminology so a software update isn't called a recall.
    • Anybody that thinks flying cars were possible are idiots. Everyone would basically need a pilot licence, can you imagine how insane and dangerous that would be, people can barely handle driving on land safely right now.
    • Microsoft Edge 149.0.4022.80 by Razvan Serea Microsoft Edge is a super fast and secure web browser from Microsoft. It works on almost any device, including PCs, iPhones and Androids. It keeps you safe online, protects your privacy, and lets you browse the web quickly. You can even use it on all your devices and keep your browsing history and favorites synced up. Built on the same technology as Chrome, Microsoft Edge has additional built-in features like Startup boost and Sleeping tabs, which boost your browsing experience with world class performance and speed that are optimized to work best with Windows. Microsoft Edge security and privacy features such as Microsoft Defender SmartScreen, Password Monitor, InPrivate search, and Kids Mode help keep you and your loved ones protected and secure online. Microsoft Edge has features to keep both you and your family protected. Enable content filters and access activity reports with your Microsoft Family Safety account and experience a kid-friendly web with Kids Mode. The new Microsoft Edge is now compatible with your favorite extensions, so it’s easy to personalize your browsing experience. Microsoft Edge 149.0.4022.80 changelog: Fixes Fixed an issue that prevented QR code generation from working. Feature updates Intune MAM Protected Downloads. The protected downloads feature for Intune MAM will now save downloaded files to the Documents > Microsoft Edge > Downloads folder in OneDrive. Extensions monitoring in the Edge management service. The Microsoft Edge management service now allows admins to gain visibility into extensions installed across their managed users. From the extensions monitoring page, admins can see which extensions have been installed as well as manage user requests for blocked extensions. For more information, see Microsoft Edge Extensions Monitoring. Validate Edge builds early with enterprise preview. Enterprise preview provides a simpler way for admins to flight pre-release Edge builds to their users. To reduce friction and bolster usage, users will receive pre-release builds directly inside of their Stable Edge application. Admins can allow users to easily opt-out of the preview experience, using built-in rollback to switch between their pre-release and stable channels with ease. Microsoft 365 admin center users can configure the feature, view their flighting population, and receive personalized recommendations all in one place. For more information, see Get started with Enterprise Preview in Microsoft Edge. Download: Microsoft Edge (64-bit) | 193.0 MB (Freeware) Download: Microsoft Edge (32-bit) | 170.0 MB Download: Microsoft Edge (ARM64) | 188.0 MB View: Microsoft Edge Website | Release History Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • The machines are starting to fight back any way they can.
  • Recent Achievements

    • Week One Done
      Eurosoft10 earned a badge
      Week One Done
    • One Month Later
      Eurosoft10 earned a badge
      One Month Later
    • One Year In
      Skeet Campbell earned a badge
      One Year In
    • One Month Later
      Sharbel earned a badge
      One Month Later
    • First Post
      BizSAR earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      598
    2. 2
      +Edouard
      189
    3. 3
      PsYcHoKiLLa
      78
    4. 4
      Michael Scrip
      76
    5. 5
      Steven P.
      69
  • Tell a friend

    Love Neowin? Tell a friend!