Used to connect to the database using the Entity Framework, this article is to experience using the SqlConnection connection database.
Open SQL Server 2008, create the database, and create the following table:
CREATE TABLE Product
(
Id int Identity (+) is not null primary key,
Name nvarchar () null,
Quantity nvarchar () null,
Price nvarchar (+) null
)
Go
Click Connect to Database under the Tools menu in Visual Studio, and select Microsoft SQL Server as the data source.
Click "Continue".
Connect to the database you just created and click "OK".
Open Server Explorer, as follows:
Right click on "Server Explorer" and click "Properties" to copy the connection string. and paste it into the connectionstrings node in Web. config.
< connectionStrings >
< Add name="DefaultConnection"connectionString="Data source=pc201312021114;initial CATALOG=MVC; User Id=sa; password= Password "
providerName="System.Data.SqlClient"/>
</ connectionStrings >
Now, you need a helper class to handle the connection, as follows:
public class SqlDB
{
protected SqlConnection Conn;
Open connection
public bool OpenConnection ()
{
conn = new SqlConnection (configurationmanager.connectionstrings["DefaultConnection"]. ConnectionString);
Try
{
bool result = true;
IF (Conn. State.tostring ()! = "Open")
{
Conn. Open ();
}
return result;
}
catch (SqlException ex)
{
return false;
}
}
Close connection
public bool CloseConnection ()
{
Try
{
Conn. Close ();
return true;
}
catch (Exception ex)
{
return false;
}
}
}
Create TestController as follows:
public class Testcontroller:controller
{
Private SqlDB _db = new SqlDB ();
//
GET:/test/
Public ActionResult Index ()
{
BOOL R = _db. OpenConnection ();
if (R)
{
return Content ("Connection succeeded");
}
Else
{
return Content ("Connection failed");
}
}
}
Browse the Test/index view page to show that the connection was successful.
ASP. NET MVC establishes a connection to SQL Server