Below is my code to add data to a database. I use SQL Server 2014 and Visual Studio community. I have created a database WebPageMovies
in the server. I can see the database in the server explorer window, but not in the solution explorer window. But while running it, it returns an error
Connection string "WebPagesMovies" was not found
Code:
@{
var title = "";
var genre = "";
var year = "";
if (IsPost)
{
title = Request.Form["title"];
genre = Request.Form["genre"];
year = Request.Form["year"];
var db = Database.Open("WebPagesMovies");
var insertCommand = "INSERT INTO Movies (Title, Genre, Year) Values(@0, @1, @2)";
db.Execute(insertCommand, title, genre, year);
Response.Redirect("~/Movies");
}
}
You can add it in multiple ways ie either in the <appSettings></appSettings>
tag or even in a <connectionStrings></connectionStrings>
tag
<appSettings>
<add key="WebPagesMovies" value="your database credentials"/>
<appSettings>
or
<connectionStrings>
<add name="WebPagesMovies" connectionString="your database credentials"/>
</connectionStrings>
After doing this read the connection string in your .cs file in which you are accessing your database.
private readonly SqlConnection connectionString = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["WebPagesMovies"]);
or
private readonly SqlConnection connectionString = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["WebPagesMovies"]);
respectively depending on where you have added the connectionstring( <Appsettings>
or <conncetionstrings>
).
There must be a connectionString called "WebPagesMovies" in your project web.config file. If not, create one.
You can add it just below <system.web>
as shown below.
<connectionStrings>
<add name="WebPagesMovies"
providerName="System.Data.SqlClient"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=DatabaseName;Integrated Security=True;MultipleActiveResultSets=True" />
</connectionStrings>
检查您的web.config中是否存在名为WebPagesMovies的连接字符串。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.