C:'附近语法不正确.关键字'和'附近语法错误

本文关键字:语法 错误 关键字 不正确 | 更新日期: 2023-09-27 17:49:32

'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();
    }
}

C:'附近语法不正确.关键字'和'附近语法错误

尝试如下:

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 =

中等号周围的空格。