'C:'附近的语法不正确。关键字'with'附近的语法不正确

时间:2015-05-18 15:57:17

标签: c# asp.net

'C:'附近的语法不正确。关键字'with'附近的语法不正确。如果此语句是公用表表达式,xmlnamespaces子句或更改跟踪上下文子句,则必须以分号结束前一个语句。

SqlConnection objcon = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|Database1.mdf;Integrated Security=True;");
SqlCommand sqlcmd = new SqlCommand();

protected void btnBackup_Click(object sender, EventArgs e)
{
    try
    {
        string _DatabaseName = ddlDatabases.SelectedItem.Text.ToString();
        string _BackupName = _DatabaseName + "_" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() + ".bak";
        objcon.Open();
        string sqlQuery = "BACKUP DATABASE " + _DatabaseName + " TO DISK = 'C:\\SQLServerBackups\\" + _BackupName + "' WITH FORMAT, MEDIANAME = 'Z_SQLServerBackups', NAME = '" + _BackupName + "';";
        SqlCommand sqlCommand = new SqlCommand(sqlQuery, objcon);
        sqlCommand.CommandType = CommandType.Text;
        int iRows = sqlCommand.ExecuteNonQuery();
        objcon.Close();
        lblMessage.Text = "The " + _DatabaseName + " database Backup with the name " + _BackupName + " successfully...";
        ReadBackupFiles();
    }
    catch (SqlException sqlException)
    {
        lblMessage.Text = sqlException.Message.ToString();
    }
    catch (Exception exception)
    {
        lblMessage.Text = exception.Message.ToString();
    }
}

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

SqlConnection objcon = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|Database1.mdf;Integrated Security=True;");
    SqlCommand sqlcmd = new SqlCommand();
    protected void btnBackup_Click(object sender, EventArgs e)
    {
        try
        {
            string _DatabaseName = ddlDatabases.SelectedItem.Text.ToString();
            string cleandb=Path.GetFileNameWithoutExtension(_DatabaseName);
            string _BackupName = cleandb + "_" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + "_" + DateTime.Now.Year.ToString() + ".bak";
            objcon.Open();
            string sqlQuery = "BACKUP DATABASE [" + _DatabaseName + "] TO DISK='C:\\SQLServerBackups\\" + _BackupName + "'";
            SqlCommand sqlCommand = new SqlCommand(sqlQuery, objcon);
            sqlCommand.CommandType = CommandType.Text;
            int iRows = sqlCommand.ExecuteNonQuery();
            objcon.Close();
            lblMessage.Text = "The " + _DatabaseName + " database Backup with the name " + _BackupName + " successfully...";
            ReadBackupFiles();
        }
        catch (SqlException sqlException)
        {
            lblMessage.Text = sqlException.Message.ToString();
        }
        catch (Exception exception)
        {
            lblMessage.Text = exception.Message.ToString();
        }
    }

我已删除备份命令上的额外参数,用括号括起数据库名称,并删除DISK =中等号周围的空格