Attaching SQL database behaviors - c#

I am trying to create a setup.exe that installs an application I've written.
The application uses a database to store and retrieve information.
In the setup, I have the installing user supply a Database server\instance, credentials and the DATA directory to copy the database files to.
I want to programmatically and permanently attach the database.
I use the following to programmatically attach a database to my instance.
The con.Open() and con.Close() are just for testing.
System.Data.SqlClient.SqlConnection con;
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = #"Data Source=.\SQLEXPRESS;Integrated Security=true;Connect Timeout=30;User Instance=True";
ServerConnection serverconn = new ServerConnection(con);
Server s = new Server(serverconn);
s.DetachDatabase("DBX2", true, true);
s.AttachDatabase("DBX2", new System.Collections.Specialized.StringCollection { #"C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\DATA\DBX2.mdf", #"C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\DATA\DBX2_log.ldf" }, AttachOptions.None);
con.Open();
MessageBox.Show("Connection Opened");
con.Close();
MessageBox.Show("Connection Closed");
Several questions to just confirm:
I get an error that it is already open, when it tries con.Open(), so does attaching a database this way automatically open it? When I remove the con.open(), it runs through and closes it just fine.
When I attach my database this way, I do not see it attached in the SQL Server Management Studio, like if I were to manually attach it there. So is the database still attached and working after I exit my application, so that other applications can access it? Is attaching this way temporary, or is it just not picked up by the SQL Management Studio?
Is this the correct way to go about achieving what I want?

Each application has it's own independent 'connection string' that provides a way to connect to the same database. SSMS and other client executables are just more of these applications. Of course, each connection string could actually be the same thing as they all point to the same database, they are just stored differently.

Related

I get an error when database is connecting

I have a probleme with the database.
On my computer is working well but when i try to run it from other computer is not working.
This is connection string:
SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\OlxBotDataBase.mdf;Integrated Security=True");
I try to put database in %appdata% folder, but is not working or maybe i'm doing it wrong.
This is the error:
EDIT: I installed sql server, but now i get this error:
you can change permission for mdf and log file so that it can be accessed through your application
I found the solution.
I installed sql server express and atached the database and i modify connectionString like this:
connection = new SqlConnection(#"Data Source=localhost\SQLEXPRESS;Database=OlxBotDataBase;Integrated Security=True");
But i want to know if there is any way to automaticaly add database.

Saving to database from WinForm

I'm having trouble to save details about a movie in my database. I know the name giving is not good, but I have just made 1 textbox for input right now, as I am getting desperate. Can anyone tell me what I have done wrong in my code.
If it helps I having the following error which suggests that it can't connect to my localDB but I am not sure.
Error from code :
Code:
private void btnRes_Click(object sender, EventArgs e)
{
SqlConnection sc = new SqlConnection();
sc.ConnectionString = ("Data Source=localhost;Initial Catalog=LoginScreen;Integrated Security=True");
SqlCommand com = new SqlCommand();
sc.Open();
com.Connection = sc;
com.CommandText = ("INSERT into movieTable (movieID, movieName, movieLength, movieDescription) VALUES ('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"');");
com.ExecuteNonQuery();
sc.Close();
Your local database is not accessible over network. Try the following -
Check whether server is on
Check whether firewall is not blocking the Program
Check whether Named Pipes and TCP/IP is enabled in SQL Configuration manager. To access SQL Configuration Manager, go to Start > SQL Server (Version) > SQL Configuration Manager. Then expand Client Configuration (if it's x64 then there will be 2 item , click that does not have 32 with it).
From the right pane select Named Pipe, Vias and TCP/IP and enable all and restart server.
Make sure you are using correct instance name. MQL Server Enterprise or Standard editions might not have instance names but also can be installed with instance name. See in you SQL configuration manager that you are using the proper instance name.
Then try again.
First of All check the Authentication mode of the Sql Server whether it is in Windows Authentication Mode or SQL Server Authentication Mode
Secondly Check whether the service of the SQL Server is in running state or not
If the SQl Server installation mode is SQl Server Authentication Mode then the connection string used is :
Server=myServerName\myInstanceName;Database=myDataBase;User Id=myUsername;
Password=myPassword;
If the SQL Server installation mode is Windows Authentication then the connection string is :
Initial Catalog=MyDb;Data Source=MyServer;Integrated Security=SSPI;

Inability to connect with database

I use Visual Studio 2012. I created a database using the "Add component" function. I try to connect to it
class DBManager
{
private SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\\Users\\somepath\\Database1.mdf;Integrated Security=True");
public DBManager()
{
using (conn)
{
conn.Open();
}
}
And I get SQL exception on the conn.Open() line. Even after trying to use System.Data.SqlServerCe and changing connection string accordingly it still throws the same exception about file being impossible to open or damaged.
If you are using SQL server your connection string should look like this:
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
Go to connectionstrings.com for more details -- or if you are using a different DB.
If the database you're trying to attach it's already attached, the parameter AttachDbFilename=C:\\Users\\somepath\\Database1.mdf in your connection is useless. Removing it, you will connect to the default database of your instance.
If you're receiving an error because your file is impossible to open or it is damaged, check its integrity, attaching the file using SQL Server Management Studio and change mdf file. If the file has some errors, your code won't work anyway.

How To Delete SQl Server database while it is "In Use" using C#?

I am trying to delete sql server database. It gets deleted if it is not in use. If database is in use an exception occurred saying that can not delete database while it is in use.
We can delete use database from management studio using option Close existing connection.
But how can we do this using C# code?
ALTER DATABASE AdventureWorks2012
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;
DROP DATABASE AdventureWorks2012;
Make a script file by writing above query in it.Then execute this script file as below :
string sqlConnectionString = "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True";
FileInfo file = new FileInfo("C:\\myscript.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
The easy way on a MS SQL Server to kick all users off is:
ALTER DATABASE [MyDB] SET Single_User WITH Rollback Immediate
GO
Fire this Query through your code and go ahead:-
SOURCE:-

Problem In Open Or Use master.mdf database in C#

I define Sql_Cmd And Other sql variable that need before
and Now write this code:
string strConnection2 = "Data Source=.\\sqlexpress;AttachDbFilename=master.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
SqlConnection sqlcon2 = new SqlConnection(strConnection2);
string sql = "select * ";
Sql_Cmd.CommandType = CommandType.Text;
Sql_Cmd.CommandText = sql;
Sql_Cmd.Connection = sqlcon2;
try
{
sqlcon2.Open();
Sql_Cmd.ExecuteNonQuery();
}
catch (SqlException Error_Exception)
{
//FormError1 = new FormErrorInDataBase();
//FormError1.Show();
}
When I want to open sqlcon2 I see this error:
An attempt to attach an auto-named database for file master.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
Please help me - how can I open master database and then use select query for this database, and what is the connection string for master.mdf?
Can I write the directory of mater.mdf such as C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\master.mdf or is it enough that I write AttachDbFilename=master.mdf?
Are you trying to open 'the' master database? The system database called 'master' is used internally by SQL Server and should not / does not need to be opened or attached in this way. If not, you'll have to call your database something other than 'master' - that is a reserved database name.
Check your parameters again. The right syntax to add an .mdf-file is as follows. Attach a database file on connect to a local SQL Server Express instance:
Server=.\SQLExpress;AttachDbFilename=c:\asd\qwe\mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;
Why is the Database parameter needed? If the named database have already been attached, SQL Server does not reattach it. It uses the attached database as the default for the connection.
See: connectionstrings.com
master database is the system database that contains system information about SQL Server instance, information about databases contained in this instance and so on. This database is opened automatically when SQL Server starts.
So, when you want to connect to SQL Server, master database is already exist and cannot be attached. Information about this database you can see here
I cannot understand why you need to attach this database. Maybe you don't need to attach this database, but only connect to it? If so, you need to change th code:
string strConnection2 = "Data Source=.\\sqlexpress;initial catalog=master;Integrated Security=True;Connect Timeout=30;"

Categories

Resources