在尝试向同一数据库中添加新元素时,如何验证该元素是否已在我的数据库中?
我知道它可能需要一些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连接/命令。
1条答案
按热度按时间w8f9ii691#
我已经找到了答案,我所要做的就是在mappath()方法之外编写文件名,如下所示: