对参数化查询使用If语句

时间:2015-02-18 15:01:31

标签: c# asp.net

我有一个网络表单,注册用户可以在其中上传文件。当用户上传文件时,它会被保存。如果上传了具有确切名称的另一个文件,则文件名将获取时间和日期戳以停止覆盖旧文件。然后我将文件名存储在数据库中,但我似乎无法弄清楚如何在数据库中保存新文件名。我的代码如下

if(FileUpload1.HasFile)
{

    string dir = "DirectoryPath";
    string fileName = Path.Combine(dir, FileUpload1.FileName);

    if (!File.Exists(fileName))
    {
      FileUpload1.SaveAs(fileName);
    }
    else
    {
      string newFileName =
      Path.Combine(Path.GetDirectoryName(fileName),
      string.Concat(Path.GetFileNameWithoutExtension(fileName),
      DateTime.Now.ToString("_yyyy_MM_dd_HH_mm_ss"),
      Path.GetExtension(fileName)));
      FileUpload1.SaveAs(newFileName);
    }
}

将其保存在数据库中

using (SqlConnection connection = new SqlConnection("MyConnectionString"))
{
  string myQuery = "INSERT INTO MyTable(FileName) VALUES(@Filename)";
  SqlCommand cmd = new SqlCommand(myQuery, connection);
  cmd.Parameters.AddWithValue("@Filename"); //What argument would I pass here?
  connection.Open();
  cmd.ExecuteNonQuery();
}

如果我cmd.Parameters.AddWithValue("@Filename",FileUpload1.FileName);,那么即使同一文件上传两次,原始名称也会存储在数据库中。我会将参数化查询放在else块中吗?在此先感谢您的帮助

6 个答案:

答案 0 :(得分:1)

您应该将新文件名传递给您的命令,如下所示:

cmd.Parameters.AddwithValue ("@fileName" , newfilename);

答案 1 :(得分:1)

根据我对你的问题的评论,我做了一个例子来说明可以做些什么。

  1. 创建一个以guid为主键的表
  2. 添加用户提供的文件名
  3. 使用guid将上传的文件保存在hardDisk上
  4. <强> fileUploadDemo.aspx

    <h2>FileUpload Demo</h2>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
        <asp:Label ID="lblStatus" EnableViewState="false" runat="server"></asp:Label>
    </div>
    </form>
    

    fileUpload.aspx

    <强> fileUploadDemo.aspx.cs

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            try
            {
                SqlConnectionStringBuilder conBuild = new SqlConnectionStringBuilder();
                conBuild.InitialCatalog = "dbFileUploadDemo";
                conBuild.DataSource = @"localhost\sqlexpress";
                conBuild.IntegratedSecurity = true;
    
                string uploadDirectory = @"e:\uploads";
                Guid idFile = Guid.NewGuid();
    
                using (SqlConnection con = new SqlConnection(conBuild.ConnectionString))
                {
                    con.Open();
                    SqlCommand com = new SqlCommand("insert into tblFiles (idFile, fileName) values (@idFile, @fileName)", con);
                    com.Parameters.AddWithValue("fileName", FileUpload1.FileName);
                    com.Parameters.AddWithValue("idFile", idFile);
                    com.ExecuteNonQuery();
    
                    string fileName = Path.Combine(uploadDirectory, idFile.ToString());
                    FileUpload1.SaveAs(fileName);
                }
                lblStatus.Text = "File uploaded";
            }
            catch (Exception ex)
            {
                // insert logging and exception handling here
                Debug.WriteLine(ex.Message);
    
                lblStatus.Text = "Error!";
            }
        }
        else
        {
            lblStatus.Text = "Please select file!";
        }
    }
    

    数据库dbFileUploadDemo

    database example from ms sql server 2012

    在硬盘上上传位置 upload directory on your hard disk

    当然还有好几件事要做。但我认为这可能会做你想要的,并提供一个很好的例子。

答案 2 :(得分:0)

我认为你需要这样的东西:

else
{
...
cmd.Parameters.AddWithValue("@Filename",newfilename); 
...
}

答案 3 :(得分:0)

简单的解决方案是始终将当前DateTime放入fileName。

cmd.Parameters.AddWithValue("@Filename",FileUpload1.FileName + DateTime.Now.ToString());

在这种情况下,每次fileName都是唯一的。如果你想只在fileName已经存在时才放入DateTime,你应该首先检查文件是否存在。

int filesCount = 0;
using (SqlConnection connection = new SqlConnection("MyConnectionString"))
{
  string query = @"Select count(*) From MyTable Where FileName=@FileName";
  SqlCommand cmd = new SqlCommand(query , connection);
  cmd.Parameters.AddWithValue("@Filename", FileUpload1.FileName); 

  connection.Open();
  filesCount  = Convert.ToInt32(cmd.ExecuteScalar());
}

在您的查询中,您将根据fileCount值设置2个不同的参数。

using (SqlConnection connection = new SqlConnection("MyConnectionString"))
{
  string myQuery = "INSERT INTO MyTable(FileName) VALUES(@Filename)";
  SqlCommand cmd = new SqlCommand(myQuery, connection);

  if(count == 0)
      cmd.Parameters.AddWithValue("@Filename", FileUpload1.FileName); 
  else
      cmd.Parameters.AddWithValue("@Filename",FileUpload1.FileName + DateTime.Now.ToString());

  connection.Open();
  cmd.ExecuteNonQuery();
}

对我而言,最好使用我的第一个建议。

答案 4 :(得分:0)

当您使用您描述的用于存储上传文件的技术时,您必须有两个文件名字段:一个用于原始文件名,另一个用于存储的文件名。

作为旁注,由于您有时重命名文件并且必须具有重命名文件的功能,我认为每次重命名文件都是有意义的。我建议使用GUID作为文件名。

我还认为根据上传日期或文件数创建文件夹结构是个好主意,所以你永远不会在一个目录中获得太多文件。

答案 5 :(得分:0)

string fileName = "";
        if (FileUpload1.HasFile)
        {

            string dir = "DirectoryPath";
            fileName = Path.Combine(dir, FileUpload1.FileName);

            if (!File.Exists(fileName))
            {
                FileUpload1.SaveAs(fileName);
            }
            else
            {
                fileName = Path.Combine(Path.GetDirectoryName(fileName), string.Concat(Path.GetFileNameWithoutExtension(fileName), DateTime.Now.ToString("_yyyy_MM_dd_HH_mm_ss"), Path.GetExtension(fileName)));
                FileUpload1.SaveAs(fileName);
            }
        }
        if (fileName != "")
        {
            using (SqlConnection connection = new SqlConnection("MyConnectionString"))
            {
                string myQuery = "INSERT INTO MyTable(FileName) VALUES(@Filename)";
                SqlCommand cmd = new SqlCommand(myQuery, connection);
                cmd.Parameters.AddWithValue("@Filename",fileName); 
                connection.Open();
                cmd.ExecuteNonQuery();
            }
        }