OLEDB commands aren't being saved in access database - c#

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.

Related

C# insert in table doesn't work but select works perfect

I work at a Windows Form C# application but i have some troubles. When I want to select from table everything works perfect ,but when i want to insert data in my table have not error and my application says "The data was inserted in database", but my table is empty.
This is my connection :
SqlConnection conexiune = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Baza-de-date.mdf;Integrated Security=True");
This is my code:
try
{
SqlCommand insert = new SqlCommand("INSERT INTO [dbo].[Tabel] ([ID], [Nume], [Prenume], [Varsta]) VALUES (#id, #nume,#prenume,#varsta)", conexiune);
insert.Parameters.AddWithValue("#id",textBox1.Text);
insert.Parameters.AddWithValue("#nume", textBox2.Text);
insert.Parameters.AddWithValue("#prenume", textBox3.Text);
insert.Parameters.AddWithValue("#varsta", textBox4.Text);
conexiune.Open();
insert.ExecuteReader();
MessageBox.Show("Datele au fost introduse cu succes in baza de date!", "Succes!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("A avut loc o eroare! Te rog sa incerci din nou", "Eroare!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
finally
{
conexiune.Close();
this.Close();
}
I'm using Visual studio 2013 and Microsoft SQL Server version 11.00.3000.
Sorry for my English
This is a problem, at least:
insert.ExecuteReader();
That's meant for queries, because you're reading data. (As noted by Steve, it would still work - but it's not
Call ExecuteNonQuery instead:
insert.ExecuteNonQuery();
Additionally, I'd advise using using statements instead of manually closing resources. (You should close the SqlCommand too.)
However, the real problem was found by Steve in comments - you were copying a fresh copy of the database on each run. So I'd expect you to see the results of the insert within one execution of the application, but they'd be lost next time you started the app.
Check your query by running the same in sql server maybe the issue is you are writing the wrong table or column names somewhere
And i guess as you are using ID column you must have kept is as identity
If this is the case then you cannot insert a value t that column it'll take the value automatically..
Return your generated query in a label or something and check it in sql server if its working properly or not..

Local Database won't show my programmaticaly added table

I will go at a c# contest and I will need to work with databases offline, and they should work on every PC, so if someone copies my project and runs my program, everything will work the same.
I created a Local Database with Add - New Item and made my database.
My code
private void Form1_Load(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(Properties.Settings.Default.bazalocalaConnectionString);
con.Open();
SqlCeCommand com = new SqlCeCommand("select * from Tabela",con);
SqlCeDataReader r = com.ExecuteReader();
while (r.Read())
{
MessageBox.Show(r["nume"].ToString());
}
com = new SqlCeCommand("create table taby(id int identity(1,1) primary key,nume nvarchar(10),prenume nvarchar(10) )", con);
com.ExecuteNonQuery();
con.Close();
}
The problem i have is, that after I create my table, and close the program, my new table won't be there in my server explorer.. why is that?
Did i Did something wrong?
And if I work like this, will it work on every PC?
My connection string is auto generated by visual studio when I create my local database and it is
Data Source=|DataDirectory|\bazalocala.sdf
When you use |DataDirectory| and compile the program in Visual Studio, the Visual studio creates a temp database in the Debug folder which is different from your original database. That is why the added table doesn't show up in there, instead of |DataDirectory| use the actual address.
The substitution string |DataDirectory| is replaced by the directory where your program runs.
During a Visual Studio debugging session this directory is BIN\DEBUG (or x86 variant).
So your table is added in a database located in BIN\DEBUG folder, while your server explorer window has a connection that points to a database located in the project folder.
You could try to add another connection that points to the database in the BIN\DEBUG folder and you will be able to see your table.
If you run your program outside VS then you don't have this problem.
To complicate further the matter there is the property Copy to output directory for your SDF file. If this property is set to Copy Always, then every time you start a debug session your SDF file is copied from your project folder to the BIN\DEBUG folder effectively overwriting the file and the change you have made in the previous debug session. You should change this property to Copy if Newer
you can try like this
try
{
SqlCeConnection con = new SqlCeConnection(Properties.Settings.Default.bazalocalaConnectionString);
con.Open();
//
// The following code uses an SqlCommand based on the SqlConnection.
//
using (SqlCeCommandcommand = new SqlCeCommand("CREATE TABLE taby(id int identity(1,1) primary key,nume nvarchar(10),prenume nvarchar(10) );", con))
{
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
SqlCeConnection con = new SqlCeConnection("Data Source=K:/PROJECT LOCATION/Database1.sdf");
con.Open();
string x = "insert into TABLE(your columns) values (what values you want)";
SqlCeCommand cmd = new SqlCeCommand(x, con);
try
{
cmd.ExecuteNonQuery();
}
catch
{
MessageBox.Show(" Something is wrong","ERROR!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
con.Close();
I created a connection and gave it the full location of the database, NOT the one from the bin/debug. Then i opened the connection and wrote the string x to save that data in my database. I created a new command which i tested in a try-catch clause and finally i closed the connection.

sql statement isnt saving any data into table

Whenever I execute my C# code everything goes well, no compiler errors, nothing.
But when I go to look at my table in the server explorer, nothing was inserted.
Restarted Visual Studio, still nothing.
I went to debug and I looked at the cmd string before it executes ExecuteNonQuery() and the string still is #itmId,... etc. Not sure if that would effect it or not. Any help?
try
{
Item workingItem = mItemList.Items[itemCombo.SelectedIndex - 1] as Item;
SqlCeConnection sc = new SqlCeConnection(SalesTracker.Properties.Settings.Default.salesTrackerConnectionString);
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Sales VALUES(#itmId, #itmNm,#fstNm, #date,#prft, #commision)", sc);
cmd.Parameters.AddWithValue("#itmId", workingItem.ItemId);
cmd.Parameters.AddWithValue("#itmNm", workingItem.ItemName);
cmd.Parameters.AddWithValue("#fstNm", logedSalesmen.ID);
cmd.Parameters.AddWithValue("#date", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
cmd.Parameters.AddWithValue("#prft", workingItem.Profit);
cmd.Parameters.AddWithValue("#commision", workingItem.Commision);
sc.Open();
cmd.ExecuteNonQuery();
sc.Close();
MessageBox.Show("Save successfull");
this.Close();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
EDIT:So it is a matter of the temporary debug database being used, i used select count(0) to figure that out. But im not sure what i should use in my connection string to fix it.
The most common error here is actually a deployment thing - i.e. having 2 different database files in play. In particular, commonly the database file you are debugging (etc) against is often the one in "bin/debug" or similar, and gets overwritten every time you build. But the file people often look at to see the change is the one in their project tree.
Make sure you are looking at the right file.
The code looks fine; the fact that the parameters are still parameters is entirely expected and correct. If you want a simple way of validating the insert, then just check
SELECT COUNT(1) FROM Sales
before and after the insert; I expect it will be incrementing.
Also check that you are closing and disposing the connection cleanly (in case this is simply a buffered change that didn't get written before the process terminated). Both sc and cmd are IDisposable, so you should use using really:
using(SqlCeConnection sc = new SqlCeConnection(
SalesTracker.Properties.Settings.Default.salesTrackerConnectionString))
using(SqlCeCommand cmd = new SqlCeCommand(
"INSERT INTO Sales VALUES(#itmId, #itmNm,#fstNm, #date,#prft, #commision)",
sc))
{
cmd.Parameters.AddWithValue("#itmId", workingItem.ItemId);
cmd.Parameters.AddWithValue("#itmNm", workingItem.ItemName);
cmd.Parameters.AddWithValue("#fstNm", logedSalesmen.ID);
cmd.Parameters.AddWithValue("#date",
DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
cmd.Parameters.AddWithValue("#prft", workingItem.Profit);
cmd.Parameters.AddWithValue("#commision", workingItem.Commision);
sc.Open();
cmd.ExecuteNonQuery();
}
You shouldn't convert DateTime.Now to a string - pass it just as DateTime.Now
You should specify the columns in your insert statement: Ie:
INSERT INTO Sales (ItemID,ItemName...) VALUES (#itmID)
You can use SQL Profiler to check what is being passed to the Database.
Visual Studio can sometimes copy SQLCE databases when you don't want it to, when you build your C# project. So, click on the sdf file in the Solution Explorer and select Copy if newer.

How to insert data into a Microsoft Access Database?

I'm trying to insert data into a Microsoft Access Database.
I inserted data into the Access database, but the first and second time are the only times that show the data I inserted. When I rebuild my application, the data I inserted is gone. I don't know where they go and not show. I use C# with the .NET framework to develop. Here's the relevant part of the code:
OleDbConnection con = new OleDbConnection(ConfigurationManager.ConnectionStrings["Constr"].ConnectionString);
OleDbCommand com = new OleDbCommand();
com.Connection = con;
com.CommandText = "Insert into Language(English,Type,Thai) values(#eng,#type,#thai)";
com.Parameters.AddWithValue("#eng", english);
com.Parameters.AddWithValue("#type", type);
com.Parameters.AddWithValue("#thai", thai);
con.Open();
com.ExecuteNonQuery();
I wrote that code, but I think it is strange. It doesn't show any errors or exceptions, but my data is not inserted correctly. Is this the correct way to insert data? If so, why it it not getting inserted?
When I rebuild my application, the data I inserted is gone
I suspect your database is being overwritten when the application is rebuilt.
This can happen, for example, if your application contains an MDB file that is copied to the output directory on build, and is used from the output directory.
I think Language should be a reserve word and you should wrap it in [] brackets.
Also consider wrapping the code in using blocks, like
using (OleDbConnection con = new OleDbConnection(...))
{
using (OleDbCommand com = new OleDbCommand(sqlString, con))
{
//code
}
}
Other than this [possible issue with table name and that you are not closing your connection], I don't see anything wrong with the code.
You define parameters for the query, but I don't see anywhere those parameters are bound to actual data...
Try some simple tests that replace the variables you're passing in as parameters with actual values, so you can isolate the problem:
In other words, replace this:
com.Parameters.AddWithValue("#eng", english);
com.Parameters.AddWithValue("#type", type);
com.Parameters.AddWithValue("#thai", thai);
With something like this:
//I don't know the data types of your fields, so I'm guessing
com.Parameters.AddWithValue("#eng", "Test1");
com.Parameters.AddWithValue("#type", myEnum.Latin);
com.Parameters.AddWithValue("#thai", "Test1a");
If that works, then your problem probably lies with the english, type, and thai variables and you'll want to make sure they're getting the data you think they should be getting.
May be ur connection string not correct you can it by using .udl file
just follow the link
http://www.gotknowhow.com/articles/test-a-database-connection-string-using-notepad
You can also check the code shown below
OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\ruby\\Desktop\\screenShots\\ruby.mdb;Persist Security Info=False");
con.Open();
OleDbCommand cmd = new OleDbCommand("insert into raj(Name,Roll) values('XYZ',12);",con);
cmd.ExecuteNonQuery();

OleDB not saved to database file

I have an MDB file I access using OleDB:
OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database.mdb;Persist Security Info=True");
And try to create a new row in a table Users:
connection.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO `users` (`name`, `password`) VALUES ('asd', 'asd')", connection);
cmd.ExecuteNonQuery();
connection.Close();
But nothing happens. I don't get an error message or exceptions, it runs without problems. But when I check the database after the program finished, the table still is empty.
(I already tried the same using DataSets and TableAdapters, but the same happened there: Inserting not committed to database)
That query does not look like an Access query. Have you tried:
"INSERT INTO [users] ([name], [password]) VALUES ('asd', 'asd')"
In Access, table and field names do not use a back-quote, however, reserved words must be enclosed in square brackets.

Categories