【问题标题】:Verify existence in database? (MySql & ASP.NET)验证数据库中是否存在? (MySql & ASP.NET)
【发布时间】: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)).
  • 试过了,结果一样,没有消息&没有添加对象。

标签: c# mysql asp.net


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-24
    • 1970-01-01
    • 2010-12-09
    • 1970-01-01
    • 2023-02-10
    相关资源
    最近更新 更多