How to backup from .mdf database that created by VS - c#

I was created a .mdf database file with vs 2010. I can retrive and insert data into database bbut when i want to backup error was handled. that database not attach in Management Studio.
my Code :
SqlConnection connect;
connect = new SqlConnection(DAL.AccessLayerClass._connectionStr);
connect.Open();
SqlCommand command;
command = new SqlCommand(#"backup database AGMDB to disk ='d:\svBackUp1.bak' with init,stats=10",connect);
command.ExecuteNonQuery();
connect.Close();
MessageBox.Show("The support of the database was successfully performed", "Back", MessageBoxButtons.OK, MessageBoxIcon.Information);
my connection string:
string _connectionStr = "Data Source=.\\SQLEXPRESS; AttachDbFilename=" + System.Windows.Forms.Application.StartupPath + "\\Database\\AGMDB.mdf; Integrated Security=True; Connect Timeout=30; User Instance=True;";
and that error was occurs:
Could not locate entry in sysdatabases for database 'AGMDB'. No entry found with that name. Make sure that the name is entered correctly.
BACKUP DATABASE is terminating abnormally.
how can i solve this error?
Thanks

You need [] around DBFileName, try this:
SqlConnection connect;
connect = new SqlConnection(DAL.AccessLayerClass._connectionStr);
connect.Open();
SqlCommand command;
command = new SqlCommand(#"backup database [" + System.Windows.Forms.Application.StartupPath + "\\Database\\AGMDB.mdf] to disk ='d:\svBackUp1.bak' with init,stats=10",connect);
command.ExecuteNonQuery();
connect.Close();
MessageBox.Show("The support of the database was successfully performed", "Back", MessageBoxButtons.OK, MessageBoxIcon.Information);
Reference : How to Backup and Restore SQL Express 2005 (AttachDbFilename mode)

Related

Cannot open backup device 'D:\Working Projects\FullBackUp.BAK'. Operating system error 3(The system cannot find the path specified.)

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.

Error with path of Compact Database .sdf in the client computer

I want to publish my project with compact database but I have an error message that says: the path is not exists, I solved it by write this code:
SqlCeConnection connection = new SqlCeConnection("Data Source=|DataDirectory|\\Database1.sdf");
but I don't have result, I mean no delete no select no insert etc..
this my delete code:
SqlCeCommand cmd = new SqlCeCommand("delete from tab ", connection);
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();

How to create a Microsoft SQL Server database by using ADO.NET?

How to create a Microsoft SQL Server database by using ADO.NET and Visual C# .NET programmatically?
I need to create databases programmatically.
I use this code but after creating database, I cannot add a table to this DB due to permission problem
string str = "CREATE DATABASE MyDatabase ON PRIMARY (NAME = MyDatabase_Data, FILENAME = 'C:\\MyDatabaseData.mdf', SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) LOG ON (NAME = MyDatabase_Log, FILENAME = 'C:\\MyDatabaseLog.ldf', SIZE = 1MB, MAXSIZE = 5MB, FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
my code for Creating Table
string path="";// new DB path
string constring = "Data Source=.\\SQLEXPRESS;AttachDbFilename=" + path + ";Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True";
string qry="create table table1 ( ID int, name varchar(20) )";
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
According with your code, you created the database, so ... Before you call the command to create the table, Did you anytime add an "USE DATABASE [DataBaseName]" in your string variable? In my case, I've had to add this code to create the tables. Of course, you must note for the user's permissions of the connection string commented above.
Based on the error description, following steps may work. I assume that your SQL server runs on the same machine as your test program.
Create a worldwide writable directory (C:\mydbdir).
Let the DB file be created there (C:\mydbdir\MyDatabaseData.mdf)
Try to create the tables in the DB
As ta.speot.is noted, you are (very likely) missing write permissions to C:\ for SQL server process.
You created a database but you did not set the permissions to it.
So after database creation add:
var userName = "sa"; // username that is used in the connection
var str = String.Format("USE MyDatabase; EXEC sp_changedbowner '{0}'", userName);
Do a ExecuteNonQuery with this as well and then you have the rights to add tables, etc.
EDIT
Btw: Sidenote: I would just execute
USE master; IF ( NOT(SELECT IsNull(db_id('myDBname'),-1)>0) ) CREATE DATABASE 'myDBname'
and let the SQL server do the rest. Easier to create like this, but it is just another way how to do it.

Struggling to insert record into "SQL Server Compact 4.0 Database" from my C# WinForm Application. (I'm using VS 2010))

In my C# Winform Application I have written a code to insert record into the "SQL Server Compact 4.0 Database". Also I had debug code line-by-line everything is working fine (without any error) but after insert functionality when I checked my database I found that record is not inserted into the database, I'm strange why it is happening..!
But I think it is happening because, "when I tried to add database in my project I got this error" Following is my code to insert record into the database--
// Retrieve the connection string from the settings file.
string conString = Properties.Settings.Default.snda_dbConnectionString;
//string conString = "Data Source=|DataDirectory|\\db_snda.sdf";
try
{
conString = conString +";Password = test#1;";
// Open the connection using the connection string.
using (SqlCeConnection con = new SqlCeConnection(conString))
{
con.Open();
// Read in all values in the table.
using (SqlCeCommand cmd = new SqlCeCommand("INSERT INTO tbl_user_master" + "(user_id, password, user_type, user_title, first_name, middle_name, last_name, gender, dob, mobile_no, email_id, plant_code, div_code, region_code, reporting_to, releaving_date, created_date)" + " VALUES(#user_id, #password, #user_type, #user_title, #first_name, #middle_name, #last_name, #gender, #dob, #mobile_no, #email_id, #plant_code, #div_code, #region_code, #reporting_to, #releaving_date, #created_date)", con))
{
cmd.Parameters.AddWithValue("#user_title", strTitle);
cmd.Parameters.AddWithValue("#first_name", strFirstName);
cmd.Parameters.AddWithValue("#middle_name", strMiddleName);
cmd.Parameters.AddWithValue("#last_name", strLastName);
cmd.Parameters.AddWithValue("#gender", strGender);
cmd.Parameters.AddWithValue("#user_type", strUserType);
cmd.Parameters.AddWithValue("#plant_code", strPlantCode);
cmd.Parameters.AddWithValue("#div_code", strDivCode);
cmd.Parameters.AddWithValue("#region_code", strRegionCode);
cmd.Parameters.AddWithValue("#reporting_to", strReportingTo);
cmd.Parameters.AddWithValue("#user_id", strUserName);
cmd.Parameters.AddWithValue("#password", Encrypt(strPassword)); //Encrypt(strPassword)
cmd.Parameters.AddWithValue("#email_id", strEmailId);
cmd.Parameters.AddWithValue("#mobile_no", strMobileNo);
cmd.Parameters.AddWithValue("#dob", strDOB);
cmd.Parameters.AddWithValue("#created_date", strCreatedDate);
cmd.Parameters.AddWithValue("#releaving_date", strReleavingDate);
cmd.ExecuteNonQuery();
}
con.Close();
XtraMessageBox.Show("User Created Successfully.", "Alert", MessageBoxButtons.OK, MessageBoxIcon.Information);
ResetAfterSubmit();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Thank you...!
It is hapening because you mix up databases - the one you check is not the one that is used during insert as likely when you start the debugging of the program a copys created in the output folder - and then discarded when you stop the program.
This is not exactly a rare problem and a good indication of someone not using a search function to find a solution.

Issue with connectionString. Using Visual studio 2013 pro. trying to connect to employee DB on SQL Server 2012,

I am trying to connect to SQL Server 2012 express. There is a database called employee which I would like to save data from a WPF form to a table called [dbo].[EVUSERS]. It is stored in my local Database. From some examples I see that "Data Source=.\SQLEXPRESS" Is this correct? Or should I specify the table aswell? using localhost as the server doesn't work either.
I get an error saying "the server was not found or was not accessible."
Do I have to configure the server in some way to receive connections?
Here is my attempt.
void saveData()
{
try
{
var firstName = fNameTextbox.Text;
var lastName = LNameTextBox.Text;
var userName = UserName.Text;
String pass = PasswordTextBox.Password;
String confirm = ConfirmTextBox.Password;
int loggedIn = 1;
//parameterise values
string connectionString = #"Data Source=.\SQLEXPRESS;Database=Employee";
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO [dbo].[EVUSERS] (UName, Pass, FName, LName, Attempts, LastLogin, LoggedIn) VALUES (#UName, #Pass, #FName, #LName, #Attempts, #LastLogin, #LoggedIn)";
command.Parameters.AddWithValue("#UName", UserName);
command.Parameters.AddWithValue("#Pass", pass);
command.Parameters.AddWithValue("#FName", firstName);
command.Parameters.AddWithValue("#LName", lastName);
command.Parameters.AddWithValue("#Attempts", attempts);
command.Parameters.AddWithValue("#LastLogin", lastLogIn);
command.Parameters.AddWithValue("#LoggedIn", loggedIn);
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("command number of rows = " + command);
}
//connection.Close();
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
Here is a screenshot of the server connection.
Many Thanks
.\SQLExpress is correct. If the database name is correct (although for SQL Express it should be a path to the file, yes?) then you can add ";Integrated Security=SSPI" to the connection string and you'll be OK if you are the user who installed it.
Can Use It For Connect With Sql Server 2012 :
var connectionString = "Server=127.0.0.1;DataBase=Employee;
User Id=(sa or your user id without Parenthesis);
Password=(your password without Parenthesis);";

Categories