C# 验证数据库中是否存在?(MySql和ASP.NET)
在尝试将新元素添加到同一数据库中时,如何验证某个元素是否已在我的数据库中 我知道它可能需要一些sql代码,但我不能做我想做的事情: 这是按钮的完整代码:C# 验证数据库中是否存在?(MySql和ASP.NET),c#,mysql,asp.net,C#,Mysql,Asp.net,在尝试将新元素添加到同一数据库中时,如何验证某个元素是否已在我的数据库中 我知道它可能需要一些sql代码,但我不能做我想做的事情: 这是按钮的完整代码: protected void Button1_Click(object sender, EventArgs e) { if (FileUpload1.PostedFile != null) { string FileName = Path.GetFileName(FileUpload1.PostedFile.Fi
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.PostedFile != null)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//saves files in the disk
FileUpload1.SaveAs(Server.MapPath("images/" + FileName));
//add an entry to the database
String strConnString = ConfigurationManager.ConnectionStrings["WebAppConnString"].ConnectionString;
MySqlConnection con = new MySqlConnection(strConnString);
string strQuery = "insert into testingdb.country (Relation, FileName, FilePath) values (@Relation, @FileName, @FilePath)";
MySqlCommand cmd = new MySqlCommand(strQuery);
cmd.Connection = con;
cmd.Parameters.AddWithValue("@Relation", TextBox1.Text);
cmd.Parameters.AddWithValue("@FileName", FileName);
cmd.Parameters.AddWithValue("@FilePath", "images/" + FileName);
cmd.CommandType = CommandType.Text;
try
{
if (File.Exists(Server.MapPath("images/" + FileName)))
{
Response.Write("El Objeto ya existe en la base de datos.");
}
else
{
con.Open();
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
con.Dispose();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
怎样才能做到呢?我对使用ASP.NET和MySql连接/命令有点陌生。我已经找到了答案,我所要做的就是在MapPath()方法之外写入文件名,如下所示:
if (File.Exists(Server.MapPath("images/") + FileName))
{
//mycode & Blah, Blah, Blah.
}
您的代码有什么问题?在“try”中验证“File.Exists”无效,我需要验证数据库中是否存在对象。您是否正确配置了路径?通常
Server.MapPath
使用虚拟路径,例如File.Exists(Server.MapPath(“~/images/”+FileName))
。尝试过,结果相同,未添加任何消息和对象。