Connection string and sql backup - c#

I'm having problem with the following C# code to perform a backup, particularly in the connection string.
The code is as follows:
private void BK()
{
string strconn = #"Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = strconn;
try {
//Query per backup
string queryBK = "BACKUP DATABASE db TO DISK ='C:\\Program Files\\Microsoft SQLServer\\MSSQL10.SQLEXPRESS\\MSSQL\\Backup\\db.bak' WITH INIT, SKIP, CHECKSUM";
SqlCommand cmdBK = new SqlCommand(queryBK, conn);
conn.Open();
cmdBK.ExecuteNonQuery();
MessageBox.Show("backup effettuato");
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "ERRORE", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally {
conn.Close();
}
}
This code works on the development PC, but if I install my application on another PC it throws this error:
The database does not exist. Verify that the name has been entered
correctly. INTERRUPTION ANOMALOUS BACKUP DATABASE.
I would stress that this string works well with the operations INSERT, DELETE, UPDATE
on both my PC and on the PC test.
If I replace the connection string with:
string strconn = #"Data Source=.\SQLEXPRESS; Database = db;Trusted_Connection =True";
The string works on my dev machine but not on the test machine. It throws the following error:
Can not open database requested by the login. Login failed. Login
failed for user Pina-PC \ Pina

Dear fellow you can use your code in this way.
private void BK()
{
string strconn = #"Data Source=.\SQLEXPRESS; AttachDbFilename=|DataDirectory|\db.mdf;Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = strconn;
try {
// First get the db name
conn.Open();
string dbname;
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
dbname = cmd.Connection.Database.ToString();
//Query per backup
string queryBK = "BACKUP DATABASE " + dbname + " TO DISK ='C:\\Program Files\\Microsoft SQLServer\\MSSQL10.SQLEXPRESS\\MSSQL\\Backup\\db.bak' WITH INIT, SKIP, CHECKSUM";
SqlCommand cmdBK = new SqlCommand(queryBK, conn);
conn.Open();
cmdBK.ExecuteNonQuery();
MessageBox.Show("backup effettuato");
}
catch (Exception ex) {
MessageBox.Show(ex.Message, "ERRORE", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally {
conn.Close();
}
}
this routine will work in your case.

Related

Connection string for local database in C#

Maybe it's repetitive but I googled and didn't find my answer.
I developed a program by .net that has a local database (Express) that works excellently on my computer, but when I create a setup and installation, it can't insert or update and so on for example in Delete() method I have
try
{
}
catch
{
}
in the exefile always goes to the catch{} section and I don't know why :((
This is my connection string:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;Connect Timeout=30
This is one of my methods for example:
private Boolean Delete(int id)
{
//String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Parnian\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection sql = new SqlConnection(Connection);
String sqll = "Delete FROM TblBank WHERE Id =#id ";
try
{
sql.Open();
SqlCommand cmd = new SqlCommand(sqll, sql);
cmd.Parameters.AddWithValue("id", id);
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
sql.Close();
return true;
}
catch (Exception ex)
{
MessageBoxEx.Show("have some problem", "wrong", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
and Necessary say i put my .mdf and .ldf file into my setup folder and make setup by Visual Studio Installer
Try this
private bool Delete(int id)
{
string connString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Parnian\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection sqlConn = new SqlConnection(connString);
String sql = "Delete FROM TblBank WHERE Id =#id ";
try
{
sqlConn.Open();
SqlCommand cmd = new SqlCommand(sql, sqlConn);
cmd.Parameters.AddWithValue("id", id);
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
sql.Close();
return true;
}
catch (Exception ex)
{
MessageBoxEx.Show(ex.Message, "wrong", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
So that you can see what the error is. At the moment you are just saying something went wrong when ex contains everything you will need to debug the problem.
Hope this helps.
(There are a few things to refactor too, such as wrapping your connection in a using statement.)
The cause of your problem is very simple. There can be two situations in your case. They are as follows:
The computer you are trying to run the application doesn't have the proper version of the sql server.
Solution: In this case, you have to find out in which sql server version you have created your database. Then you have to include that version of sql server into the setup.exe package. So that when the setup.exe executes the proper sql server also setups with your application.
The computer you are trying to setup the application has proper sql version but still you are getting the error.
Solution: First delete your existing database and create new database from solution explorer.Then use this particular connection string given below
SqlConnection conn = new
SqlConnection (global::ProjectName.Properties.Settings.Default.ProjectConnectionString);
ProjectConnectionString can be found in App.config file after you connect your database to your solution.
Hope this helps. Feel free to ask in the comment if you need to.
#Parnian It should required to install local db in your system.
1.when you click server object explorer and then when you click on Localdb server you will get proper connection string from properties .
enter code here static void Main(string[] args)
{
TestConncetion testConncetion = new TestConncetion(Delete);//here I used delegate
WriteLine($"My connection string is working Fine ,result is {testConncetion(1)}");
}
private static bool Delete(int id)
{
string Connection = #"Data Source=(localdb)\ProjectsV13;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
//String conString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Parnian\\documents\\visual studio 2017\\Projects\\Bank\\Bank\\Database.mdf;Integrated Security=True";
SqlConnection sql = new SqlConnection(Connection);
string sqll = "Delete FROM TblBank WHERE Id =#id ";
try
{
sql.Open();
SqlCommand cmd = new SqlCommand(sqll, sql);
cmd.Parameters.AddWithValue("id", id);
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
sql.Close();
return true;
}
catch (Exception ex)
{
WriteLine("have some problem", "wrong", ex.Message);
return false;
}
}

Inserting data into SQL table from asp.net form

I am trying to build a registration web form which saves user data into an SQL table. This is what I have so far:
public static SqlConnection GetConnection()
{
String connection;
connection = #"example/file/path";
return new SqlConnection(connection);
}
protected void submitButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection = GetConnection();
try
{
myConnection.Open();
String myQuery = "INSERT INTO RegistrationDB([firstName], [lastName], [eMail], [dob], [userName], [password]) values ('"
+fNameBox.Text+ "' ,'"+ lNameBox.Text+"' ,'"+emailBox.Text+"' ,'"
+ dobBox.Text+"', '"+userNameBox.Text+"' ,'"+passwordBox.Text+"';)";
SqlCommand myCommand = new SqlCommand(myQuery, GetConnection());
myCommand.ExecuteNonQuery();
myConnection.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
myConnection.Close();
}
}
The error occurs in my GetConnection() method where I return the connection. The error I get is:
An exception of type 'System.ArgumentException' occurred in
System.Data.dll but was not handled in user code
Additional information: Format of the initialization string does not conform to specification starting at index 0.
I do not know how to get past this problem but any help is very appreciated.
Your problem lies in
String connection;
connection = #"example/file/path";
return new SqlConnection(connection);
your connectionString variable (connection in your case) is not set properly, there are multiple ways to do that just to list 2 of the most common ones.
Standard Connection with username and password:
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"User id=UserName;" +
"Password=Secret;";
conn.Open();
Trusted Connection:
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=ServerName;" +
"Initial Catalog=DataBaseName;" +
"Integrated Security=SSPI;";
conn.Open();
You might want to look at this question for example:
How to set SQL Server connection string?
Pijemcolu's answer is correct, but I think several things can be added to enhance your code:
1) use proper names for variables. E.g.: connection string is different from actual connection
public static SqlConnection GetConnection()
{
// if Windows Authentication is used, just get rid of user id and password and use Trusted_Connection=True; OR Integrated Security=SSPI; OR Integrated Security=true;
String connStr = "Data Source=ServerName;Initial Catalog=DataBaseName;User id=UserName;Password=Secret;";
return new SqlConnection(connStr);
}
2) Try to dispose disposable objects (i.e. implement IDisposable) should be properly disposed.
Also, commands should not constructed with string concatenation, but using parameters. This is particularly important when providing direct user input into the query, since malicious users might try to perform queries to compromise the data (read more about SQL injection here).
The connection can be closed only within finally block, since everything there is executed no matter what (exception raised or not in the catch block).
protected void submitButton_Click(object sender, EventArgs e)
{
SqlConnection myConnection = null;
try
{
using (myConnection = GetConnection())
{
myConnection.Open();
String myQuery = #"
INSERT INTO RegistrationDB([firstName], [lastName], [eMail], [dob], [userName], [password])
values (#firstName, #lastName, #eMail, #dob, #userName, #password)";
using (SqlCommand myCommand = new SqlCommand(myQuery, GetConnection())
{
myCommand.Parameters.AddWithValue("#firstName", fNameBox.Text);
myCommand.Parameters.AddWithValue("#lastName", lNameBox.Text);
myCommand.Parameters.AddWithValue("#eMail", emailBox.Text);
myCommand.Parameters.AddWithValue("#dob", dobBox.Text);
myCommand.Parameters.AddWithValue("#userName", userNameBox.Text);
myCommand.Parameters.AddWithValue("#password", passwordBox.Text);
myCommand.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
if (myConnection != null)
myConnection.Close();
}
}
3) Password storage
It looks like your storing password typed by the user. It is strongly recommended to store a representation of the password (some sort of hash that it is easy to compute from a string, but the string is almost impossible to be retrieved from the hash). More details can be found here.

WPF Install Setup and Deployment and sql Script file

I'm currently developing a small WPF application.
I generate sql script file that contains commands to create database and tables, views, procedures and so on.
But where in my wpf code I must put this script or how to read the sql script file during first run and create database and tables? Other if the client choose a diferente folder and directory to install the application how to get a path of sql script file? I use Visual Studio Installer.
void excuteScript()
{
String connString = #"Data Source=.\sqlexpress;Initial Catalog=master;Integrated Security=True";
String cmdText = "select * from master.dbo.sysdatabases where name= 'Teste'";
Boolean bRet;
SqlConnection sqlConnection = new SqlConnection(connString);
SqlCommand sqlCmd = new SqlCommand(cmdText, sqlConnection);
try
{
sqlConnection.Open();
SqlDataReader reader = sqlCmd.ExecuteReader();
bRet = reader.HasRows;
sqlConnection.Close();
}
catch (Exception e)
{
bRet = false;
sqlConnection.Close();
MessageBox.Show(e.Message);
}
if (bRet == true)
{
}
else
{
string sqlConnectionString = "Data Source=(local);Initial Catalog=master;Integrated Security=True";
var file = new FileInfo(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"teste.sql"));
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
}
}

Set database backup file on local machine

POSSIBLE DUPLICATE OF :
How to create SQL Server 2008 database full backup programmatically in desired folder
I have a database on my computer (SQL Server 2008 Express).
I need any sample code in C# that I can use to backup the database to a file using Visual Studio 2010.
Thanks..
i'll using this code to connect Database
public SqlConnection SqlSaverConn()
{
string path = Application.StartupPath + "\\";
String conStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename="+ path +"SMS_DB.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(conStr);
try
{
con.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return con;
}
Just execute SQL Server command
BACKUP DATABASE database_name TO DISK='d:\path\to\backup\file\on\the\server.bak'
from your program
EDIT
public SqlConnection SqlSaverConn()
{
string path = Application.StartupPath + "\\";
String conStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename="+ path +"SMS_DB.mdf;
Integrated Security=True; User Instance=True";
SqlConnection con = new SqlConnection(conStr);
try
{
con.Open();
SqlCommand command;
command = new SqlCommand(#"backup database SMS_DB.mdf to disk ='" + path + "\\" + name, con);
command.ExecuteNonQuery();
MessageBox.Show("Backup Created.");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return con;
}
Try this peice of code.
Im using flowing code to connect database
public SqlConnection SqlSaverConn()
{
string path = Application.StartupPath + "\\";
String conStr = #"Data Source=.\SQLEXPRESS;AttachDbFilename="+ path +"SMS_DB.mdf;Integrated Security=True;User Instance=True";
SqlConnection con = new SqlConnection(conStr);
try
{
con.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
return con;
}
can i use your SQL Command to set backup using upon type connection
This what I did and it Worked!
private void BackupButtonClick(object sender, RoutedEventArgs e)
{
// FILE NAME WITH DATE DISTICNTION
string fileName = string.Format("SchoolBackup_{0}.bak", DateTime.Now.ToString("yyyy_MM_dd_h_mm_tt"));
try
{
// YOUR SEREVER OR MACHINE NAME
Server dbServer = new Server (new ServerConnection("DESKTOP"));
Microsoft.SqlServer.Management.Smo.Backup dbBackup = new Microsoft.SqlServer.Management.Smo.Backup()
{
Action = BackupActionType.Database,
Database = "School"
};
dbBackup.Devices.AddDevice(#backupDirectory() +"\\"+ fileName, DeviceType.File);
dbBackup.Initialize = true;
dbBackup.SqlBackupAsync(dbServer);
MessageBox.Show("Backup", "Backup Completed!");
}
catch(Exception err)
{
System.Windows.MessageBox.Show(err.ToString());
}
}
// THE DIRECTOTRY YOU WANT TO SAVE IN
public string backupDirectory()
{
using (var dialog = new FolderBrowserDialog())
{
var result = dialog.ShowDialog();
return dialog.SelectedPath;
}
}

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