[Learning] Optimal Method for connecting ASP. NET to access database web. config

Source: Internet
Author: User

 

 

Many of my friends are troubled by the relative path of the Access database in the. NET program, so every time a mobile program wants to modify web. config
Database path of the database connection string in.

The Web. config statement is as follows:

<Deleetask>
<Add key = "oledbconnectionstring" value = "provider = Microsoft. Jet. oledb.4.0; Data
Source = E: \ WEB \ app_data \ data. mdb) "> </Add>
</Appsettings>

Write in the program as follows:

Myconn = new oledbconnection (system. configuration. configurationmanager. deleetpipeline ["oledbconnectionstring"]); // Note: The configurationsettings statements in vs2005 and vs2003 are different. Check the differences.

In this way, errors such as the following are often prompted during the program running:
'C: \ windows \ system32 \~ \ App_data \ data. mdb 'is not a valid path. Check whether the path name is correctly spelled and whether it is connected to the server where the file is stored. Data Source = ~ \ App_data \ data. MDB
Even if the absolute path is correct, you need to modify web. config when porting the program, which is troublesome.

Some web. config also uses server. mappath like ASP to retrieve the database path. However, Web. config does not know server. mappath, and this method does not work.

Later, by exploring and referring to other programs, we summarized the following methods to facilitate program migration without having to modify the ACCESS database path.

My web. config statement is as follows:

<Deleetask>
<Add key = "sqlconnstring" value = "provider = Microsoft. Jet. oledb.4.0; Data Source ="/>
<Add key = "dbpath" value = "~ /App_data/mydata. mdb "/>
</Appsettings>
In the program's data category class, I took "sqlconnstring" and "dbpath" and connected them to a string "conn_string_non_dtc"
Public static readonly string conn_string_non_dtc = system. configuration. configurationmanager. appsettings ["sqlconnstring"]. tostring () + system. web. httpcontext. current. server. mappath (configurationmanager. appsettings ["dbpath"]) + ";";

End of ASP. NET optimal way to connect to the ACCESS database web. config

Post 2 web. config configure the relative path of access

I am using VS 2005. After debugging, the Code is as follows (VB. NET example, C # method is the same, not to mention here)

First, add the following code to the <etettings> node of the web. config file:
<! -- Data source -->
<Add key = "myds" value = "Provider = Microsoft. Jet. OLEDB.4.0; Data source ="/>
<! -- Database relative path -->
<Add key = "myconn" value = "App_Data \ VinikeData. mdb"/>

Then, write a class file and call the above definition. The Code is as follows:

'The difficulty lies in defining a connection string. Many servers are used online. mapPath, but it still does not work. Note that the Request is used here. mapPath (this is useless to asp)
Public connstr As String = ConfigurationSettings. receivettings ("myds") + HttpContext. Current. Request. MapPath ("~ ") + (ConfigurationSettings. receivettings (" myconn "). Trim ())

 

Using System;
Using System. Data;
Using System. Configuration;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. UI. HtmlControls;
Using System. Data. OleDb;
/// <Summary>
/// Summary of Connection
/// </Summary>
Public class connection
{
Public connection ()
{
//
// Todo: add the constructor logic here
//
}
Public static oledbconnection connaccess ()
{
Oledbconnection conn = new oledbconnection (getconnstring ());
Return conn;
}
Private Static string getconnstring ()
{
Return System. configuration. configurationsettings. receivettings ["connstr"] + system. Web. httpcontext. Current. server. mappath ("~ ") + System. configuration. configurationsettings. receivettings [" dbpath "];
}

}

 

 

Using system;
Using system. Data;
Using system. configuration;
Using system. collections;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;
Using system. Data. oledb;
Public partial class test_sss_defauldddt: system. Web. UI. Page
{
Protected void page_load (Object sender, eventargs E)
{

}
Protected void button#click (Object sender, eventargs E)
{
System. Data. oledb. oledbconnection conn1 = connection. connaccess ();
Conn1.open ();
If (conn1.state = connectionstate. open)
{
Label1.text = "connection successful! ";
}
Else
{
Label1.text = "connection failed! ";
}
}
}

Post 3 c #2.0 web. config

<Configuration xmlns = "http://schemas.microsoft.com/.NetConfiguration/v2.0">
<AppSettings/>
<ConnectionStrings>
<Add name = "book" connectionString = "Provider = Microsoft. Jet. OLEDB.4.0; Data Source = D: \ c # \ book \ App_Data \ book. mdb"
ProviderName = "System. Data. OleDb"/>
</ConnectionStrings>

 

Database Calling:

Using System;
Using System. Data;
Using System. Configuration;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. UI. HtmlControls;
// The namespace must be introduced here because you need to use the Access database.
Using System. Data. OleDb;

/// <Summary>
/// This is mainly the database connection class used in the message book. because there are not many data operations, the conventional operation classes are also put here.
/// </Summary>
Public class odb
{
Public string name;
Public string email;
Public string qq;
Public string msn;
Public string url;
Public string title;
Public string concent;
Public string face;
Public string ip;
Public string pwd;
Public string uid;
Public string pwda;
Public DateTime dtt;

Public odb ()
{
//
// TODO: add the constructor logic here
//
}
Public static OleDbConnection con ()
{// Database connection class
OleDbConnection con = new OleDbConnection (ConfigurationManager. ConnectionStrings ["book"]. ConnectionString );
Return con;
}
Public static bool insert (string que)
{// Insert, delete, update, and other operations based on the passed SQL statement
OleDbConnection con = odb. con ();
Con. Open ();
OleDbCommand cmd = new OleDbCommand (que, con );
Int count = Convert. ToInt32 (cmd. ExecuteNonQuery ());
If (count> 0)
Return true;
Else
Return false;
}
Public static DataTable ds (string que)
{// Return a data table loaded with an SQL-based message,
OleDbConnection con = odb. con ();
OleDbDataAdapter oda = new OleDbDataAdapter ();
Oda. SelectCommand = new OleDbCommand (que, con );
DataSet ds = new DataSet ();
Oda. Fill (ds, "thc ");
Return ds. Tables ["thc"];
}
Public static bool img (string que)
{// Query whether the specified item has content based on the sent condition. If yes, true is returned.
OleDbConnection con = odb. con ();
Con. Open ();
OleDbCommand cmd = new OleDbCommand (que, con );
If (cmd. ExecuteScalar (). ToString ()! = "")
Return true;
Else
Return false;
Con. Close ();
}
Public static string SCR (string que)
{// Return the value of a field based on the sent SQL statement. Generally, the SQL statement should be implemented in the class.
Oledbconnection con = ODB. Con ();
Con. open ();
Oledbcommand cmd = new oledbcommand (que, con );
Return cmd. executescalar (). tostring ();
}
Public static int num (string mm)
{// Return the number of entries per entry as required
Return convert. toint32 (ODB. scr ("select [" + mm + "] from [config]");
}
}
Post 4How to connect to the access database on the asp.net logon interface for verification
Using System;
Using System. Data;
Using System. Configuration;
Using System. Collections;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. UI. HtmlControls;
Using System. Data. OleDb;
Public partial class login: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
// The following code generates a random Verification Code and is displayed in label1.
Random ro = new Random ();
If (! IsPostBack)
{
This. Label1.Text = ro. Next (1000,999 9). ToString ();
}
}
Protected void button#click (Object sender, eventargs E)
{

If (this. Name. Text! = "") // Determines whether the user name is empty
{
If (this. pwd. Text! = "") // Determines whether the password is empty
{
If (this. yanzhen1.text! = "") // Check whether the verification code is empty
{
If (this. yanzhen1.text = This. label1.text) // checks whether the verification code is equal.
{
String SQL;
SQL = "select count (*) from userinfo where username = '" + this. name. text + "'and Pwd ='" + this. PWD. text + "'"; // create an SQL query statement
Try
{
Oledbconnection conn = new oledbconnection ("provider = Microsoft. jet. oledb.4.0; Data Source = "+ server. mappath (". /app_data/DB. mdb "); // create a database connection
Conn. open ();
Oledbcommand cmd = new oledbcommand (SQL, Conn );
Int state = convert. toint32 (CMD. executescalar (); // execute the SQL statement and return the obtained value.
If (State = 0 | State> 1) // if there are no or multiple records in the data, an error is returned.
{
This. label2.text = "the user does not exist. Check whether the user name and password are correct! ";
}
Else
{
This. label2.text = "Login successful! ";

}
Conn. Close ();

}
Catch (Exception)
{
Response. writea. Message );
}
}
Else
{
This. label2.text = "the verification code is incorrect. Please enter it again! ";
}
}
Else
{
This. label2.text = "the verification code is not filled! ";

}
}
Else
{
This. label2.text = "the password is not entered! ";

}
}
Else
{
This. label2.text = "the user name is not filled! ";
}
}
}

 

 

Source: http://www.cnblogs.com/sxjrcool/archive/2008/08/16/1269462.html

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.