代码是在我上传图片后尝试将数据插入数据库但没有存储时给出的。我不知道为什么?
public partial class upload : System.Web.UI.Page
{
protected void UploadVideo_Click(object sender, EventArgs e)
{
string constr = @"Data Source=DESKTOP-1VOSUKD\SQLEXPRESS;Initial Catalog=Youtube;Integrated Security=True";
if (VideoUpload.PostedFile != null && ThumbnailUpload.PostedFile!=null)
{
//Video
string user = Session["user"].ToString();
string videoname = Path.GetFileName(VideoUpload.PostedFile.FileName);
string vid = user + "-video-" + videoname.Split('.')[0].ToString();
string ext = videoname.Split('.')[1];
string pathServer = Server.MapPath("~\\uservideos\\" + vid + "." + ext);
VideoUpload.PostedFile.SaveAs(pathServer);
string pathAccess = "~/uservideos/" + vid + "." + ext;
string time = "";
//Thumbnail
string thumbname = Path.GetFileName(ThumbnailUpload.PostedFile.FileName);
string thumb = user + "-thumbnail-"+videoname+"-" + thumbname.Split('.')[0].ToString();
string thumbext = thumbname.Split('.')[1];
string thumbpathServer = Server.MapPath("~\\thumbnails\\" + thumb + "." + thumbext);
ThumbnailUpload.PostedFile.SaveAs(thumbpathServer);
string thumbpathAccess = "~/thumbnails/" + thumb + "." + thumbext;
//add to database
try
{
SqlConnection con = new SqlConnection(constr);
con.Open();
string q = "insert into videos(Upload_User, Title, Discription, Video_Time, Tags, [Format], Thumbnail_Path, Video_Path) " +
"values('" + user + "','" + Title.Text + "','" + DiscriptionTextBox.Text + "','" + time + "','" + TagsTextBox.Text + "','" + ext + "','" + pathAccess + "','" + thumbpathAccess + "')";
SqlCommand cmd = new SqlCommand(q, con);
cmd.ExecuteNonQuery();
Response.Write("<script>alert('Data Saved!');</script>");
con.Close();
}
catch (Exception exe)
{
Response.Write("<script> alert('"+exe.Message+"');</script>");
}
}
}
}
答案 0 :(得分:0)
您需要将更改保存回源数据库。现在它只影响工作目录中的数据库
您可以使用Entity Framework执行此操作。将新项添加到名为“ADO.NET实体框架数据模型”的解决方案中,您可能需要从NuGet安装它。
我不知道您的文件夹结构如何,但您需要项目中的数据库副本。同时将数据库属性“复制到输出目录”更改为“如果更新则复制”。添加数据模型时,它将进行配置。
之后,代码中只进行了一些更改..
try
{
Database1Entities database1Entities = new Database1Entities();
//Edit the connectionString
SqlConnection con = new SqlConnection(database1Entities.Database.Connection.ConnectionString);
con.Open();
//Changed values to be in correct order
string q = "insert into videos(Upload_User, Title, Discription, Video_Time, Tags, [Format], Thumbnail_Path, Video_Path) " +
"values('" + user + "','" + Title.Text + "','" + DiscriptionTextBox.Text + "','" + time + "','" + TagsTextBox.Text + "','" + ext + "','" + thumbpathAccess + "','" + pathAccess + "')";
SqlCommand cmd = new SqlCommand(q, con);
cmd.ExecuteNonQuery();
//Save changes back to source
database1Entities.SaveChanges();
Response.Write("<script>alert('Data Saved!');</script>");
con.Close();
}