繁体   English   中英

验证数据库中是否存在? (MySQL和ASP.NET)

[英]Verify existence in database? (MySql & ASP.NET)

尝试将新元素添加到同一数据库时,如何验证数据库中是否已存在某个元素?

我知道它可能需要一些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连接/命令。

我已经找到了答案,我所要做的就是在MapPath()方法之外编写FileName,如下所示:

if (File.Exists(Server.MapPath("images/") + FileName))
{
    //mycode & Blah, Blah, Blah.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM