Writing data from C# to a MDF database - c#

I have a C# piece of code which listens for mouse-up events and then the data is to be written to a database. I have a .MDF database file I locally created in Visual Studio within the application. I am using the below code for this.
The thing is when I open the .MDF database file in SQL Server Management Studio after installing the application, I can't see any rows of data. I can see the columns I created but no data. The "Server" in server explorer in Visual Studio shows up to be my laptop number it seems:
private void MouseUpEvent(object sender, KeyEventArgs e)
{
MousePressed = e.KeyCode.ToString();
int Counting = MousePressed.Split('/').Length - 1;
long TimePressed = _MousePressed_Length;
String DateToday = SQLDate;
String TimeToday = SQLTime;
float TimeNow = SQLTimeExactmilliseconds;
var guid = Guid.NewGuid().ToString();
var guid2 = guid + TimeNow;
string sqlCon = #"Data Source=.\SQLEXPRESS;" +
#"AttachDbFilename=|DataDirectory|\Database1.mdf;
Integrated Security=True;
Connect Timeout=30;
User Instance=True";
using (var db = new SqlConnection(sqlCon))
{
db.Open();
var command = new SqlCommand("INSERT INTO Database1 (Table) VALUES (#Date);", db);
command.Parameters.AddWithValue("#Date", DateToday);
var command2 = new SqlCommand("INSERT INTO Database1 (Table) VALUES (#Time);", db);
command2.Parameters.AddWithValue("#Time", TimeToday);
var command3 = new SqlCommand("INSERT INTO Database1 (Table) VALUES (#Mousepress);", db);
command3.Parameters.AddWithValue("#Mousepress", TimePressed);
var command5 = new SqlCommand("INSERT INTO Database1 (Table) VALUES (#TimeExact);", db);
command5.Parameters.AddWithValue("#TimeExact", TimeNow);
var command6 = new SqlCommand("INSERT INTO Database1 (Table) VALUES (#Id);", db);
command6.Parameters.AddWithValue("#Id", guid2);
command.ExecuteNonQuery();
command2.ExecuteNonQuery();
command3.ExecuteNonQuery();
command5.ExecuteNonQuery();
command6.ExecuteNonQuery();
db.Close();
}
}
When I try to open the .MDF database file in Server Explorer, I get this message from Visual Studio :
Database 'C:\Program Files (x86)\muhammadADIbrahim#outlook.com\Setup_Attention_Assist\Database1.mdf' already exists. Choose a different database name.
An attempt to attach an auto-named database for file C:\Users\muham\OneDrive\Desktop\Attention_Residue\BAAB UL WORK\NIZAM\CURRENT SOFTWARE\NizamSolutionBackup2.6\Nizam.Monitor\Database1.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
The code compiles and works properly so I am guessing this is something that is just to do with the connection to the database.
What should happen is that the .mdf data gets installed along with the .msi file when the user installs the application locally and the data is written to the database. For any user, I should be able to take the local .mdf file and open it in SQL Server Management Studio and view the results.
Thanks,
Ibrahim

The problem with the mdf database is that you need to install SQLSever.
The problem with mySql is similar. SQLLite didn't seem to work well for me either.
I have ended up creating a .txt file for this which for now seems to be working fine.

Related

Update SQL LocalDB schema in C# WinForms Application through setup

I am creating a C# WinForms Application along with SQL LocalDB. I am new to SQL and I am following this tutorial (timestamp: 5.50) to add database in project. I have also added a setup project to install the application to other PCs. When I installed the project for the first time it worked perfectly well, but when I updated the database schema (added one more column) the changes are not reflecting, updated version of setup & assembly and installed the setup file again, the database schema changes are not reflecting in the application. It is giving the following error:
My code is something like this:
private void load_list()
{
string conn = Properties.Settings.Default.dbAgeConnectionString;
SqlConnection sqlConn = new SqlConnection(conn);
string sqltext = "SELECT Name, Age, DOB from Users";
if (sqlConn.State != ConnectionState.Open) sqlConn.Open();
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(sqltext,sqlConn);
adapter.Fill(table);
sqlConn.Close();
lstRecords.DisplayMember = "Name";
lstRecords.ValueMember = "Id";
lstRecords.DataSource = table;
gvrecords.DataSource = table;
}
Connection String:
Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\dbAge.mdf;Integrated Security=True
I tried adding the database files manually in Application folder of Setup but still no results.
I searched on the internet but did not find any database version control or upgrade method for SQL LocalDB. Is there any way I can achieve this?
Thanks in advance.

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

Cannot add sqlite db file to Word adding deployment

I developed C# Word add-in which populates some data from database file. It is working fine while I am running through Visual studio running. But if I publish it cannot connect to database.
Here is how I get data from database:
SQLiteConnection con = new SQLiteConnection(ThisAddIn.connectionString);
con.Open();
var command = con.CreateCommand();
command.CommandText =
#"
SELECT *
FROM JK
WHERE article_number = $article_number
";
command.Parameters.AddWithValue("$article_number", textFromDoc);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var title = reader.GetString(2);
var article = reader.GetString(3);
ResultForm resultForm = new ResultForm();
resultForm.setArticle(title, article);
resultForm.ShowDialog();
}
}
public static string connectionString = #"Data Source=E:\projects\c#\TBPWordAddin\WordAddIn1\codexes.db";
Am I doing something wrong or do I need to include file in another way? Any help will be appreciated.
Also I tried publishing using Visual studio installer and it connected to database but the add in didnot lounched on other computers.
The connection string contains an absolute path which can be changed after publishing an application. I'd suggest using a relative path instead - in that case you will be able to find the Db easily. You may check out the following threads for more information on such kind of issues:
Connection string with relative path to the database file
How to give relative path of connection string or data source in windows form application
But if I publish it cannot connect to database.
Make sure the Db path (see the connection string) corresponds to the hardcoded value in the application used.

How to save DataSet after adding data?

Yes, I know that this questions has been asked at least 5-10 times in here, but I can't for the life of me get any of the methods to save the data.
The idea is to create a new row in table Companies in column Name (there is only one column) with value "asdf"`.
I've tried combinations of the following:
DatabaseDataSetTableAdapters.CompaniesTableAdapter adapter = new DatabaseDataSetTableAdapters.CompaniesTableAdapter();
DatabaseDataSet ds = new DatabaseDataSet();
adapter.Insert("asdf");
adapter.Fill(ds.Companies);
adapter.Update(ds.Companies);
ds.AcceptChanges();
ds.Companies.AddCompaniesRow("asdf");
ds.Companies.AcceptChanges();
ds.Companies.AddCompaniesRow("asdf");
ds.Companies.Rows[0]["Name"] = "asdf";
adapter.Update(ds.Companies);
I'm using C# WPF .NET 4.5.1
It does add the data, but it doesn't save it when I exit the program - I know that it adds data, because if I call this method twice it crashes, because the value is no longer unique.
Here is the DatabaseDataSetTableAdapters:
http://pastebin.com/gNsaRFD5
This did not work either:
SqlConnection myConnection = new SqlConnection(global::AliBabaMailer.Properties.Settings.Default.DatabaseConnectionString);
myConnection.Open();
SqlCommand myCommand = new SqlCommand("INSERT INTO Companies (Name) " +
"Values ('string')", myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();
Ok so your problem is the Connection String:
Properties.Settings.Default.DatabaseConnectionString
This connection string is of the form:
“Data Source=ServerName;AttachDbFilename=|DataDirectory|\DataBaseName;Integrated Security=True”
The |DataDirectory| is usually here:
C:\Users\UserName\AppData
When you save the data it is being saved to a database file at `|DataDirectory| location but when you try to view the data using Server Explorer you are trying to view from a database file which is in your project's folder, that is why If you try to save and then view the data on run time it will work fine because then you will be querying the same database you are storing your data into.
|DataDirectory|:
|DataDirectory| (enclosed in pipe symbols) is a substitution string that indicates the path to the database. It eliminates the need to hard-code the full path which leads to several problems as the full path to the database could be serialized in different places. |DataDirectory| also makes it easy to share a project and also to deploy an application.
For example, instead of having the following connection string:
"Data Source= c:\program files\MyApp\Mydb.sdf"
Using DataDirectory, you can have the following connection string:
“Data Source = |DataDirectory|\Mydb.sdf”
To set the DataDirectory property, call the AppDomain.SetData method. If you do not set the DataDirectory property, the following default rules will be applied to access the database folder:
For applications that are put in a folder on the user's computer, the database folder uses the application folder.
For applications that are running under ClickOnce, the database folder uses the specific data folder that is created.
Link
Coding Advice:
Try to dispose your Command and Connection Objects like this:
using(SqlConnection myConnection = new SqlConnection(global::AliBabaMailer.Properties.Settings.Default.DatabaseConnectionString))
using(SqlCommand myCommand = new SqlCommand("INSERT INTO Companies (Name) " + "Values ('string')", myConnection))
{
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}

empty sqlite file after building

I'm trying to write a C# console application that interacts with a sqlite DataBase. Every time I try to build my console application project, an empty SuperCrewNet.sqlite file is being created in my Bin folder and causes the "Flights" table (and all other tables) to disappear, the original sqlite file next to the main cs file id perfectly fine.
When I try to the sqlite_cmd.ExecuteScalar(), an exeption is thrown (no such table: Flights)
How do I solve this problem??
sqlite_conn = new SQLiteConnection("Data Source=SuperCrewNet.sqlite;Version=3;New=True;Compress=True;");
sqlite_conn.Open();
sqlite_cmd = sqlite_conn.CreateCommand();
sqlite_cmd.CommandText = "SELECT FlightID FROM Flights WHERE FlightID='" + FlightNumber + FlightDate + "'";
sqliteDatareader = sqlite_cmd.ExecuteScalar();
Check this site for help on connection strings:
http://www.connectionstrings.com/sqlite/
As mentioned in comments:
Create a new database:
Data Source=c:\mydb.db;Version=3;New=True;
So just remove New=True;

Categories

Resources