I trying to make backup and restore as a start i am trying to get backup database so write a code like this
try
{
string cbdfilename = "c:\\Bbcon.bak";
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\BbCon.mdf;Integrated Security=True;Connect Timeout=30;");
string sql = "Backup database #DBNAME to Disk = #FILENAME with Format";
SqlConnection.ClearAllPools();
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#DBNAME", "BbCon");
cmd.Parameters.AddWithValue("#FILENAME", cbdfilename);
con.Open();
try
{
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show("Backup DB failed" + ex.ToString());
}
finally
{
con.Close();
con.Dispose();
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
but when i run this code i get an error database BbCon not exist check your database i don't know what is problem for sure but i think i have given wrong path to database I know the path od database correctly it is like
C:\Users\Mahdi Rashidi\AppData\Local\Apps\2.0\NOL11TLW.9XG\CZM702AQ.LPP\basu..tion_939730333fb6fcc8_0001.0002_fd707bbb3c97f8d3
but this project is for some other clients so when i install this software to other computer path will change so i will get an error so i am begging you all to help finding me a better solution for creating a backup programattically
I recommend you to create an app.config file and put the backup target path there
OR
What I did some time ago (to load assemblies dynamically, but this piece of code allows u to retrieve the path location based on the assembly that you're running) it was something like:
(Don't forget to add System.Reflection to your using list)
// get the current assembly from cache
var currentAssembly = Assembly.GetEntryAssembly();
// if current assembly is null
if (currentAssembly == null)
{
// get the current assembly from stack trace
currentAssembly = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly;
}
// get the assemblies path (from returned assembly)
assembliesPath = Path.GetDirectoryName(currentAssembly.Location);
From that point now you can concatenate you "Data Path" and save your data there.
Hope it helps.
Related
i am testing my sqlite local server with c#, I have the connection and query setup without problem. I tried to copy the query to sqlite and it runs without problem. However, when I run it in my program, nothing insert into the db. Wondering what the problem is.
I have set the db build action to Content, and the copy to output directory options to copy if newer
private void insertIntoDB(string query)
{
using (System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("data source=.\\VHTDatabase.db"))
{
using (System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand(conn))
{
conn.Open();
Console.WriteLine(query);
cmd.CommandText = query;
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
Try a full path to your database in your Connectionstring
Then maybe try to add the CommandText before you open the Connection.
i mean:
cmd.CommandText = query;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Does your database give you informations with SELECT?
Maybe you need to reconfigure the User of the Database and give him rights to write, change and delete.
If nothing helps, then you can check, if it gives you an error.
try
{
cmd.CommandText = query;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
I am building a inventory based application that can be directly run from any pc without any installation and so i am using SQL CE.. On Start, I am checking if database is present. If Not i am creating new database as :
try
{
string conString = "Data Source='ITM.sdf';LCID=1033;Password=ABCDEF; Encrypt = TRUE;";
SqlCeEngine engine = new SqlCeEngine(conString);
engine.CreateDatabase();
return true;
}
catch (Exception e)
{
//MessageBox.Show("Database Already Present");
}
The database is created properly and i can access the database to create tables as well.. The Problem i am facing is - I am inserting and updating records in windows form on button click with code :
using (SqlCeConnection connection = new SqlCeConnection(DatabaseConnection.connectionstring))
{
connection.Open();
String Name = NameTxt.Text.ToString();
String Phone = PhoneTxt.Text.ToString();
double balance = Double.Parse(BalanceTxt.Text.ToString());
String City = CityTxt.Text.ToString();
string sqlquery = "INSERT INTO Customers (Name,Phone,Balance,City)" + "Values(#name,#phone, #bal, #city)";
SqlCeCommand cmd = new SqlCeCommand(sqlquery, connection);
cmd.Parameters.AddWithValue("#name", Name);
cmd.Parameters.AddWithValue("#phone", Phone);
cmd.Parameters.AddWithValue("#bal", balance);
cmd.Parameters.AddWithValue("#city", City);
int x = cmd.ExecuteNonQuery();
if (x > 0)
{
MessageBox.Show("Data Inserted");
}
else
{
MessageBox.Show("Error Occured. Cannot Insert the data");
}
connection.Close();
}
and Updation Code is
using (SqlCeConnection connection = new SqlCeConnection(DatabaseConnection.connectionstring))
{
connection.Open();
int idtoedit = select_id_edit;
String Name = NameEditTxt.Text.ToString();
String Phone = metroTextBox1.Text.ToString();
String City = CityEditTxt.Text.ToString();
string sqlquery = "Update Customers Set Name = #name, Phone = #phone,City = #city where Id = #id";
SqlCeCommand cmd = new SqlCeCommand(sqlquery, connection);
cmd.Parameters.AddWithValue("#name", Name);
cmd.Parameters.AddWithValue("#phone", Phone);
cmd.Parameters.AddWithValue("#id", idtoedit);
cmd.Parameters.AddWithValue("#city", City);
int x = cmd.ExecuteNonQuery();
if (x > 0)
{
MessageBox.Show("Data Updated");
}
else
{
MessageBox.Show("Error Occured. Cannot Insert the data");
}
loadIntoGrid();
connection.Close();
}
Whenever i execute code for inserting and updating records - Records are reflected in datagrid filled with adapter from database table. But once i restart the application, values do not appear in database. Once in a million, values are reflected in database. I cannot understand the reason behind this issue.
I have reffered to these articles :
C# - ExecuteNonQuery() isn't working with SQL Server CE
Insert, Update, Delete are not applied on SQL Server CE database file for Windows Mobile
But since i am creating database programmatically - It is getting created directly to bin/debug directory and i cannot see it in solution explorer in visual studio for changing copy options
You probably rewrite your database file with a blank copy from your project.
See this answer. You should not store your database in a bin folder, rather you should find a place in user's or public profile in AppData or another folder, depending on your needs.
The connection string would look like this:
<connectionStrings>
<add name="ITMContext" connectionString="data source=|DataDirectory|\ITM.sdf';LCID=1033;Password=ABCDEF; Encrypt = TRUE;" providerName="System.Data.SqlServerCe.4.0">
You shuld deploy your db file with your custom code run at app's starup to a chosen location, see this ErikEJ blog: http://erikej.blogspot.cz/2013/11/entity-framework-6-sql-server-compact-4_25.html
private const string dbFileName = "Chinook.sdf";
private static void CreateIfNotExists(string fileName)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
// Set the data directory to the users %AppData% folder
// So the database file will be placed in: C:\\Users\\<Username>\\AppData\\Roaming\\
AppDomain.CurrentDomain.SetData("DataDirectory", path);
// Enure that the database file is present
if (!System.IO.File.Exists(System.IO.Path.Combine(path, fileName)))
{
//Get path to our .exe, which also has a copy of the database file
var exePath = System.IO.Path.GetDirectoryName(
new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath);
//Copy the file from the .exe location to the %AppData% folder
System.IO.File.Copy(
System.IO.Path.Combine(exePath, fileName),
System.IO.Path.Combine(path, fileName));
}
}
Check also this post.
You have several options to change this behavior. If your sdf file is
part of the content of your project, this will affect how data is
persisted. Remember that when you debug, all output of your project
(including the sdf) if in the bin/debug folder.
You can decide not to include the sdf file as part of your project and manage the file location runtime.
If you are using "copy if newer", and project changes you make to the database will overwrite any runtime/debug changes.
If you are using "Do not copy", you will have to specify the location in code (as two levels above where your program is running).
If you have "Copy always", any changes made during runtime will always be overwritten
The database file in your project can be different when debugging or not. Check also this answer. You might be writting your records to another copy of the database file.
This question is answered many times in Stackoverflow, But I didn't get proper solution for my project.
Let me show you my code first:
namespace ConsoleDBManagement
{
class Program
{
static void Main(string[] args)
{
//Metioned here your database name
string dbname = "newDb";
SqlConnection sqlcon = new SqlConnection();
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
sqlcon.ConnectionString = #"Server=ABC-PC\SQLEXPRESS;database=" + dbname + ";uid=dran;pwd=sri;";
//Enter destination directory where backup file stored
string destdir = "D:\\Working Projects";
//Check that directory already there otherwise create
if (!System.IO.Directory.Exists(destdir))
{
System.IO.Directory.CreateDirectory("D:\\Working Projects");
}
try
{
//Open connection
sqlcon.Open();
//query to take backup database
//System.IO.File.Create("D:\\Working Projects\\FullBackUp.BAK");
sqlcmd = new SqlCommand("backup database newDb to disk='" + destdir + "\\FullBackUp.BAK'", sqlcon);
sqlcmd.ExecuteNonQuery();
//Close connection
sqlcon.Close();
//Response.Write("Backup database successfully");
}
catch (Exception ex)
{
//Response.Write("Error During backup database!");
}
}
}
}
I am getting exception while query executed.
Cannot open backup device 'D:\Working Projects\FullBackUp.BAK'. Operating system error 3 (The system cannot find the path specified.).
BACKUP DATABASE is terminating abnormally.
Please give me your suggestions.
When you run backup and/or other external file related commands when using a SQL auth login, the Windows security context is that of the SQL Service.
Your question is duplicate of Backup Permissions. Either grant permission for the SQL Service account/group, or run the backups using a Windows auth login that has permissions to the path.
I have a mssql database on remote machine and backup file for this database. I want to create a method (c#) for restoring of database from backup. I will execute my method on my local machine. Can somebody help me to create such method for restoring remote database?
Try the this:
public void RestoreDatabase(string fileName)
{
try
{
using (SqlConnection conn = new SqlConnection("connectionString"))
{
string sql = "RESTORE DATABASE YourDatabase FROM DISK = N''" + fileName;
conn.Open();
SqlCommand _command = new SqlCommand(sql, conn);
_command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
throw;
}
}
You call it this way :
RestoreDatabase(#"\\remotemachine\...\YourFile.bak");
NB: Put an actual path for where the file is located
I cannot save data in access 2007. I tried the following:
Add a password to my DB; didn't work
Saved the db as a 2003 file; didn't work
Here is my code:
public bool ExecuteUDI(string query)
{
Command = new OleDbCommand();
Command.Connection = Connection;
Command.CommandText = query;
Command.CommandType = System.Data.CommandType.Text;
try
{
// Open connection
Open();
if (Command.ExecuteNonQuery() != -1)
return true;
else
return false;
}
catch (Exception e)
{
mError = "ExecuteUDI - " + e.Message;
return false;
}
finally
{
// Always close connection
Close();
}
}
When I add breakpoints, I see my query looks good:
INSERT INTO DVD (Titel) VALUES ('Elegy')
I don't get any errors, but the affected rows is 0. How come? I dont understand..
Where is your mdb file located in relation to your code? I have had issues in the past that having the mdb file in the project folder will in essence create a local copy of the db in memory when the app is running, but nothing is actually written back to the mdb in the folder...
I recommend putting the mdb file outside your project's folder. That should work.