Error While Creating Database in SQL - c#

I am new to SQL and trying to create a Database using C#. Here is my Code...
private void CreateDBBtn_Click(object sender, EventArgs e)
{
String connectionString = GetConnectionString();
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
String SQLCommand = "CREATE DATABASE MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'D:\\MyDatabase.mdf'," +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%)";
SqlCommand cmd = new SqlCommand(SQLCommand, connection);
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ae)
{
MessageBox.Show(ae.Message);
}
}
private String GetConnectionString()
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = #".\SQLSERVER";
builder.AttachDBFilename = #"D:\MyDatabase.mdf";
builder.IntegratedSecurity = true;
builder.ConnectTimeout = 30;
builder.UserInstance = true;
return builder.ConnectionString;
}
but it gives me error that...
Where as D:\MyDataBase.mdf file has size 3.13 MB on my PC.

I completely agree with DJ KRAZE. It would take about two seconds to create that using whatever server manager you have.

Related

Unable to create database using parameter for database name SQL Server & C#

I am trying to use this code:
var connString = "Server=localhost\\SQLEXPRESS;Integrated Security = SSPI; database = master";
string cmdText = "CREATE DATABASE #userDatabase";
using (var sqlConnection = new SqlConnection(connString))
{
using (var sqlCmd = new SqlCommand(cmdText, sqlConnection))
{
sqlCmd.Parameters.Add("#userDatabase", System.Data.SqlDbType.NVarChar).Value = databaseName;
sqlConnection.Open();
sqlCmd.ExecuteNonQuery();
}
}
I get an error on sqlCmd:
'Incorrect syntax near '#userDatabase'
However, when I add the database using dynamic SQL code, I get no errors and the query runs perfectly (I heard that will be dangerous though).
You can create a dynamic query to perform this.
private void SetupDatabase(string dbFolder, string dbName)
{
if (Directory.Exists(String.Format("{0}\\db", dbFolder)) == false)
{
Directory.CreateDirectory(String.Format("{0}\\db", dbFolder));
}
if (File.Exists(String.Format("{0}\\db\\{1}_Data.mdf", dbFolder, dbName)) == false)
{
ExecuteQuery(
"master",
String.Format("CREATE DATABASE {1} ON PRIMARY (NAME = {1}_Data, FILENAME = '{0}\\db\\{1}_Data.mdf', SIZE = 2MB, FILEGROWTH = 10%) LOG ON (NAME = {1}_Log, FILENAME = '{0}\\db\\{1}_Log.ldf', SIZE = 1MB, MAXSIZE = 5MB, FILEGROWTH = 10%)", dbFolder, dbName));
}
}
private void ExecuteQuery(
string db,
string query)
{
SqlConnection connection = null;
try
{
connection = new SqlConnection(string.Format(connectionString, db));
connection.Open();
// Creates DB
using (SqlCommand command = new SqlCommand(query, connection))
{
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
connection.Close();
}
}

I'm trying to restore a SQL Server database backup with this code :

I'm trying to restore a SQL Server database backup with this code:
private void restoreButton_Click(object sender, EventArgs e)
{
string database = con.Database.ToString();
if (con.State != ConnectionState.Open)
{
con.Open();
}
try
{
string sqlStmt2 = string.Format("ALTER [MangementSystemBD] [" + database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
SqlCommand bu2 = new SqlCommand(sqlStmt2, con);
bu2.ExecuteNonQuery();
string sqlStmt3 = "USE MASTER RESTORE [MangementSystemBD] [" + database + "] FROM DISK='" + textBox2.Text + "'WITH REPLACE;";
SqlCommand bu3 = new SqlCommand(sqlStmt3, con);
bu3.ExecuteNonQuery();
string sqlStmt4 = string.Format("ALTER [MangementSystemBD] [" + database + "] SET MULTI_USER");
SqlCommand bu4 = new SqlCommand(sqlStmt4, con);
bu4.ExecuteNonQuery();
MessageBox.Show("database restoration done successfully");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
But when I execute it I get this error:
For restoring database use this code
public void RestoreDatabaseBackup()
{
ExecuteQuery("EXEC msdb.dbo.sp_delete_database_backuphistory #database_name = 'DatabaseName");
ExecuteQuery("USE MASTER");
OpenFileDialog res = new OpenFileDialog();
res.ShowDialog();
if (res.FileName.ToString() == "")
{
//MessageBox.Show("Select Valid .bak File");
}
else
{
try
{
string s = res.FileName.ToString();
SqlConnection sqlConnection = new SqlConnection(#"Data Source=ServerName;Initial Catalog=yourDatabaseName;Integrated Security=True;Pooling=False");
if (sqlConnection.State == System.Data.ConnectionState.Open)
{
sqlConnection.Close();
}
sqlConnection.Open();
ServerConnection ServerConnection = new ServerConnection(sqlConnection);
Server srv = new Server(ServerConnection);
//Declare a BackupDeviceItem by supplying the backup device file name in the constructor, and the type of device is a file.
BackupDeviceItem bdi = default(BackupDeviceItem);
bdi = new BackupDeviceItem(s, DeviceType.File);
// Define a Restore object variable.
Restore rs = new Restore();
//Set the NoRecovery property to true, so the transactions are not recovered.
rs.NoRecovery = true;
rs.ReplaceDatabase = true;
// Add the device that contains the full database backup to the Restore object.
rs.Devices.Add(bdi);
rs.NoRecovery = false;
// Specify the database name.
rs.Database = sqlConnection.Database.ToString();
// Restore the full database backup with no recovery.
sqlConnection.ChangeDatabase("master");
rs.SqlRestore(srv);
// Inform the user that the Full Database Restore is complete.
srv = null;
MessageBox.Show("Database Restore complete.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
ExecuteQuery is a normal method to run SQL you should make it

How to create new database upon reopening application?

I have a log viewing application that writes log statements to a database and then sends them from the database to the log viewer GUI. I want to be able to open more than one instance of the log viewer but when I do it will be creating a database with the same name as the previous instance of the viewer. I've tried creating a database with a different name if one has already been created but that doesn't seem to work. Any suggestions? Here's the code for creating/accessing/destroying databases:
public class Database
{
public bool hasAdminPriv
{
get;
set;
}
public bool hasBeenCreated
{
get;
set;
}
public Database()
{
hasAdminPriv = true;
//Construction checks to see if user has Admin priveleges
bool isElevated;
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
if (!isElevated)
hasAdminPriv = false;
}
//returns true if the database creation was successful
public bool CreateDatabase()//creates a database dynamically by making a query request to the server
{
String str;
SqlConnection myConn = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS; Initial Catalog=Master;Integrated Security=True");
str = "CREATE DATABASE MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\MyDatabaseData.mdf', " +
"SIZE = 30MB, MAXSIZE = 10GB, FILEGROWTH = 20%) " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = 'C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\MyDatabaseLog.ldf', " +
"SIZE = 10MB, " +
"MAXSIZE = 1GB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
int done = 0;
while (done < 10)
{
String str2 = "CREATE DATABASE" + done + " MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\MyDatabaseData.mdf', " +
"SIZE = 30MB, MAXSIZE = 10GB, FILEGROWTH = 20%) " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = 'C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL.1\\MSSQL\\Data\\MyDatabaseLog.ldf', " +
"SIZE = 10MB, " +
"MAXSIZE = 1GB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand2 = new SqlCommand(str2, myConn);
try{
myCommand2.ExecuteNonQuery();
}
catch{
++done;
}
myConn.Close();
hasBeenCreated = true;
return true;
}
return false;
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
hasBeenCreated = true;
return true;
}
//Creates the table in the database by a query request
//a return value of true means Database was created succesfully
public bool CreateTable()
{
SqlConnection myConn = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS; Initial Catalog=MyDatabase;Integrated Security=True");
string createString = "CREATE TABLE storage (ID INT NOT NULL, Level varchar(255) , LevelInt INT, DateTime varchar(255),Counter smallint,Device varchar(255), Source varchar(255), Description varchar(255),PRIMARY KEY (ID))"; //YOUR SQL COMMAND TO CREATE A TABLE
SqlCommand create = new SqlCommand(createString, myConn);
myConn.Open();
create.ExecuteNonQuery();
myConn.Close();
return true;
}
//Add the element's values to the database/table to later recall/reorder
public bool addElement(LogParse log,int num)
{
SqlConnection con = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True");
try
{
con.Open();
SqlCommand cmd = new SqlCommand("Insert into storage(ID, Level, LevelInt, DateTime, Counter, Device, Source, Description) values(" + num + ",#Level, #LevelInt, #DataTimeItem,#counterItem,#deviceItem,#sourceItem,#descItem)", con);
cmd.Parameters.AddWithValue("#Level", log.Level);
cmd.Parameters.AddWithValue("#LevelInt", log.LevelInt);
cmd.Parameters.AddWithValue("#DataTimeItem", log.TimeStamp);
cmd.Parameters.AddWithValue("#counterItem", log.SequentialNumber);
cmd.Parameters.AddWithValue("#deviceItem", log.Device);
cmd.Parameters.AddWithValue("#sourceItem", log.Source);
cmd.Parameters.AddWithValue("#descItem", log.Description);
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ee)
{
return false;
}
return true;
}
//outputs a string array with all the values in the database
public LogParse[] readValue(int start, int end)
{
SqlConnection con = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True");
con.Open();
LogParse[] s = new LogParse[end - start];
try
{
using (var oCommand = new SqlCommand("SELECT * From storage WHERE ID BETWEEN #Start AND #End", con))
{
oCommand.Parameters.AddWithValue("#Start", start);
oCommand.Parameters.AddWithValue("#End", end);
using (var oReader = oCommand.ExecuteReader())
{
int i = 0;
while (oReader.Read() && i < end-start)
{
//s[i] = oReader.GetString(1) + oReader.GetString(2) + oReader.GetString(3);
String Level = oReader.GetString(1);
Int32 LevelInt = oReader.GetInt32(2);
String Datetime = oReader.GetString(3);
Int16 SequentialNumber = (Int16)oReader.GetValue(4);
String Device = oReader.GetString(5);
String Source = oReader.GetString(6);
String Description = oReader.GetString(7);
s[i] = new LogParse();
s[i].Level = Level;
s[i].LevelInt = LevelInt;
s[i].TimeStamp = DateTime.Parse(Datetime);
s[i].SequentialNumber = SequentialNumber;
s[i].Device = Device;
s[i].Description = Description;
s[i].Source = Source;
++i;
}
}
}
}
catch
{
}
con.Close();
return s;
}
//Deletes the database by a query statement
//a return value of true means the delete was succesful
public static bool deleteDatabase()
{
String str;
SqlConnection myConn = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS; Initial Catalog=Master;Integrated Security=True");
str = #"ALTER DATABASE MyDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE;DROP DATABASE [MyDatabase]";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
}
catch (System.Exception ex)
{
return false;
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
return true;
}
}
DON'T create another database, or table, it's evil. Just add Instance ID into table storage. And when writing new logs just add instance ID, same goes when reading from DB, put instance ID into where clause.
Another issue is to pick good Instance ID, your scenario is not very clear to me, but if you want every new application instance to have separate data, just create new GUID and use it as Instance ID.
For example you can have static property InstanceID in your Database class, and your class could look something like this :
public class Database
{
public static Guid InstanceID = new Guid();
//Add the element's values to the database/table to later recall/reorder
public bool addElement(LogParse log,int num)
{
SqlConnection con = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True");
try
{
con.Open();
SqlCommand cmd = new SqlCommand("Insert into storage(ID, InstanceID, Level, LevelInt, DateTime, Counter, Device, Source, Description) values(" + num + ",#Level, #LevelInt, #DataTimeItem,#counterItem,#deviceItem,#sourceItem,#descItem)", con);
// writing InstanceID
cmd.Parameters.AddWithValue("#InstanceID", Database.InstanceID);
cmd.Parameters.AddWithValue("#Level", log.Level);
cmd.Parameters.AddWithValue("#LevelInt", log.LevelInt);
cmd.Parameters.AddWithValue("#DataTimeItem", log.TimeStamp);
cmd.Parameters.AddWithValue("#counterItem", log.SequentialNumber);
cmd.Parameters.AddWithValue("#deviceItem", log.Device);
cmd.Parameters.AddWithValue("#sourceItem", log.Source);
cmd.Parameters.AddWithValue("#descItem", log.Description);
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ee)
{
return false;
}
return true;
}
//outputs a string array with all the values in the database
public LogParse[] readValue(int start, int end)
{
SqlConnection con = new SqlConnection("Data Source=" + Environment.UserName + "-D1SD\\SQLEXPRESS;Initial Catalog=MyDatabase;Integrated Security=True");
con.Open();
LogParse[] s = new LogParse[end - start];
try
{
// select with InstanceID
using (var oCommand = new SqlCommand("SELECT * From storage WHERE InstanceID = #InsID ID BETWEEN #Start AND #End", con))
{
oCommand.Parameters.AddWithValue("#Start", start);
oCommand.Parameters.AddWithValue("#End", end);
oCommand.Parameters.AddWithValue("#InsID", Database.InstanceID);
using (var oReader = oCommand.ExecuteReader())
{
int i = 0;
while (oReader.Read() && i < end-start)
{
//s[i] = oReader.GetString(1) + oReader.GetString(2) + oReader.GetString(3);
String Level = oReader.GetString(1);
Int32 LevelInt = oReader.GetInt32(2);
String Datetime = oReader.GetString(3);
Int16 SequentialNumber = (Int16)oReader.GetValue(4);
String Device = oReader.GetString(5);
String Source = oReader.GetString(6);
String Description = oReader.GetString(7);
s[i] = new LogParse();
s[i].Level = Level;
s[i].LevelInt = LevelInt;
s[i].TimeStamp = DateTime.Parse(Datetime);
s[i].SequentialNumber = SequentialNumber;
s[i].Device = Device;
s[i].Description = Description;
s[i].Source = Source;
++i;
}
}
}
}
catch
{
}
con.Close();
return s;
}
}
btw. DON'T swallow exceptions ! I leave your code the same but please don't do that, it's also evil, another thing is if there is a exception in your addElement method your connection will not be closed, use Using statement.
that doesn't sound safe at all, maybe one database with several user tables to store the logfiles for each user, but this just doesn't sound right to me.
otherwise a variable that is assigned randomly when the application is started in place of the database name when it is created.
but if you do something wrong there are going to be a lot of databases out there, but it looks like you have figured out sizing and some other things to keep them from overpowering the server machine.
Additional Information from Comment
if you are going to use tables on the Database(which I think is what you really need) then create the database separate and then create randomly named tables inside your application every time it is opened, you may want to have another table that would keep track of the the tables and the times they were opened as well, perhaps even what user opened them and such things like that

Generate database creation scripts

Is it possible to generate the database creation scripts for a SQL server database from .NET?
I am using C# and I would like to create some sort of an installer project for my application
on which I can select an existing database, generate the creation scripts and run them on another SQL server instance.
Yes, it is possible.
It's easy to do this with SMO, see Transfer class for scripting operations and Database class for database operations (create, drop, etc). Usage looks like this:
private StringCollection GetTransferScript(Database database)
{
var transfer = new Transfer(database);
transfer.CopyAllObjects = true;
transfer.CopyAllSynonyms = true;
transfer.CopyData = false;
// additional options
transfer.Options.WithDependencies = true;
transfer.Options.DriAll = true;
transfer.Options.Triggers = true;
transfer.Options.Indexes = true;
transfer.Options.SchemaQualifyForeignKeysReferences = true;
transfer.Options.ExtendedProperties = true;
transfer.Options.IncludeDatabaseRoleMemberships = true;
transfer.Options.Permissions = true;
transfer.PreserveDbo = true;
// generates script
return transfer.ScriptTransfer();
}
if you want to create database dynamically with c# code then here is the code:
you can do it like this also:
String Connectionstring = CCMMUtility.CreateConnectionString(false, txt_DbDataSource.Text, "master", "sa", "happytimes", 1000);
SqlConnection con = new SqlConnection();
con.ConnectionString = Connectionstring;
bool resultdbexistencx = CCMMUtility.CheckDatabaseExists(con, txt_DbName.Text);
if (!resultdbexistencx)
{
// if not exists create it check the user name for sub-admin avialibe or not.
if (txt_DbName.Text.Trim() == string.Empty) return;
string strDbCreate;
strDbCreate = "CREATE DATABASE " + txt_DbName.Text + " ON PRIMARY " +
"(NAME = " + txt_DbName.Text + "_Data, " +
"FILENAME = 'D:\\" + txt_DbName.Text + "Data.mdf', " +
"SIZE = 4MB, MAXSIZE = 10GB, FILEGROWTH = 100%) " +
"LOG ON (NAME = " + txt_DbName.Text + "_Log, " +
"FILENAME = 'D:\\" + txt_DbName.Text + ".ldf', " +
"SIZE = 4MB, " +
"MAXSIZE = 10GB, " +
"FILEGROWTH = 100%)";
SqlConnection sqlconn = new SqlConnection(Connectionstring);
SqlCommand cmd = new SqlCommand(strDbCreate, sqlconn);
try
{
sqlconn.Open();
sqlconn.ChangeDatabase("master");
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Int32 dbRollbackResult = RollBackTheWholetransaction(txt_DbName.Text.Trim(), Convert.ToInt32(HospitalResult));
if (dbRollbackResult == 1)
{
Response.Write(ex.Message);
lblMessage.DisplayMessage(StatusMessages.ErrorMessage, "There is some problem while generating the database or database name doesn't avialible.");
}
}
Here is the code of "RollBackTheWholetransaction" method :
private Int32 RollBackTheWholetransaction(String DbName, Int32 HospitalId)
{
Int32 result = 0;
try
{
String Connectionstring = CCMMUtility.CreateConnectionString(false, txt_DbDataSource.Text, "master", "sa", "happytimes", 1000);
SqlConnection con = new SqlConnection();
con.ConnectionString = Connectionstring;
String sqlCommandText = "ALTER DATABASE [" + DbName + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE";
String sqlCommandText1 = "DROP DATABASE [" + DbName + "]";
if (con.State == ConnectionState.Closed)
{
con.Open();
SqlConnection.ClearPool(con);
con.ChangeDatabase("master");
SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con);
sqlCommand.ExecuteNonQuery();
SqlCommand sqlCommand1 = new SqlCommand(sqlCommandText1, con);
sqlCommand1.ExecuteNonQuery();
ClsHospitals objHospiitals = new ClsHospitals();
String resultDbdelete = objHospiitals.DeleteHospital(HospitalId, Session["devSuperAdmin"].ToString());
if (resultDbdelete == "1")
{
result = 1;
}
else
{
result = 2;
}
}
else
{
SqlConnection.ClearPool(con);
con.ChangeDatabase("master");
SqlCommand sqlCommand = new SqlCommand(sqlCommandText, con);
sqlCommand.ExecuteNonQuery();
SqlCommand sqlCommand1 = new SqlCommand(sqlCommandText1, con);
sqlCommand1.ExecuteNonQuery();
}
con.Close();
con.Dispose();
result = 1;
}
catch (Exception ex)
{
result = 0;
}
return result;
}
And here is the code to check existence of db in Database :
public static bool CheckDatabaseExists(SqlConnection tmpConn, string databaseName)
{
string sqlCreateDBQuery;
bool result = false;
try
{
// tmpConn = new SqlConnection("server=(local)\\SQLEXPRESS;Trusted_Connection=yes");
sqlCreateDBQuery = string.Format("SELECT database_id FROM sys.databases WHERE Name = '{0}'", databaseName);
using (tmpConn)
{
using (SqlCommand sqlCmd = new SqlCommand(sqlCreateDBQuery, tmpConn))
{
if (tmpConn.State == System.Data.ConnectionState.Open)
{
tmpConn.Close();
tmpConn.Dispose();
}
tmpConn.Open();
tmpConn.ChangeDatabase("master");
int databaseID = (int)sqlCmd.ExecuteScalar();
tmpConn.Close();
result = (databaseID > 0);
}
}
}
catch (Exception ex)
{
result = false;
}
return result;
}
its the working code, hope it will work for you too....
You have to create your own installer by coding it all yourself. there are frameworks out there that make it much easyier.
like Windows Installer XML (WiX)
Windows installer
and more...
I would suggest you to have a look at WiX, worked with it and its quite easy and you can do much. Can be integrated in Visual Studio

How to backup database (SQL Server 2008) in C# without using SMO?

I have this code and it is not working but I don't why?
try
{
saveFileDialog1.Filter = "SQL Server database backup files|*.bak";
saveFileDialog1.Title = "Database Backup";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
SqlCommand bu2 = new SqlCommand();
SqlConnection s = new SqlConnection("Data Source=M1-PC;Initial Catalog=master;Integrated Security=True;Pooling=False");
bu2.CommandText = String.Format("BACKUP DATABASE LA TO DISK='{0}'", saveFileDialog1.FileName);
s.Open();
bu2.ExecuteNonQuery();
s.Close();
MessageBox.Show("ok");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
and I get this error :
What is the problem?
You need to assign that SqlConnection object to the SqlCommand - try this code:
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string connStr = "Data Source=M1-PC;Initial Catalog=master;Integrated Security=True;Pooling=False";
using(SqlConnection conn = new SqlConnection(connStr))
{
string sqlStmt = String.Format("BACKUP DATABASE LA TO DISK='{0}'", saveFileDialog1.FileName);
using(SqlCommand bu2 = new SqlCommand(sqlStmt, conn))
{
conn.Open();
bu2.ExecuteNonQuery();
conn.Close();
MessageBox.Show("ok");
}
}
}
You never tell your SqlCommand which connection to use (this is what the error message says by the way, did you read it?). Either set the Connection property or use SqlConnection.CreateCommand to create the command in the first place.
Backup Sql Server 2008 database in C#(100% correct)
using System.Data.SqlClient;
try{
SqlConnection con = new SqlConnection(cs.conn());
string database = con.Database.ToString();
string datasource = con.DataSource.ToString();
string connection = con.ConnectionString.ToString();
string file_name =data_loaction+database_name;
--- "D:\\Hotel BackUp\\" + database + day + month + year + hour + minute + second + ms + ".bak";
con.Close();
con.Open();
string str = "Backup Database [" + database + "] To Disk =N'" + file_name + "'";// With Format;' + char(13),'') From Master..Sysdatabases Where [Name] Not In ('tempdb','master','model','msdb') and databasepropertyex ([Name],'Status') = 'online'";
SqlCommand cmd1 = new SqlCommand(str, con);
int s1 = cmd1.ExecuteNonQuery();
con.Close();
if (s1 >= -1)
MessageBox.Show("Database Backup Sucessfull.", "Hotel Management", MessageBoxButtons.OK, MessageBoxIcon.Information);
else{
MessageBox.Show("Database Backup Not Sucessfull.", "Hotel Management", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}

Categories