【发布时间】:2018-04-18 05:39:40
【问题描述】:
当尝试将新元素添加到同一个数据库中时,我如何验证一个元素是否已经在我的数据库中?
我知道它可能需要一些 sql 代码,但我不能做我想做的事:
这是按钮的完整代码:
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 连接/命令的新手。
【问题讨论】:
-
你的代码有什么问题?
-
验证"try"里面的"File.Exists",不起作用,我需要验证数据库中的对象是否存在。
-
您是否正确配置了路径?通常
Server.MapPath使用虚拟路径,例如File.Exists(Server.MapPath("~/images/" + FileName)). -
试过了,结果一样,没有消息&没有添加对象。