How to create an embedded database? - c#

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 ! :)

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

Restart program and lost data in database

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.

SQL Server Express inserts doesn't work anymore

In my C# application, I do the following:
using (SqlConnection connection = new SqlConnection(connectionstr))
{
connection.Open();
SqlCommand com1 = new SqlCommand("insert into Anfangstierbestand(bestand, jahr, loginid) VALUES (" + bestand + ", " + jahr + ", " + loginid + ");", connection);
SqlCommand com2 = new SqlCommand("select * from Anfangstierbestand;", connection);
com1.Connection = connection;
int ferksum = 0;
com1.ExecuteNonQuery();
connection.Close();
connection.Open();
SqlDataReader read = com2.ExecuteReader();
while (read.Read())
{
ferksum += Convert.ToInt32(read[2]);
}
// MessageBox.Show("Fehler beim Erstellen des Tierbestandes", "Fehler"); }
MessageBox.Show(ferksum.ToString());
}
It's a simple insert to a database. I added com2 to check, if the insert works.
Unfortunately, the the value of com2 tells me, that it works, but when I go to the Server Explorer and press Execute SQL, there are no new values.
I don´t know the reason. The code above is just an example, since a few days, no insert works anymore(before, the same code works).
Does anybody know what the reason can be?
EDIT:
C#:
string connectionstr = "Data Source=.\\SQLEXPRESS;" + "AttachDbFilename=|DataDirectory|\\Datenbank\\FarmersCalc.mdf;" + "Integrated Security=True;" + "User Instance=true;";
EDIT2:
Server Explorer:
Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Users\user\Desktop\Farmer´s Calc\Programmierung\WPF\Finanz_WPF\Finanz_WPF\Datenbank\FarmersCalc.mdf";Integrated Security=True;User Instance=True
EDIT3:
Here are the columns:
id int,
jahr int,
anzahl int,
loginid int
EDIT4:
Is it possible that it´s a problem that I opened my project with expression blend? Normally, I work with VS 2010...
EDIT5:
Even because I can not answer my question(<100 reputations) I write it here:
Shame on me. Some of you were right, it was the wrong database-file. But I´m still wondering, why this happened, because I did not change anything since a few days and before this, it worked!
Thanks to all for helping!
You're using user instances, why? Isn't it possible that the instance you're connecting to in Server Explorer is not the same as the instance where your app is inserting data? What happens when you select data from within the app, does it reflect your insert(s)? It seems to me based on your connection strings that these are two completely different MDF files - they have the same name but they are in different locations.
Is the issue implicit transactions? Do you need to issue a commit of the SQL Insert? If com2 tells you that it's there then it may only see it since it's in the context of the current SQL transaction.
You should share your connection string for both Server Explorer and your SqlConnection (connectionstr). Ensure that you setup your Server Explorer connection with User Instance=true;.
As a diagnostic,
connection.Open();
int n = com1.ExecuteNonQuery();
// log or show 'n' , the nr of rows affected
Edit, after seeing the connectionstrings:
local db files in |DataDirectory|\ are very prone to be overwritten by the next run or build command.
Make sure you set them to 'copy never' or 'copy if newer' in the VS Solution explorer.
Perhaps somewhere in the callstack above this code, someone has added a TransactionScope.
This would cause the connections to enroll automatically in the transaction, and the connections could see the data inserted via that not-yet-committed transaction. When the scope is exitted without calling scope.Complete, the transaction gets rolled back and no data is saved.

Can't create a sql connection due to the fact that it won't rcognize the data source keyword

Hello I'm trying to run a simple sql command on a DB from MS VS C# 2010 and I have encountered a error I have never seen before the relevant code is:
SqlConnection comCon = new SqlConnection(#"Data Source=C:\\Users\\George\\Desktop\\programming\\C#workspace\\Projects\\Examen\\Examen\\Companie.mdf;Initial Catalog=Proiect;Integrated Security=True"); 
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE Proiect SET Buget = Buget + 500 WHERE (Buget > 0)";
cmd.Connection = comCon;                                                      
comCon.Open();
Console.WriteLine(cmd.ExecuteNonQuery().ToString());
comCon.Close();
And the error is Keyword not supported: 'data source'
The main problem is that I'm not used to creating these sqlconnections by hand so please tell me if I'm missing something.
You are using the wrong structure. To attach a database file, you need to use the following structure:
SqlConnection sqlConnection =
"Server=DatabaseServerName;AttachDbFilename=d:\Database\Database.mdf;
Database=DatabaseName; Trusted_Connection=Yes";
You need to have the right permissions on both the target file and database server to attach the databse and establish the connection.
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|mydbfile.mdf;Database=dbname; Trusted_Connection=Yes;
If it's not an ASP.NET application don't use the DataDirectory syntax and just use the full c:... path.

SQlite & c#, unable to connect database error

SQLiteConnection conn = new SQLiteConnection("Data Source=/data/bakkal.db3;");
conn.Open();
conn.Close();
I am new at programming so maybe the problem is a very dumb one, sorry for that.
I am trying to connect my project with a database which exists in the directory listed above. But the project gives an error at "conn.Open();" line which is just "unable to connect database". Database has no passwords or etc, it is just a very small database with 2 columns.
I don't think it is going to change anything but my project is a WPF application project, maybe differs.
Thanks for any help
If the database file is located in the same folder as the executable you could try this:
using (var conn = new SQLiteConnection(#"Data Source=|DataDirectory|bakkal.db3"))
{
conn.Open();
}
If it is in a subfolder:
#"|DataDirectory|data\bakkal.db3"
If not use absolute path:
#"c:\somepath\data\bakkal.db3"
Write out the location of the database completely [drive][path][databasefile]
using (SQLiteConnection connection = new SQLiteConnection(#"Data Source=c:\data\bakkal.db3"))
{
connection .Open();
}

Categories

Resources