ASP. NET database connection code (access, mssql)

Source: Internet
Author: User

Asp.net is a Microsoft product. Next I will introduce you to how to use. net to connect to the mssql database and access database. If you need to know it, please do not refer to it.

Method

Asp.net connection access code

The Code is as follows: Copy code


<% @ Page Language = "C #" %>
<% @ Import Namespace = "System. Data" %>
<% @ Import Namespace = "System. Data. OleDb" %>
<Script runat = "server">
// Insert page code here
//
Void Page_Load (){
String db = @ "database/data. mdb ";
String connStr = "PROVIDER = Microsoft. Jet. OLEDB.4.0; DATA Source =" + Server. MapPath (db) + ";";
String SQLcmd = "create table IEB_webs (ID identity primary key, title varchar (255) Default Null )";
OleDbConnection conn = new OleDbConnection (connStr );
Conn. Open ();
OleDbCommand OleCmd = new OleDbCommand (SQLcmd, conn );
OleCmd. ExecuteNonQuery (); // execute the SQL command
Response. Write ("data table created! ");
}
Conn. Close ();
Conn = null;
OleCmd = null;
}
</Script>
<Html>
<Head>
</Head>
<Body>
<Form method = "post" runat = "server">
<! -- Insert content here -->
</Form>
</Body>
</Html>

Cause of access connection failure

An error occurred while processing the AccessDataSource connection.

(1) In the ch02 folder, create a file named TIO-4-ConnectionFailure-CS.aspx. In the Design view, add an AccessDataSource control pointing to Northwind to the page, which selects all columns from the table.

(2) Add a GridView to display information in the data source control. Similarly, add a tag control and name it "Message ".

(3) switch to the Source view and make some changes to the tag, as shown in the highlighted code below. If there is a <columns> tag, delete it. The code left behind should be as follows:

The Code is as follows: Copy code


<Html>
<Head id = "Headl" runat = "server">
<Title> Chapter 2 TIO #4 Connection Failure to Access in C # </title>
</Head>
<Body>
<H3> Chapter 2 TIO #4 Connection Failure to Access in C # <Form id = "forml" runat = "server">
<Asp: label ID = "Message" runat = "server"/> <br/>
<Asp: gridview id = "GridViewl" runat = "server"
Performanceid = "access0000cel"
AutoGenerateColumns = "true"
EmptyDataText = "No data records were returned"/>
<Asp: AccessDataSource ID = "AccessDataSourcel" Runat = "server"
Selectcommand = "Select * From Products"
Datafile = "~ /App_Data/Northwind. mdb"
OnSelected = "AccessDataSourcel_Selected"
/>

</Form>
</Body>

  

(4) Check the page. When you view products sold by Northwind, there should be no problems.

(5) Now we will add code to solve the connection problem. Go to the top of the page and enter the following script. The first example is written in C #, and the second example is written in VB. Enter one of them.

The Code is as follows: Copy code


<% @ Page language = "C #" %>
<Script runat = "server">

Void AccessDataSourcel_Selected (object sender, SqlDataSourceStatusEventArgs e)
{
If (e. Exception! = Null)
{
If (e. Exception. GetType () = typeof (System. Data. OleDb. OleDbException ))
{
Message. Text = "There was a problem opening a connection to
Database. Please contact the system administrator for this site .";

// Optionally set GridViewl. Visible = false;

E. ExceptionHandled = true;
}
}
}

</Script>
<Html>

Database Path Problems

Configure the Access database driver and database file name in Web. Config.
Please refer to the code

The Code is as follows: Copy code
<Deleetask>
<Add key = "DBDriver" value = "Provider = Microsoft. Jet. OLEDB.4.0; Data Source ="/>
<Add key = "DBName" value = "Company. mdb"/>
</AppSettings>

Obtain the Access database link string in the database Access layer, such as OleDBHelper. cs.

The Code is as follows: Copy code

/** // <Summary>
/// Obtain the database connection string from Web. Config
/// </Summary>
// Obtain the database name from the configuration file
Public static readonly string DBName = ConfigurationManager. receivettings. Get ("DBName"). ToString ();
// Obtain the database driver from the configuration file
Public static readonly string DBDriver = ConfigurationManager. deleetmanager. Get ("DBDriver"). ToString ();
// Obtain the database connection string
Private static string DBConnectionString = DBDriver + HttpContext. Current. Server. MapPath (HttpContext. Current. Request. ApplicationPath + "/App_Data/") + DBName;
// Create a database connection object
Private static OleDbConnection OleDbConn = new OleDbConnection (DBConnectionString );
After this setting, you can use the above code to access the database in any subdirectory correctly.

 

Asp.net connection to mssql database

. Net connection ms SQL database

The Code is as follows: Copy code

String ConnectionString = "workstation id =" + hostname + "; packet size = 4096; user id =" + username + "; password =" + password + "; data source = "+ hostname +"; persist security info = False; initial catalog = "+ databasename;

SqlConnection Connection = new System. Data. SqlClient. SqlConnection ();

Connection. ConnectionString = ConnectionString;

This. Connection. Open ();

System. Data. SqlClient. SqlCommand SelectCommand;

SelectCommand = new System. Data. SqlClient. SqlCommand ();

SelectCommand. CommandText = "select * from" + TableName;

SelectCommand. Connection = this. Connection;

System. Data. SqlClient. SqlDataReader dr = SelectCommand. ExecuteReader ();


Or write it like this.

The Code is as follows: Copy code

SqlConnection SQL = new SqlConnection (@ "server =. sql2005; Integrated Security = SSPI; Persist Security Info = False; Initial Catalog = test; Data Source = 7085360CB900427 ");

Try
{
SQL. Open ();
If (SQL. State = ConnectionState. Open)
Label1.Text = "connection successful! ";
}
Catch (SqlException S)
{
MessageBox. Show (S. Message );

}
Finally
{
SQL. Close ();
SQL. Dispose ();
}

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.