The following ASP.NET database program based on the "pubs" database. If you dont have the pubs database on your SQL server please follow the url.
http://www.codeproject.com/KB/database/InstallingNorthwindAndPub.aspx
After you setup the pubs database on your SQL server , you need to make a connectionstring in your we.config file.
In order to making a connection string you have to provide the following information.
SqlServer Name Database Name UsernamePassword
connectionString="Server=yourservername; Database=pubs;User Id=your userid; password=you password"
After collecting above information , you have to create web.config file like shown below , or copy and paste the below
content in your web.config file and fill the appropriate parameter values.
Here we are going to connect the database and count the number of rows in the publishers table.
The sql command is : SELECT COUNT(*) FROM publishers
In order to retrieve the connection string value from web.config file , we code like the following :
vb.netDim connectionString As StringconnectionString = ConfigurationManager.ConnectionStrings("SQLDbConnection").ToString
C# string connectionString = ConfigurationManager.ConnectionStrings["SQLDbConnection"].ToString();
After we retrieve the connection string , we will create a command object for execute the sql and read the result using SqlDataReader.
vb.net Dim command As SqlCommand
Dim dataReader As SqlDataReader
command = New SqlCommand("SELECT COUNT(*) FROM publishers", connection)
dataReader = command.ExecuteReader
SqlCommand command = new SqlCommand("SELECT COUNT(*) FROM publishers", connection);
SqlDataReader dataReader = command.ExecuteReader();
Finally we retrieve the result in a string and show it in a Label control.
vb.net Label1.Text = "Rows Count : " & dataReader(0).ToString()
C# Label1.Text = "Rows Count : " + dataReader[0].ToString();
Default.aspx
Untitled Page
Click the following links to see full source code
Advertisement