Asp.net database connection code

Source: Internet
Author: User

Written according to your own understanding, there may be errors

When I first started learning, I thought how I needed so many things to connect to a database. Now I want to help my friends who just started learning asp.net.


Data acquisition phase:

Protected SqlConnection conn; // create a database connection object
Protected SqlDataAdapter da; // create a database query object
Protected DataSet ds; // create a DataSet data table object to achieve a closed connection
Protected SqlCommand comm; // operation object for creating a database
Protected void Page_Load (object sender, EventArgs e)
{
Conn = new SqlConnection ("Data Source = localhost; Initial Catalog = nd_data; User ID = sa; Password = aaaaaa"); // obtain the connection string and establish a connection
Da = new SqlDataAdapter (); // initialize the query object
Da. SelectCommand = new SqlCommand ("select name, id from xs Order by id, name DESC", conn); perform a database operation to query the id and name
Ds = new DataSet (); initialize the DataSet object
Try
{
Conn. Open (); // Open the connection
Da. Fill (ds, "abs"); // obtain data and store it in a table named "abs ".
Conn. Close (); // Close the connection
}
Catch (SqlException e1) // handle errors
{
Response. Write (e1.ToString ());
}

Data Display stage:

PagedDataSource objPds = new PagedDataSource (); // create a data source object acting on the Control
ObjPds. DataSource = ds. Tables ["abs"]. DefaultView; // input the previously saved "abs" table.
DataListname. DataSource = objPds; // the data source object is passed into the DataList control.
DataListname. DataBind (); // The DataList control displays data information.


Foreground Data Display Method:

<ItemTemplate> // DataList Data Control Template
<Asp: Label ID = "lbNwes" runat = "server" Text = '<% # Eval ("id") %>'> </asp: Label> // display id
<Asp: Label ID = "lbTime" runat = "server" Text = '<% # Eval ("name") %>'> </asp: Label> // display name
</ItemTemplate>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.