WinForm code, it is best to run the code on the computer where the data resides, or it will fail due to permissions problems.
Database backup:
SqlConnection con = new SqlConnection ("Data source=.;;i Nitial catalog=db_test; User Id=sa; Password=sa "); String sql = "Backup database db_test to disk= ' C:\\avb.bak '"; Con. Open (); if (! File.exists ("C:\\aa.bak")) { SqlCommand com = new SqlCommand (sql, con); Com. ExecuteNonQuery (); Executes the SQL statement lblmessage. Text = "System Information: Backup succeeded!" "; } else { lblmessage. Text = "System info: File already exists!" ";
Database restore:
Reference SQLDMO.DLL,SQLDMO is provided by Microsoft SQL Server's SQLDMO.dll, SQLDMO.dll is a COM object SQLDMO. SQL Server SVR = new SQLDMO. Sqlserverclass (); try {svr. Connect ("192.168.89.20", "sa", "Aa123456"); Get all the process list SQLDMO. QueryResults qr = svr. EnumProcesses (-1); int icolpidnum =-1; int icoldbname =-1; Locate and to recover the database related processes for (int i = 1; I <= qr. Columns; i++) {String strName = Qr.get_columnname (i); if (Strname.toupper (). Trim () = = "SPID") {icolpidnum = i; } else if (Strname.toupper (). Trim () = = "DBNAME") {icoldbname = i; } if (Icolpidnum! =-1 && icoldbname! = 1) break; }//Kill the related process for (int i = 1; I <= qr. Rows; i++) {int lpid = QR. GetColumnLong (i, icolpidnum); String strDbName = Qr. GetColumnString (i, icoldbname); if (strdbname.toupper () = = Strdbname.toupper ()) SVR. KillProcess (LPID); } SQLDMO. Restore res = new SQLDMO. Restoreclass (); Res. Action = SQLDMO. Sqldmo_restore_type. Sqldmorestore_database; Res. Files = strFileName; Res. Database = strDbName; Res. FileNumber = 1; Res. ReplaceDatabase = true; Res. SQLRestore (SVR); return true; } catch (Exception err) {//throw (New Exception ("" + Err. Message)); MessageBox.Show ("Failed to recover the database, please close all programs connected to the database!") "+ Err. Message); return false; } finally {svr. DisConnect (); }
C # Restore SQL database (non-stored procedure mode)