Restart program and lost data in database - c#

I have data in 'mdf' database, which I'm not allowed to come.
But every time I restart the program the data is lost? Why?
System.Data.SqlClient.SqlConnection con;
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = #"Data Source=(LocalDB)\v11.0;
AttachDbFilename=C:\Users\Jirka\Project_26\databaze.mdf;
Integrated Security=True";
con.Open();
con.Close();

If 'every time I restart the program' mean every time you run it in visual studio, then your problem is that the database is copied on every compile.
Select the Copy if newer option instead and try then.

Related

How to establish SQL Connection in Visual Studio using local mdf file

I'm new to coding. I'm attempting to access a SQL Server file through WPF / C# and I am having trouble getting in the correct string, I believe. I do not yet fully understand SQL logins, but here is the code I have now, which I believe as close to correct as I can get on my own:
string CS = #"Data Source=(LocalDB)\v11.0; Integrated Security=true; AttachDbFileName=C:\Users\Madison\source\repos\TheRealStudyBot\TheRealStudyBot\TestingData.mdf";
SqlConnection con = new SqlConnection(CS);
SqlCommand cmd = new SqlCommand("CREATE TABLE table1 (PK int, Name nvarchar(255), PRIMARY KEY *PK),);", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
con.Close();
This code is under public MainWindow(), after InitializeComponent(). The file path should be correct. The database is empty. I get this exception:
Win32Exception: Unknown error (0x89c50118)
Ran it once more and I think I may have accidentally altered my debug settings because now it also provides a window stating
The solution does not contain the specified document
(along with plenty of other jargony-code-exception-results-text). I don't see where I'm going wrong. Please help!
If you are on Visual Studio 2019,
Double Click on your LocalDB which opens Server Explorer
Clicking on your database, On the properties tab shows the connection string.
Copy that & Paste on CS!
And the Normal Connection String Format For LocalDB is,
Data Source=Your_DataSource;Initial Catalog=YourDatabaseName;Integrated Security=True;Pooling=False

How to create an embedded database?

So, I started to make an app on my main pc. The database works just fine.
But when I move the app on the second Pc,or any other Pc , to continue the work, it chrases, and throws this exception:
System.Data.SqlClient.SqlException: 'An attempt to attach an auto-named database for file C:\Users\Cristi\OneDrive\Documente\Licurici\Licurici\qst.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.'
This is the initial connection string :
SqlConnection sqc = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Cristi\OneDrive\Documente\Licurici\Licurici\qst.mdf;Integrated Security=True");
I changed the connection string in:
SqlConnection sqc = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|qst.mdf;Integrated Security=True");
and I also tried this :
SqlConnection sqc = new SqlConnection(Properties.Settings.Default.qstConnectionString);
The last 2 strings work fine, and makes the database portable, but makes INSERT commands not work anymore, at all. This is my sql command:
sqc.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Question(quest, a, b, c, d) VALUES(#q, #a, #b, #c, #d)",sqc);
cmd.Parameters.AddWithValue("#q", richTextBox1.Text.ToString());
cmd.Parameters.AddWithValue("#a", richTextBox2.Text.ToString());
cmd.Parameters.AddWithValue("#b", richTextBox3.Text.ToString());
cmd.Parameters.AddWithValue("#c", richTextBox4.Text.ToString());
cmd.Parameters.AddWithValue("#d", richTextBox5.Text.ToString());
cmd.ExecuteNonQuery();
sqc.Close();
So I am asking you, how do I create a portable(or embedded) database, that will work on any pc, without having to change manually the connection string everytime and also have the possibility to work properly with the sqlcommands like insert ?
I'm working in Visual Studio 2017 with .NET framework.The project is a windows form app.
Any help is appreciated ! :)

Connecting to local database

I am trying to create to a local database via a mdf file, like so:
scon = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDBFilename=|DataDirectory|\articles.mdf; Integrated Security=True");
scon.Open();
scmd = new SqlCommand("Insert INTO articles(url) VALUES(#url)");
scmd.Parameters.AddWithValue("#url", "http://google.com");
scmd.ExecuteNonQuery();
MY mdf file is in the root folder, and in the debug folder too. When I run the following code I get an error saying the following:
I can't use the full connection path because it's a long url with spaces, here is my file structure:
My database exists:
How can I fix this so I can connect to my database?
Pass the connection object to the SqlCommand constructor
scmd = new SqlCommand("Insert INTO articles(url) VALUES(#url)", scon);
The connectionstring is fine, the error message informs you that it is not possible to execute a command if the database is not known. The SqlConnection contains this information and you need to pass it to your command.
Another possibility is through the
scmd.Connection = scon;
but, personally, I prefer to pass that info in the constructor.
Final but really important note:
SqlConnection and SqlCommand are disposable objects. You should always dispose these kind of objects. The using statement is the correct method
using(scon = new SqlConnection(....))
using(scmd = new SqlCommand("Insert INTO articles(url) VALUES(#url)",scon))
{
scon.Open();
scmd.Parameters.AddWithValue("#url", "http://google.com");
scmd.ExecuteNonQuery();
}
The Problem With Your Code Is That You Have A Command and a Connection But There Is Nothing To Till The Command To Use This Connection Object ... You Can Use The SqlCommand Constructor To Do That
scmd = new SqlCommand("Insert INTO articles(url) VALUES(#url)",scon)
Or Use The Connection Property Of The SqlCommand Class Like This
scmd.Connection = scon
Consider Adding Using To Your SQL Connection ... Or Else You Will Have To Manually Close The Connection By Calling scon.Close();
if You Didn't Do either Of Those You Will Run Into An Exception If Your Tried To Open The Connection Again While It's Already Open

SQL query does not update table

I have got an UPDATE query, what works well when I execute it in MS Managment Studio.
But if I try execute this query from my c# app, it executes without any exceptions, but does not update the table. Connection string is right.
This is the way I do it:
int contractId = 2
con.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\tst.mdf;Integrated Security=True;Connect Timeout=30";
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "update аренды set datetime_возврата=GETDATE() where id_договора=#contractId";
cmd.Parameters.Add("#contract_id", SqlDbType.Int, 4).Value = contractId;
cmd.ExecuteNonQuery();
What can be wrong?
If your c# code executes without any exceptions, it updates the database too, but please note you are used AttachDbFilename=|DataDirectory|\tst.mdf in your ConnectionString means the database that is updated is located in the sub-folder BIN\DEBUG folder of your project. If you want to see the updated data just attach the database located in the bin/debug folder in SSMS.
Also as Steve mentioned in comments, for more details read this post.

Error establishing connection to SQL Server

I just started creating a local database in Visual Studio for the first time and I'm having a hard time making it work.
In modify connection I tested and it works and also got the connection string:
string ConnectionString = #"Data Source=D:\Bratulescu Mihai\WindowsFormsApplication1\WindowsFormsApplication1\NodeBDatabase.sdf";
sqlConn = new SqlConnection(ConnectionString);
sqlConn.Open();
But when it tries Open() it cannot connect. I don't know much about this whole server thing, I just created the db and it's DataSet.
If you are using SQLCe since I see you are reffering to an sdf file you should add a reference of System.Data.SqlServerCe and try:
using System.Data.SqlServerCe;
....
sqlConn = new SqlCeConnection(ConnectionString);
sqlConn.Open();
are you sure about the connection string?
You could take a look at this site: http://www.connectionstrings.com/sql-server-compact/

Categories

Resources