Sunday, March 25, 2012

Accessing database

In a useless wrox press book I'm currently being tortured by there is the script below, it is suppose to simply open and close a connection to the northwind SQL Server 2000 database but it doesn't work:

<%@.Import namespace="System.Data"%>
<%@.Import namespace="System.Data.SqlClient"%>
<script runat="server" language="c#">
void Page_Load()
{
string strConnection = "user id=sa;password=;";
strConnection += "initial catalog=northwind;server=MIKE;";
strConnection += "Connect Timeout=30";

data_src.Text = strConnection;

SqlConnection objConnection = new SqlConnection(strConnection);

try
{
objConnection.Open();
con_open.Text = "Connection opened successfully.<br />";
objConnection.Close();
con_close.Text = "Connection closed <br />";
}
catch (Exception e)
{
con_open.Text = "Connection failed to open.<br />";
con_close.Text = e.ToString();
}
}
</script>
<html>
<body>
<h4>Testing the data connection <asp:label id="data_src" runat="server" /></h4>
<asp:label id="con_open" runat="server" /><br />
<asp:label id="con_close" runat="server" /><br />
</body>
</html
It returns the following error:

System.Data.SqlClient.SqlException: Login failed for user 'sa'. at System.Data.SqlClient.ConnectionPool.GetConnection(Boolean& isInTransaction) at System.Data.SqlClient.SqlConnectionPoolManager.GetPooledConnection(SqlConnectionString options, Boolean& isInTransaction) at System.Data.SqlClient.SqlConnection.Open() at ASP.sql_connection_aspx.Page_Load()

The book also states that if the script doesn't work we should try replacing the user id and password line with this line:

string strConnection = "Integrated Security=SSPI;";

But this doesn't work either. So needless to say I have no idea what's wrong, can anyone help as unfortunately the psychic powers Wrox Press clearly believe I possess aren't working. I have no idea whether this should work straight out like this or whether some configuration or something needed to be done first. I'm totally stuck, please help.

ThanksProbably the username and password for the database server you are trying to access is not valid. SqlServer defaults to a blank password for sa but generally that's one of the first things changed so that the server is more secure.

Is this on your own machine or is it remote? In either case you need to find a valid username and password for accessing the database. If you can get into Enterprise Manager, check in the Security section under Logins. Either use an existing one or create a new one. If it's a remote server then check with whomever is responsible for it.

No comments:

Post a Comment