Before connecting the SQL Server database in ASP. NET, first make sure that sqlserver2008 is installed properly and that there is a database.
Add a class db to your project that is specifically responsible for performing additions and deletions to the database. One of the following prompts pops up during the add process
The direct point is that you can.
In this class, first define a Connection object private SqlConnection conn = null; then define the following three functions
private void SetConnection ()//Initialize Connection object
{
if (conn = = null)
{
Get the database connection string in the configuration file
String connectestring = configurationmanager.connectionstrings["Sqlcontent"]. ToString ();
conn = new SqlConnection (connectestring);
}
}
SQL to execute Query database
Public DataSet GetResult (String sql)
{
SetConnection ();
Conn. Open ();
DataSet ds = new DataSet ();
Try
{
SqlCommand command = new SqlCommand (SQL, conn);
SqlDataAdapter ad = new SqlDataAdapter (command);
Ad. Fill (DS);
}
Catch
{ }
Finally
{
Conn. Close ();
}
return DS;
}
Perform add and modify, delete functions
public bool Exemend (String sql)
{
SetConnection ();
Conn. Open ();
SqlCommand cmd = null;
SqlTransaction trans = conn. BeginTransaction (); Create transaction
Try
{
cmd = new SqlCommand (Sql,conn,trans); To create a Command object
int Num=cmd. ExecuteNonQuery ();
if (num > 0)
return true;
Else
return false;
}
catch (Exception e)
{
Trans. Rollback ();//Transaction rollback
Console.WriteLine (E.message.tostring ());
return false;
}
Finally
{Conn. Close (); }
}
Then configure the database connection string to open the configuration file, Web. config
Which. indicates this machine, if it is a server, that is the IP of the server, Mrs represents the database name.
To this, SQL Server database connection is done, you can in the business code by calling GetResult and Exemend to implement the database additions and deletions.
In C #, there are 5 common classes that work with databases: A DataSet DataSet, equivalent to an in-memory database, a SqlDataAdapter data adapter, a SqlConnection database connection object, a SqlCommand database command object, SqlDataReader the database reader.
Here's a look at the control BulletedList to display the data queried from the database by binding:
In the foreground code, pre-provision several items to see what the final display looks.
Data binding in the background
Displays the results. As you can see, the displayed results do not show the preset items.
ASP. NET connection to SQL Server database