How to restore SQL localDB programmatically - c#

I'm trying to create backup and restore functionality to my Windows form application.
So, I've tried to do a database restore. My code is like this:
string cbdfilename = "c:\\Users\\Public\\Public Document";
SqlConnection.ClearAllPools();
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\BbCon.mdf;Integrated Security=True;Connect Timeout=30;");
string sql;
sql = "Use master;Alter Database BbCon Set Single_User With Rollback Immediate;Restore Database BbCon From Disk = #FILENAME With Replace;Alter Database BbCon Set Multi_User;";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#FILENAME", cbdfilename);
con.Open();
try
{
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show("Restore DB failed" + ex.ToString());
}
finally
{
con.Close();
con.Dispose();
}
But when I try to run this, I get an error:
Restore db failed System.Data.SqlClient.SqlException(0X80131904):userdoesnot have permission to alter database BbCon.mdf the database doesnot exist or or datbase is not in a state that allows access checks.
Can anyone help me please?

Are you trying to Backup or Restore? You mention Backup in the Title and the commmand is for Restore.
There're not many example cases for localDB yet.
Utilize my code as below. Hope this helps..
For Backup-
string master_ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;Database=Master;Integrated Security=True;Connect Timeout=30;";
using (SqlConnection masterdbConn = new SqlConnection())
{
masterdbConn.ConnectionString = master_ConnectionString;
masterdbConn.Open();
using (SqlCommand multiuser_rollback_dbcomm = new SqlCommand())
{
multiuser_rollback_dbcomm.Connection = masterdbConn;
multiuser_rollback_dbcomm.CommandText= #"ALTER DATABASE yourdbname SET MULTI_USER WITH ROLLBACK IMMEDIATE";
multiuser_rollback_dbcomm.ExecuteNonQuery();
}
masterdbConn.Close();
}
SqlConnection.ClearAllPools();
using (SqlConnection backupConn = new SqlConnection())
{
backupConn.ConnectionString = yourConnectionString;
backupConn.Open();
using (SqlCommand backupcomm = new SqlCommand())
{
backupcomm.Connection = backupConn;
backupcomm.CommandText= #"BACKUP DATABASE yourdbname TO DISK='c:\yourdbname.bak'";
backupcomm.ExecuteNonQuery();
}
backupConn.Close();
}
For Restore-
string master_ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;Database=Master;Integrated Security=True;Connect Timeout=30;";
using (SqlConnection restoreConn = new SqlConnection())
{
restoreConn.ConnectionString = master_ConnectionString;
restoreConn.Open();
using (SqlCommand restoredb_executioncomm = new SqlCommand())
{
restoredb_executioncomm.Connection = restoreConn;
restoredb_executioncomm.CommandText = #"RESTORE DATABASE yourdbname FROM DISK='c:\yourdbname.bak'";
restoredb_executioncomm.ExecuteNonQuery();
}
restoreConn.Close();
}
Update-
Oops, sorry, my code is for SQL localDB 2014 but it seems you're using 2012.
Kindly replace (LocalDB)\MSSQLLocalDB to (LocalDB)\v11.0
And kindly just try with above change.
And for your information, as per my experience, if I wrote |Data Directory| in my connectionString, I could only read (SQL SELECT command) the Database. In other word to say, the Insert and Update commands could be done but the database was not inserted or updated actually without any exception. I think setting as |Data Directory| would make the database as read-only and I've found some people were having difficulties to insert or update to database with |Data Directory| setting.
Hope your good days ! Thanks !

Related

How to insert data into local database using C#

I am working on my first project using local database on C#. I have searched on internet different code for inserting data, but nothing has worked for me. I am trying different code, the problem that occurs to me is the built in functions they are using doesn't show up in my code. Can someone share the authentic code for inserting, retrieving and deleting in local database ?
The recent code that I have tried, some exception is occurring in SqlCeConnection.
This is my code :
string str="Data Source=(localdb)shop_database;Initial Catalog=shop_database;Integrated Security=True";
SqlCeConnection con = new SqlCeConnection(str);
SqlCeDataAdapter sda = new SqlCeDataAdapter();
SqlCeCommand cmd = con.CreateCommand();
cmd.CommandText = "Insert into Account_details (Account_No,Customer_name,Customer_father_name,Profession,Mobile_No,Office_Address,House_Address,CNIC,Item_name,Item_color,Item_model,Item_engine_NO,Item_chasis_NO,Cash_price,Installment_price,Advance_given,Amount_left,Monthly_Installment,Monthly_Rent,Date_of_giving,Sponsor_name,Sponsor_father_name,Sponsor_profession,Sponsor_Address,Sponsor_CNIC,Sponsor_Mobile_No) values (#Account_No,#Customer_name,#Customer_father_name,#Profession,#Mobile_No,#Office_Address,#House_Address,#CNIC,#Item_name,#Item_color,#Item_model,#Item_engine_NO,#Item_chasis_NO,#Cash_price,#Installment_price,#Advance_given,#Amount_left,#Monthly_Installment,#Monthly_Rent,#Date_of_giving,#Sponsor_name,#Sponsor_father_name,#Sponsor_profession,#Sponsor_Address,#Sponsor_CNIC,#Sponsor_Mobile_No)";
cmd.Parameters.AddWithValue("#Account_No", this.Textbox0.Text);
cmd.Parameters.AddWithValue("#Customer_name", this.Textbox1.Text);
cmd.Parameters.AddWithValue("#Customer_father_name", this.Textbox2.Text);
cmd.Parameters.AddWithValue("#Profession", this.Textbox3.Text);
cmd.Parameters.AddWithValue("#Mobile_No", this.Textbox4.Text);
cmd.Parameters.AddWithValue("#Office_Address", this.Textbox5.Text);
cmd.Parameters.AddWithValue("#House_Address", this.Textbox6.Text);
cmd.Parameters.AddWithValue("#CNIC", this.Textbox7.Text);
cmd.Parameters.AddWithValue("#Item_name", this.Textbox14.Text);
cmd.Parameters.AddWithValue("#Item_color", this.Textbox15.Text);
cmd.Parameters.AddWithValue("#Item_model", this.Textbox16.Text);
cmd.Parameters.AddWithValue("#Item_engine_NO", this.Textbox17.Text);
cmd.Parameters.AddWithValue("#Item_chasis_NO", this.Textbox18.Text);
cmd.Parameters.AddWithValue("#Cash_price", this.Textbox19.Text);
cmd.Parameters.AddWithValue("#Installment_price", this.Textbox20.Text);
cmd.Parameters.AddWithValue("#Advance_given", this.Textbox21.Text);
cmd.Parameters.AddWithValue("#Amount_left", this.Textbox25.Text);
cmd.Parameters.AddWithValue("#Monthly_Installment", this.Textbox22.Text);
cmd.Parameters.AddWithValue("#Monthly_Rent", this.Textbox23.Text);
cmd.Parameters.AddWithValue("#Date_of_giving", this.Textbox24.Text);
cmd.Parameters.AddWithValue("#Sponsor_name", this.Textbox8.Text);
cmd.Parameters.AddWithValue("#Sponsor_father_name", this.Textbox9.Text);
cmd.Parameters.AddWithValue("#Sponsor_profession", this.Textbox10.Text);
cmd.Parameters.AddWithValue("#Sponsor_Address", this.Textbox11.Text);
cmd.Parameters.AddWithValue("#Sponsor_CNIC", this.Textbox12.Text);
cmd.Parameters.AddWithValue("#Sponsor_Mobile_No", this.Textbox13.Text);
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
To edit, insert, in general interact with your database you need the class SqlCommand. First you create a connection to your database with an SqlConnection object. Then you pass the SQL statement as a string and the connection into the constructor of the SqlConnection class. Little example:
SqlConnection con = new SqlConnection("server=localhost;database=test_db;uid=root;password=yourpassword");
SqlCommand cmd = new SqlCommand("select * from your_table", con);
To retreive the data from the database you need to use the SQL Statements. For example an SQL statement is something like:
insert into my_table (value1, value2)
values("Example", "Insertion");
When you created your SqlConnection and the SqlCommand you need to open the database connection and execute the command. Wether it's a command for receiving information from the database or editing the database you use ExecuteReader() or ExecuteNonQuery(). For example when you want to receive all the Information stored in one table you use:
SqlConnection con = new SqlConnection("connection string as shown above");
SqlCommand cmd = new SqlCommand("select * from example_table", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
Console.WriteLine(reader[<table_index or attribute Name>]);
And finally dont forget to call the close method on your SqlConnection and SqlDataReader object
You are probably making two mistakes:
Problem 1. Your connecting string looks like wrong. Instead of:
Data Source=(localdb)shop_database;Initial Catalog=shop_database;Integrated Security=True";
It should be:
Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=shop_database;Integrated Security=True";
Problem 2. You are not opening the connection before executing the command. Your code in the block should be like this:
try
{
conn.Open(); // Open the connection
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close(); // Close the connection
}
As a best practice, I recommend that you use "using" block to create your connection. In that case, you don't have to explicitly close the connection and set it to null:
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
conn.Open();
// Remaining code
}
}
catch(Exception ex)
{
// Manage your exception here
}

Open database into application c#

I have added a SQL Server .mdf database file to my C# application, but when I try to connect with this code, the program causes a connection error.
CODE:
DataSet data;
string con = "Data Source=dbinterno.mdf;";
string queryString = "Select * FROM Dati";
try
{
using (SqlConnection connection = new SqlConnection(con))
{
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand command = new SqlCommand(queryString, connection);
command.ExecuteNonQuery();
data = new DataSet();
adapter.Fill(data);
MessageBox.Show(data.ToString());
connection.Close();
}
}
catch
{
MessageBox.Show("\n Problemi di connessione al database");
}
The error is:
ERROR IMAGE
Here are a couple observations:
Your connection string will need to be modified. Try using
string con = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;";
using Windows Authentication or this:
string con = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;
Password=myPassword;"; using standard security, Source: connectionstrings.com. This should be managed some other way than in code as well. Desktop applications can be de-compiled, and if the password changes, you would need a rebuild. In a ASP.NET application, Microsoft advises to use a web.config file or in the windows registry using a custom subkey.
You will want to use ExecuteReader() for a SELECT statement as ExecuteNonQuery() will not return a result set. See this answer that describes the differences in the types of SQL Server methods
you don't need connection.Close();, the using statement will handle that.

Getting Error while connecting to DB using c#

Is there anything wrong with this code? Please help me out.
protected void Button_Click(object sender, EventArgs e)
{
string cs = "Data Source=SFSIND0402;Initial Catalog=TestDB;Integrated Security=SSPI;Provider=Microsoft.ACE.OLEDB.12.0";
OleDbConnection conn = new OleDbConnection(cs);
conn.Open();
OleDbCommand insert = conn.CreateCommand();
insert.CommandText="insert into Employee(ID, Name, Sex, Salary) values('003','Vedpathi','M',25000)";
insert.Connection = conn;
insert.ExecuteNonQuery();
conn.Close();
}
I am getting the following error:
Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done
(on line 22:conn.Open();)
When connecting to an MS SQL database, use the MS SQL providers:
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var cmd = new SqlCommand(commandText, connection);
cmd.ExecuteNonQuery();
}
In addition to the solution Luaan mentioned, you should store your connection string in the config file of the app and also encrypt it.
Even if you use SSL encryption when communicating with the DB, an ill-indended person can extract the string variables, if he / she runs the application on his / her machine.

How I create a SQL Server Compact 3.5 .sdf file and connect to it?

I have created a SQL Server Compact Database (.sdf file) and I want to be connected to it for do some insert , delete ... .
This is my creation code for it:
if (File.Exists(dbfilename))
File.Delete(dbfilename);
string connectionString = "Data Source=" + dbfilename + """;
SqlCeEngine engine = new SqlCeEngine(connectionString);
engine.CreateDatabase();
engine.Dispose();
SqlCeConnection conn = null;
try
{
conn = new SqlCeConnection(connectionString);
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "CREATE TABLE Contacts (ID uniqueidentifire, Address ntext)";
cmd.ExecuteNonQuery();
}
catch { }
finally
{
conn.Close();
}
Is it true?
How can I connect to it?
That connection string is broken.
"
is not a valid entity where you are trying to use it. Fix your connection string.
Also, you will need to associate the command with the connection, either in the constructor or after the fact.
Please read through an example such as this one, which was the first google result for "connect sql compact example c#":

Looking for code which will let me backup SQL Server 2005/2008/2008R2 database inside C# tests (MSTest)

I have found a starting point below, but I worry that I can miss calls to CreateDbBackup() and RestoreDbBackup(). I was hoping that I could write and use an attribute on my tests. Is this possible? How? I am using MSTest library and C# 4.0.
http://www.linglom.com/2008/01/12/how-to-backup-and-restore-database-on-microsoft-sql-server-2005/
internal void CreateDbBackup()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConStr"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = string.Format(#"BACKUP DATABASE [MyDatabase] TO DISK = N'{0}' WITH INIT , NOUNLOAD , NOSKIP , STATS = 10, NOFORMAT", UtilityClassGeneral.DbBackupPath);
con.Open();
cmd.ExecuteNonQuery();
}
}
internal void RestoreDbFromBackup()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConStr"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
con.Open();
// Make sure to get exclusive access to DB to avoid any errors
cmd.CommandText = "USE MASTER ALTER DATABASE [MyDatabase] SET SINGLE_USER With ROLLBACK IMMEDIATE";
cmd.ExecuteNonQuery();
cmd.CommandText = string.Format(#"RESTORE DATABASE [MyDatabase] FROM DISK = N'{0}' WITH FILE = 1, NOUNLOAD , STATS = 10, RECOVERY , REPLACE", UtilityClassGeneral.DbBackupPath);
cmd.ExecuteNonQuery();
}
}
Have a look at SQL Server Management Objects (SMO). You should be able to use this to backup and restore SQL Server databases.

Categories

Resources