验证数据库中存在? (MySql& ASP.NET)

时间:2018-04-18 05:39:40

标签: c# 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连接/命令。

1 个答案:

答案 0 :(得分:0)

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

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