I have a C# winforms application connected to a localDB in Visual Studio 2012.
When i run the application for the first time i can add a record with the code below.
SqlCommand com = new SqlCommand();
com.Connection = new SqlConnection(Properties.Settings.Default.BioEngineering);
com.Connection.Open();
com.CommandText = "INSERT INTO Users (Forename, Surname, Company, SecurityLevel, IssueDate, ExpiryDate, CardID) VALUES (#Forename,#Surname,#Company,#SecurityLevel,#IssueDate,#ExpiryDate,#CardID)";
com.CommandText = "INSERT INTO SignInOut (UserID) VALUES (#UserID)";
com.Parameters.AddWithValue("#UserID", this.txtMemberId.Text);
com.Parameters.AddWithValue("#Forename", this.txtFirstName.Text);
com.Parameters.AddWithValue("#Surname", this.txtLastName.Text);
com.Parameters.AddWithValue("#Company", this.txtCompany.Text);
com.Parameters.AddWithValue("#SecurityLevel", SecurityLevel);
com.Parameters.AddWithValue("#IssueDate", this.dtpIssueDate.Value);
com.Parameters.AddWithValue("#ExpiryDate", this.dtpExpiryDate.Value);
com.Parameters.AddWithValue("#CardID", this.txtCardId.Text);
com.ExecuteNonQuery();
com.Connection.Close();
MessageBox.Show("New Member has been added!");
this.Hide();
mainMenu.Show();
Now, it shows this one record, but when i go to add a second record through the winforms, it says it is updated, but when i go to view the LocalDB it still only has the first record. Ive spent all trying to figure it out, i also have output set to not copy since it cause problems in the bin DB, which i dont want, i want it to update directly to the localDB? i refreshed as well, any ideas???
Any more information can be provided upon request.
Related
I'm working in Windows Forms and trying to use OLEDB to connect to an access .accdb file.
I can SELECT data without issue.
I can execute Insert and Create commands with no error.
But when I check the database afterward the data is not showing.
For example, when I create a new Table, the code will say the table was created and if I try to create the table again without closing the Windows Form it will throw an error saying the table already exists, but if I close and restart the program it will let me create the table once more.
Also, if I look into the Access file I wont see the table.
I've tried multiple tests both with Access open and closed. The Connection String is correct as I have made changes to tables in the Access file and they are reflected in the SELECT queries I've sent.
I suspect there must be a setting in Access I must enable for it to autocommit changes. But I haven't found it.
OleDbConnection conn = new OleDbConnection(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source =Database2.accdb");
string query = "INSERT INTO [TestTable] ([Test_Name], [Test_Number]) VALUES (?, ?)";
try
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
cmd.Parameters.AddWithValue("Test_Name", list_all_meters[0][0].Name);
cmd.Parameters.AddWithValue("Test_Number", list_all_meters[0][0].Value);
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("An Item has been successfully added", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}catch(Exception ex)
{
Debug.WriteLine(ex.Message);
}
Looks like the issue was I had set the Database "Copy to Output Directory" to Copy Always, which overwrote my changes every time I ran the program. Changing it to Copy if Newer fixed the issue.
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.
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.
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.
I'd like to ask you why doesn't this code work? It goes without any error, even cmd.ExecuteNonQuery(); returns 1 (is it if changes one row in the database), but in the actual database, there's absolutely no change. With other database tables, this code works properly, but I'm also not able to remove a row from this table - it behaves asi it if was "read-only", but I have no idea why - yesterday, everything worked fine and now, it's suddenly stopped working :-(
string sConnectionString;
sConnectionString = "Data Source=.\\SQLEXPRESS; AttachDbFilename=\"" + zdielaneInfo.Adresar + "\\rozvrh.mdf\";";
sConnectionString += "Integrated Security=True;User Instance=True";
SqlConnection objConn
= new SqlConnection(sConnectionString);
objConn.Open();
SqlCommand cmd = new SqlCommand("", objConn);
if (zdielaneInfo.Edit)
cmd.CommandText = "UPDATE subject " +
"SET name = #name, day = #day, timeStart = #timeStart, timeEnd = #timeEnd "
+ "WHERE id = #id";
else
cmd.CommandText = "INSERT INTO subject (name, day, timeStart, timeEnd) " +
"Values (#name, #day, #timeStart, #timeEnd)";
cmd.Parameters.Add(new SqlParameter("#name", txbName.Text));
cmd.Parameters.Add(new SqlParameter("#day", dniNaInt(cbDen.Text)));
cmd.Parameters.Add(new SqlParameter("#timeStart", DateTime.Parse(txbStart.Text)));
cmd.Parameters.Add(new SqlParameter("#timeEnd", DateTime.Parse(txbEnd.Text)));
cmd.Parameters.Add(new SqlParameter("#id", zdielaneInfo.Id));
cmd.ExecuteNonQuery();
objConn.Close();
Your problem looks like mdf file overwrite problem.
You are accessing mdf files that are put in the debug folder and replaced every time you run the application.
Be sure that in your project, if you have the database attached within your solution that you are not overwriting it. So select the mdf file in your solution explorer and make sure that its "Copy to output" is set to "Do not copy", then manually copy over the mdf file to the project\bin\debug folder then run the application.
Hope it helps.
Maybe the table is locked.
From HERE, try this:
select
object_name(P.object_id) as TableName,
resource_type, resource_description
from
sys.dm_tran_locks L
join sys.partitions P on L.resource_associated_entity_id = p.hobt_id
If your table is in the result set you have your answer.
Another possibility is the user that you are using to run. Maybe he got privileges revoked.
STOP using the user instance / attachdbfilename options (user instance is deprecated!). Create your database on a real SQL Server, then connect to it directly with your connection string. Using this deprecated feature means that every time you start up your program you're starting with a new copy of the database, and what you inserted yesterday is no longer there - and if you connect to the database using that connection string from two different applications, one is not going to see the data that the other one is changing.