Here, I useProgramInstall the SQL Server database on the customer's machine: Check whether the database exists before restoring the data. If yes, you can delete the database or kill the related processes of the database. Then perform the restore operation.
Code
Public Class Databaseworkflow
{
Public Dataoperatebase _ example; // Database operation objects
Public Databaseworkflow ()
{
_ Bytes = New Sqldataoperate ();
// Webconfig is the definition class
_ Response. connectionstring = Webconfig. getmasterconn (); // Initialize connection
}
/// <Summary>
/// Backup/recovery
/// </Summary>
/// <Param name = "type"> Operation type, 1 is backup, 2 is recovery </Param>
/// <Param name = "filepath"> Path, such as D: \ Bak. Bak </Param>
/// <Returns> </returns>
Protected Bool Databasebak ( Int Type, String Filepath)
{
Bool Returndata = False ;
String Dbname;
String Sqltext = String . Empty;
Sqlconnection con = New Sqlconnection ();
Con. connectionstring = Webconfig. getconnstr ();
Dbname = Con. database;
If (Type = 1 )
{
Sqltext = " Backup Database " + Dbname + " To disk =' " + Filepath + " 'With init " ;
}
Else If (Type = 2 )
{
If (Existsdb (dbname ))
{
Killproc (dbname );
}
Sqltext = " Restore database " + Dbname + " From disk =' " + Filepath + " ' " ;
}
Try
{
_ Plain. execsql (sqltext );
Returndata = True ;
}
Catch (Sqlexception sqlex ){
Throw (Sqlex );
}
Return Returndata;
}
}
/// <Summary>
/// Determine whether the database exists
/// </Summary>
/// <Param name = "dbname"> Database Name </Param>
/// <Returns> </returns>
Private Bool Existsdb ( String Dbname)
{
Bool Exist = False ;
String Sqltext = " If not exists (select * from Master .. sysdatabases where name =' " + Dbname + " ') Select getdate () else select null " ;
Datatable DT;
_ Response. connectionstring = Webconfig. getmasterconn ();
_ Plain. execsql (sqltext, Out DT );
If (Dt. Rows [ 0 ] [ 0 ] = Convert. dbnull)
{
Exist = True ;
}
Return Exist;
}
/// <Summary>
/// Kill database Processes
/// </Summary>
/// <Param name = "dbname"> Name of the database to kill the process </Param>
Private Void Killproc ( String Dbname)
{
_ Parameter. addparameter ( " @ Dbname " , Dbname );
Try
{
_ Program. execproc ( " Killspid " ); // Stored procedures are available in many places and can be found online
}
Catch (Sqlexception ex)
{
Throw New exception (ex. Message);
}< BR >}