How to make SQL Server backup in Laravel? - sql-server

I try to do backup to my SQL Server databases in App as its explained in Microsoft.
It's executing, I see the Dumpfile on disk as I have named it and it disappears after a few seconds. And no error appear. I do it by different ways all of its give the same result.
this is the Microsoft link: https://learn.microsoft.com/ar-sa/archive/blogs/brian_swan/backup-and-restore-a-database-with-the-sql-server-driver-for-php
I had run it by routes and controller, and by PHP code and JavaScript, all of them do the same .
This is the PHP code:
$backup_file = "d:\backup\TestDB_Backup.bak";
$sql = "BACKUP DATABASE Mydatabase TO DISK = '".$backup_file."'";
$connectionInfo = array( "Database"=>"Mydatabase","TrustServerCertificate"=>"True", "CharacterSet" => "UTF-8");
$conn=sqlsrv_connect( ".", $connectionInfo);
$stmt = sqlsrv_query($conn, $sql);
SQL Server Version 2017, Laravel V9

Related

SQL Server configuration in Lumen

I'm trying to set Lumen with SQL Server, but I can not ...
My .env file is:
DB_CONNECTION = sqlsrv
DB_HOST = MYSERVER
DB_DATABASE = MIDB
DB_USERNAME = MIUSER
DB_PASSWORD = MIPASSWORD
Lumen does not throw any errors, but is left wondering, do nothing.
we could explain the correct way to set up for another engine database than not MySQL.
Greetings, thank you very much.

Can't restore database with LocalDB

I have been using this code for about 2 years to restore 2008 r2 backup to 2008 r2 and it works every time. I am now trying to use the same code to restore from 2008 r2 backup to 2012 localdb and it fails every time. The error message is below. Not only does the restore fail, it leaves my current database in 'recovery pending' state, and is unusable. I am using c# and this must all be done programmatically with no user or DBA involvement. Can you help me get this thing back on track?
using(var connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = String.Format("Alter Database {0} SET SINGLE_USER With ROLLBACK IMMEDIATE", dbName);
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
connection.Open();
cmd.ExecuteNonQuery();
SqlCommand cmd2 = new SqlCommand();
cmd2.CommandText = String.Format(#"RESTORE DATABASE {0} FROM DISK = '{1}'", dbName, backupFilePath);
cmd2.CommandType = CommandType.Text;
cmd2.Connection = connection;
cmd2.ExecuteNonQuery();
}
System.Data.SqlClient.SqlException (0x80131904): The logical database file 'MyData_log' cannot be found. Specify the full path for the file.
RESTORE could not start database 'MyData'.
RESTORE DATABASE is terminating abnormally.
Edit: changed one line to
cmd2.CommandText = String.Format(#"RESTORE DATABASE {0} FROM DISK = '{1}' WITH FILE = 1, NOUNLOAD, REPLACE, STATS = 5", dbName, backupFilePath);
So far has made no difference.
Shouldn't you RESTORE DATABASE and use the WITH REPLACE option? And does your connection string connect you to the 'master' database for running these commands, rather than the database being restored?
Have you used SQL Server Management Studio to look at the database file name and locations for the *.mdf and *.ldf files?
I also find that sometimes the very FIRST restore of a database doesn't work as expected, but subsequent ones do... have you tried manually restoring the database (using SQL Server Management Studio... right-click the DB, tasks, restore database), and then tried running the code programmatically?
Generally, when doing restores programmatically, you want to grab the file names of the mdf and ldf files, and then specify them in the RESTORE command with the "WITH REPLACE" option.

"The target database schema provider could not be determined" With VSDBCMD but Only When /ConnectionString is Specified

I have been developing a deployment script to deploy our database project to multiple database instances. I'm testing it by running it manually. It is a very simple script, and just runs VSDBCMD against a deployment manifest created to deploy our base, or template database. In order to deploy to different databases on the same server, the script uses the deployment manifest, but then also specifies the /p:DatabaseName and /p:TargetDatabase properties.
This has been working all day.
We are using SQL Server authentication for these databases, and I wanted to be able to specify the username and password as parameters to the script, so that they wouldn't have to be hardcoded. The only way I could see to do that was to use the /ConnectionString switch. That's what caused the failure. Even when I specify the exact same connection string as is stored in the deployment manifest, the script fails with the error "The target database schema provider could not be determined". The script:
function DeployDatabase([string] $manifestPath, [string] $password, [string] $instance, [string] $server, [string] $user)
{
$vsdbcmdPath = "c:\Program Files (x86)\Microsoft Visual Studio 10.0\VSTSDB\Deploy"
$vsdbcmd = "$vsdbcmdPath\vsdbcmd.exe"
$outputScriptPath = "$instance.sql"
$logPath = "$instance.log"
$connectionString = "Data Source=$server;User ID=$user;"
& $vsdbcmd /dd /dsp:SQL /manifest:$manifestPath /a:Deploy /p:DatabaseName=$instance /p:TargetDatabase=$instance /script:$outputScriptPath /cs:"$connectionString" |
Out-File -FilePath $logPath
}
# Actual call is omitted to protect the $server, $user and $password
Simply omitting the /cs switch allows this to succeed again. Note from the connection string, above, that it's not even necessary to specify the password in the connection string in order to cause a failure.
The target database server is running SQL Server 2008 R2, and is up to date on patches.
I'd like to know how to avoid this error, or else I'd like to know a better way to specify the username and password when deploying, without requiring the password to be in the deployment manifest in cleartext.
I am having the same issue. Did you try to set the instance name?
The SQL Instance name in the connection string could be wrong.
Also doublecheck if User Id and Password are set, if you are not using Integrated Security.

Powershell SQL Server database restore (with CDC)

I am trying to create a Powershell script to restore database to my laptop from my desktop. I have a script which creates the backup files and have almost got the restore script working apart from a strange error I get with a CDC enabled database. What I end up with is an off-line single user database. I have to bring it back on-line and change it back to multi-user manually. Here are the relevant bits of my powershell code ...
$instance = "(local)"
$server = New-Object Microsoft.SqlServer.Management.Smo.Server $instance
$restore = New-Object Microsoft.SqlServer.Management.Smo.Restore
$restore.Action = "Database"
$restore.Database = $dbname
$restore.NoRecovery = $false
$restore.ReplaceDatabase = $true
$restore.Devices.AddDevice($filename, "File")
$restore.SqlRestore($server)
I get an error message saying ...
*System.Data.SqlClient.SqlException: Could not update the metadata that indicates database xxxxx is not enabled for Change Data Capture. The failure occurred when executing the command '[sys].[sp_MScdc_ddl_database triggers 'drop''. The error returned was 15517: 'Cannot execute as the database principal because the principal "dbo" does not exist, this type of principal cannot be impersonated, or you do not have permission'*
and a bit further down ...
*The database has been left offline. See the topic MSSQL_ENG003165 in SQL Server Books Online.*
further down ...
Converting database 'xxxxx' from version 655 to the current version 661.Database 'xxxxx' running the upgrade step from version 655 to version 660.Database 'xxxxx' running the upgrade step from version 660 to 661.
While I can get the database back to a useable state, I would ideally like to have it completely scripted. The idea of this is that I can run the backup script on my desktop and then run the restore script on my laptop, which then restores the databases on my laptop so I have a working copy of the same database for when I need to work remotely.
Any insights would be great, even better if someone has come across and solved the same problem.
When I had to set an explicit CDC setting in a restore script, I did something like:
$script_lines = $restore.script( $server )
$script_lines += ', keep_cdc'
$script = ''
foreach ($line in $script_lines) {
$script += $line
}
$script
invoke-sqlcmd -ServerInstance $server.name -Query $script -QueryTimeout 65535

don't see the new database and can't log in

I create a database using ADO.NET SQL queries like this:
create database mydatabase
create login 'loginname' with password='somepassword'
create user 'username' for login loginname
The queries aren't exact, I've typed them as far as I could remember them.
After that I don't see the database in my ms sql server 2008 r2 express management studio.
I also can't log in with the newly created login. The "enable server authentication" is set to true.
What should I do to see that database in the manager?
Why can't I log in with newly created login? I've looked into the logs and it says that the password is incorrect.
I do have 2 sql express instances, but I use the same one when I run my sql
select ##servername when run in management studio returns "BOGDAN".
ADO.NET query returns "BOGDAN\BBF17ECB-69FF-4B" . Code is below:
SqlConnection con = new SqlConnection("Data Source=BOGDAN;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand("select ##servername", con);
con.Open();
string s = (string)cmd.ExecuteScalar();
Console.WriteLine("Server name:" + s);
con.Close();
Console.ReadKey(false);
Don't know where BBF17ECB-69FF-4B came from, I explicitly stated server name as "BOGDAN".
the script is:
IF DB_ID('MyDatabase') IS NULL CREATE DATABASE [MyDatabase]
USE MyDatabase
IF NOT EXISTS(SELECT * FROM master.dbo.syslogins WHERE loginname = 'AUsername') CREATE LOGIN AUsername WITH PASSWORD='APassword'
IF NOT EXISTS (SELECT * FROM sys.sysusers WHERE name='AUsername') CREATE USER AUsername FOR LOGIN AUsername
EXEC sp_addrolemember N'db_owner', N'AUsername'
Do you have multiple instances of Sql Server on your box? Maybe an express install, and a developer edition install? It's possible you were pointed at the other instance when you created the db...I have done this before.
Are you sure that the database creation completed without error? Maybe it failed, and the db was never created.
Unfortunately, the details of the query that you would have run are where we would find the evidence for the problem.
The problem was with the connection string: I had to remove "User Instance=true" from it. That fixed the problem!
I thought the problem was with how I configurated the servers or with the SQL requests.

Resources