SQL Server Express with Windows app C# [duplicate] - c#

I am executing SQL command INSERT like this in my Visual C#.NET using MS VS 2010 Express Edition:
private void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(Properties.Settings.Default.loginDBConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO tblEmp (ID, firstname, lastname, email, position) VALUES ('"+textBox1.Text+"','"+textBox2.Text+"', '"+textBox3.Text+"', '"+textBox4.Text+"', '"+comboBox1.Text+"')", con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Added!");
}
When executing this, the MessageBox showed up which means the execution was successful. But, when I checked on the table , the data that I am trying to insert before isn't appear at all.
I have one database (loginDB.mdf) with 2 tables inside :
- TblLogin - contains username and password for login purpose which executed successfully.
- tblEmp - contains employee data, this is the one that I tried to insert data to.
What I don't understand is why the MessageBox appear when in fact none inserted into my tblEmp.
EDIT : ConnectionString to loginDB.mdf :
Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Users\Andreas\documents\visual studio 2010\Projects\LoginApplication\LoginApplication\loginDB.mdf";Integrated Security=True;User Instance=True
The database name is loginDB.mdf instead of logindatabase.mdf as previously written. I changed it to loginDB.mdf just to test it, but still no changes appear.

If your c# code executes without any exceptions, it updates the database too. You have probably used AttachDbFilename=|DataDirectory|\yourDB.mdf in your ConnectionString, that means the databse that is updated is located in the subfolder 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.
for more details read this post.
Also make sure your table in server explorer is not already open, if it is already open you must refresh it to show updated data. Please note:as mentioned in the comments you should always use parameterized queries to avoid Sql Injection.

Related

Data is not showing/updating in the SQLite table when the data is inserted through my C# code

Currently, I have been doing some simple coding related to SQL and C#. I have created this a registration form which will store the data, username and password, in an SQLite database. This is the code that I am currently using:
private void AddLoginInfo(string username, string password)
{
auth = new Authentication();
auth.getConnection();
using (SQLiteConnection con = new SQLiteConnection(auth.connectionstring))
{
SQLiteCommand cmd = new SQLiteCommand();
con.Open();
string que = #"INSERT INTO LoginInfo(Username, Password) VALUES (#username, #password)";
cmd.CommandText = que;
cmd.Connection = con;
cmd.Parameters.Add(new SQLiteParameter("#Username", username));
cmd.Parameters.Add(new SQLiteParameter("#Password", password));
cmd.ExecuteNonQuery();
MessageBox.Show("Account Created!");
}
}
This code currently works and does add to the correct table in the database however whenever a new user is added. The user information can be used to login but it does not show within the table, which is viewed using DB Browser for SQLite.
For example, if I create a new user; 'admin' as the username and 'password' as the password, through the form, I get the message box saying 'Account Created' and I can use that very account to login. However, if I go view that very data in the DB browser the data doesn't show even after refreshing the table.
After doing some digging, I found this and saw that they were using sqlCommand.Parameters.AddWithValue so I tried this within my code:
SQLiteCommand cmd = new SQLiteCommand(#"INSERT INTO LoginInfo(Username, Password) VALUES (#username, #password)", con);
cmd.Parameters.AddWithValue(new SQLiteParameter("#Username", txtBoxUsername.Text));
I tried this and I got a CS7036 error. Then I realised that they had not used the new SQLiteParameter() part and so I removed it cmd.Parameters.AddWithValue("#Username", txtBoxUsername.Text); and tried again but it still wouldn't update in the table but the data could still be used to log in.
I have also found a similar post but no one had answered it.
Now I don't know what to do, so I am asking for your help.
I figured out what was the problem; I was checking the database that was stored in the solution but what I should have checked is the database stored in the ...\bin\debug folder. The database within the folder shows the added data.
Are you retrieving the db file from another system? i.e. Android Emulator or a network location?
Are there any other files in the folder, you are specifically looking for a filename that contains '-wal'. Additional information on SQLite Wal format
the data is actually contained in this other file. DB Browser knows to look for this file. However, if you are downloading the db to your system before you take a look, you are probably not downloading the -wal file as well.
Depending on how you are configuring your SQLite db, the limit by default for checkpoint threshold is 1kb. Until the checkpoint is triggered, the data doesn't get transferred to the main db file. There are ways to manually trigger the checkpoint, see the link I have included above.

SqlCommand cannot create table

I have a problem with creating a table with SqlCommand. The code is as follow
string cs = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="+ Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + #"\Database\Test.mdf;Integrated Security=True; Database=Test";
SqlConnection sc = new SqlConnection(cs);
sc.Open();
//SqlCommand cmd = new SqlCommand();
try
{
using (SqlCommand command = new SqlCommand(
"CREATE TABLE Dogs1 (Weight INT, Name TEXT, Breed TEXT)", sc))
{
Console.WriteLine(command.ExecuteNonQuery());
}
}
catch
{
Console.WriteLine("Table not created.");
}
I put the code in Main function and run it. There is no error and the database can be opened. However, when I check the database, there is no table created. Can anyone help to see what is wrong here? Thank you.
Thank you everyone. This problem has been solved. When I created Test.mdf, I actually created in the Database folder in the project. When I double clicked the Test.mdf, it was linked to Server Explorer in Visual Studio. Then when I changed the property to Copy Always, the Test.mdf will be copied to bin/Debug/Database/. When I used Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), I was actually operating the one in bin/Debug/, rather than the one in the project folder. As a result, it looks like the table was not created. So now I linked the Test.mdf in bin/Debug/Database to the Server Explorer, I can see new tables are created.
Yes, you have created the DB inside your project which will not be available in SQL Server Management studio because this is local application DB. The .mdf file location is different for the DB in SSMS.

SQL command INSERT is working but the data not appear in table

I am executing SQL command INSERT like this in my Visual C#.NET using MS VS 2010 Express Edition:
private void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(Properties.Settings.Default.loginDBConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO tblEmp (ID, firstname, lastname, email, position) VALUES ('"+textBox1.Text+"','"+textBox2.Text+"', '"+textBox3.Text+"', '"+textBox4.Text+"', '"+comboBox1.Text+"')", con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Added!");
}
When executing this, the MessageBox showed up which means the execution was successful. But, when I checked on the table , the data that I am trying to insert before isn't appear at all.
I have one database (loginDB.mdf) with 2 tables inside :
- TblLogin - contains username and password for login purpose which executed successfully.
- tblEmp - contains employee data, this is the one that I tried to insert data to.
What I don't understand is why the MessageBox appear when in fact none inserted into my tblEmp.
EDIT : ConnectionString to loginDB.mdf :
Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Users\Andreas\documents\visual studio 2010\Projects\LoginApplication\LoginApplication\loginDB.mdf";Integrated Security=True;User Instance=True
The database name is loginDB.mdf instead of logindatabase.mdf as previously written. I changed it to loginDB.mdf just to test it, but still no changes appear.
If your c# code executes without any exceptions, it updates the database too. You have probably used AttachDbFilename=|DataDirectory|\yourDB.mdf in your ConnectionString, that means the databse that is updated is located in the subfolder 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.
for more details read this post.
Also make sure your table in server explorer is not already open, if it is already open you must refresh it to show updated data. Please note:as mentioned in the comments you should always use parameterized queries to avoid Sql Injection.

How can I display a message if a value already exists in database?

I am currently writing my first .Net & C# application with Visual Studio, and have a need to write generated values to MySQL from the application.
At present, I can write values fine - but I need to be able to check to see if a value exists and display that line if it does exist, otherwise insert new line to table. My connection string is defined at the top of the form.
I have the following defined already, and it writes to the database successfully if no duplicate values exist in the LicenseKey column. If a duplicate exists, it throws an unhandled exception.
private void SaveDetails()
{
// MySQL 'insert' command
string InsertNewLicense = "insert into BCOM.LicenseDetails(LicenseeName,ComputerName,ContactName,ContactEmail,LicenseKey,CreationDate) values('" +this.textBoxLicenseeName.Text+ "','" +this.textBoxComputerName.Text+ "','" +this.textBoxContactName.Text+ "','" +this.textBoxContactEmail.Text+ "','" +this.textBoxLicenseKey.Text+ "','" +this.textBoxCreationDate.Text+ "');";
//MySQL instance details
MySqlConnection InsertLicenseDetails = new MySqlConnection(LicenseDatabaseConnection);
//MySQL command execution
MySqlCommand InsertCommand = new MySqlCommand(InsertNewLicense, InsertLicenseDetails);
// Handles command outputs.
MySqlDataReader InsertReader;
//Opens connection to run query on database
InsertLicenseDetails.Open();
// Here our query will be executed and data saved into the database.
MessageBox.Show("License Details Saved. Please ensure you have emailed the license to the customer.");
while (InsertReader.Read())
{
}
InsertLicenseDetails.Close();
}
What I want to happen is for a check to be run on the LicenseKey column to see if the value exists, before different actions are taken.
If the value does not exist, I would like to insert the new line to the table (like my existing command does).
If, however, the value does exist, I would like to pop up a form showing the values from the line that the duplicate appears in as a form.
Where would I put in an event handler to read MySQLException values? What exception would I have to respond to for a duplicate value or no database response?
I agree with what the others have said in their comments, you could change the SQL Query to do the check instead of having 2.
IF(SELECT ... WHERE A = B)
RETURN THAT THE VALUE ALREADY EXISTS
ELSE
INSERT NEW VALUE
Also there was a good comment about SQL Injection and parameterized queries. The query string should look a bit more like
INSERT into BCOM.LicenseDetails(LicenseeName,ComputerName,ContactName,ContactEmail,LicenseKey,CreationDate) values(#LicenseeName, #ComputerName, #ContactName ...);
and your SqlCommand be parameterized
InsertCommand.Paramaters.AddWithValue("#LicenseeName", this.textBoxLicenseeName.Text);
InsertCommand.Paramaters.AddWithValue("#ComputerName", this.textBoxComputerName.Text);
...
That should be a good start to get you going.
After looking at the queries for a while I decided to try a different tack - instead of using a direct check if it's there, I opted to use a count(*) query. When I click the save button on the form, the buttonClick_event calls SaveDetails(), which runs the following:
private void SaveDetails()
{
string InsertNewLicense = "INSERT into BCOM.LicenseDetails(LicenseeName,ComputerName,ContactName,ContactEmail,LicenseKey,CreationDate) values(#LicenseeName, #ComputerName, #ContactName, #ContactEmail, #LicenseKey, #CreationDate)";
string LicenseExistence = "SELECT COUNT(*) FROM BCOM.LicenseDetails WHERE LicenseKey LIKE #LicenseKey";
MySqlConnection LicenseDetails = new MySqlConnection(LicenseDatabaseConnection);
MySqlCommand InsertCommand = new MySqlCommand(InsertNewLicense, LicenseDetails);
InsertCommand.Parameters.AddWithValue("#LicenseeName", this.textBoxLicenseeName.Text);
InsertCommand.Parameters.AddWithValue("#ComputerName", this.textBoxComputerName.Text);
InsertCommand.Parameters.AddWithValue("#ContactName", this.textBoxContactName.Text);
InsertCommand.Parameters.AddWithValue("#ContactEmail", this.textBoxContactEmail.Text);
InsertCommand.Parameters.AddWithValue("#LicenseKey", this.textBoxLicenseKey.Text);
InsertCommand.Parameters.AddWithValue("#CreationDate", this.textBoxCreationDate.Text);
MySqlCommand QueryCommand = new MySqlCommand(LicenseExistence, LicenseDetails);
QueryCommand.Parameters.AddWithValue("#LicenseKey", this.textBoxLicenseKey.Text);
MySqlDataReader InsertReader;
LicenseDetails.Open();
if ((int)(long)QueryCommand.ExecuteScalar() >0)
{
MessageBox.Show("This license already exists in the database.");
}
else
{
InsertReader = InsertCommand.ExecuteReader();
MessageBox.Show("License Details Saved. Please ensure you have emailed the license to the customer.");
while (InsertReader.Read())
{
}
}
LicenseDetails.Close();
So, if the query against the license keys returns with any results at all (more than 0 rows returned), a messagebox pops up showing that the key already exists. If the resultant number of rows is 0, the insert command gets run.
This was figured out with a look through MySQL command notes, testing with phpMyAdmin, matching against existing projects online, and support from the following:
The SELECT query was figured out with great support from #Seige.
The query was parameterized with help from Seige, following on from the advice of Sani Huttunen. Many thanks to them both.
Changing to the count method was done on the advice of a fellow coder in another community online - a good friend and brilliant coder.

Insert Into local database C#

I can't Insert and select from Local database data in C#.
I've read these articles
C# - Writing data in local database
http://msdn.microsoft.com/en-us/library/system.data.sqlserverce.sqlceconnection(v=vs.100).aspx
How to add local database items into textBox using listBox in C#
All the code samples are the same, here's my sample.
SqlCeConnection conn = new SqlCeConnection(#"Data Source=|DataDirectory|\PacjenciDB.sdf");
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText="INSERT INTO pacjenci (nazwiskoimie,adres,skierowany,opis) values (#nazwiskoimie,#adres,#skierowany,#opis)";
cmd.Parameters.AddWithValue("#nazwiskoimie", txtnazwiskoimie.Text);
cmd.Parameters.AddWithValue("#adres", txtadres.Text);
cmd.Parameters.AddWithValue("#skierowany", txtskierowany.Text);
cmd.Parameters.AddWithValue("#opis", txtopis.Text);
cmd.ExecuteNonQuery();
conn.Close();
Can someone tell me what I'm doing wrong?
I've tried tons of samples about insert data, but it doesn't work.
I can manage .MDF, but .SDF seems quite problematic.
Hope you help me
Ok, I'm going to take a guess here. Is the PacjenciDB.sdf included into Visual Studio project by any chance? Do you have the property "Copy to output folder" set to "Always" or something similar? It seems that every time you do a build you could be overwriting your output folder database file. Try putting the database in a folder that is not inside VS project.
BTW, your code is OK.
Look for a copy of the database with data in your bin/debug folder.
Solution is to not use |DataDirectory|, but use full path instead.
The above code is correct and most likely the problem is somewhere else, where you call that code from. If there is a problem with db connection or data is wrong - you should get an exception. Since there is no error occurred and no new records added - the code is not executed at all.
P.S.
.sdf is a Sql Server Compact Local Database, so using System.Data.SqlServerCe is correct
http://msdn.microsoft.com/en-us/library/system.data.sqlserverce(v=vs.100).aspx
Try using double backslash when setting the path to your database file:
string dbPath + "Data Source=C:\\DataDirectory\\PacjenciDB.sdf";
SqlCeConnection conn = new SqlCeConnection(dbPath);
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText="INSERT INTO pacjenci (nazwiskoimie,adres,skierowany,opis) values (#nazwiskoimie,#adres,#skierowany,#opis)";
cmd.Parameters.AddWithValue("#nazwiskoimie", txtnazwiskoimie.Text);
cmd.Parameters.AddWithValue("#adres", txtadres.Text);
cmd.Parameters.AddWithValue("#skierowany", txtskierowany.Text);
cmd.Parameters.AddWithValue("#opis", txtopis.Text);
cmd.ExecuteNonQuery();
conn.Close();

Categories