ASP. net mvc and SQL Server connection, asp. netmvc
I used to use Entity Framework to connect to the database. In this article, I will try to use SqlConnection to connect to the database.
Open SQL Server 2008, create a database, and create the following table:
create table Product
(
Id int identity(1,1) not null primary key,
Name nvarchar(50) null,
quantity nvarchar(50) null,
Price nvarchar(50) null
)
go
Click "connect to Database" under "Tools" in Visual Studio, and select "Microsoft SQL Server" as the data source.
Click "continue ".
Connect to the created database and click "OK ".
Open "server resource manager" as follows:
Right-click "server resource manager" and click "properties" to copy the connection string. Paste the post to 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 help class to process connections, as shown below:
public class SqlDB
{
protected SqlConnection conn;
// Open the 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 the 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 successful ");
}
else
{
Return Content ("connection failed ");
}
}
}
View the Test/Index view, and the connection is successful.