INSERT query OleDB C# - c#

I know it was 1000000000 times already, but none solution helped to me.
I want to insert data in C# using OleDB. I tried mln solutions but here is the easiest one which should work but it doesn't:
SQLCONNECTION = #"Provider=Microsoft.Jet.OLEDB.4.0;DataSource=|DataDirectory|\dbScenariusz.mdb";
using (OleDbConnection connection = new OleDbConnection(SQLCONNECTION))
{
string sql = "INSERT INTO Table (content) VALUES('lala')";
connection.Open();
OleDbCommand command = new OleDbCommand(sql, connection);
command.ExecuteNonQuery();
connection.Close();
}
SQLCONNECTION is ok. It works fine for the SELECT query.
string sql - I tried this query in Access and it works fine.
I get no error. It just didn't insert anything to the database.
When I run the query in Access (the same database) the row is inserted.
The strange thing is that command.ExecuteNonQuery(); returns 1! That means that 1 row was affected!
I really have no idea where the problem is, so I really appreciate any help.
Sorry for my english.
UPDATE: Another strange thing. I change query to update and it works fine! really wtf? :)

You are connecting to the DataDirectory. Is the .mbd file being copied after the build? In other words are you re-deploying the database with each build and thereby losing the inserts?
A quick test could be using the same code and same connection to do a select after the insert.

In the solution Explorer, check app.config. Double click the app.config, then re-enter the connectionString. Give the path of your database.
For example, in my project the default location of connectionString is:
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\App_Data\database.accdb;Persist Security Info=True"
Suppose the database is stored in this location:
C:\Documents and Settings\Amuk\My Documents\Visual Studio 2010\Projects\insertion\insertion\App_Data
therefore, replace the connectionString with
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents and Settings\Amuk\My Documents\Visual Studio 2010\Projects\insertion\insertion\App_Data\database.accdb;Persist Security Info=True"
your problem will be solved, i hope this will definitely help you, i was also getting the same problem, and by replacing the connectionString with original path, the database is storing all records.

You can try to use transaction to commit your changes.
command.Transaction = connection.BeginTransaction(); //after connection.open()
Then add
command.Transaction.Commit(); //Before connection.close()

Related

Insert integer value into SQL Server database from C#

I am trying to insert an integer value into a SQL Server database as below when I run the program there are no any errors, but the table doesn't get updated with values. I have searched on the internet and I am doing the same can anyone help to find what I am doing wrong.
Note: I already defined "connectionString" as a string on the form class
private void btnUpdate_Click(object sender, EventArgs e)
{
int totalincome=600;
int totaldeductions = 10;
connectionString = ConfigurationManager.ConnectionStrings["BudgetApp.Properties.Settings.MainDataBaseConnectionString"].ConnectionString;
con = new SqlConnection(connectionString);
con.Open();
cmd = new SqlCommand("INSERT INTO Totals(TotalIncome, TotalDeductions) VALUES (#TotalIncome, #TotalDeductions)", con);
cmd.Parameters.AddWithValue("#TotalIncome", totalincome);
cmd.Parameters.AddWithValue("#TotalDeductions", totaldeductions);
cmd.ExecuteNonQuery();
MessageBox.Show("Done !!");
}
The whole AttachDbFileName= approach is flawed - at best! When running your app in Visual Studio, it will be copying around the .mdf file (from your App_Data directory to the output directory - typically .\bin\debug - where you app runs) and most likely, your INSERT works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the myConnection.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. MainDataBase)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=MainDataBase;Integrated Security=True
and everything else is exactly the same as before...
Also see Aaron Bertrand's excellent blog post Bad habits to kick: using AttachDbFileName for more background info.
Code Seems correct,Perhaps you are checking the wrong DB?. I would add a Try/catch for exceptions. And remember to close connection after executing query. Regards
check your database column datatype,use try catch.
and try to replace cmd.Parameters.AddWithValue("#TotalIncome", totalincome); to cmd.Parameters.Add("#Number", SqlDbType.Int).Value = totalincome;
try
{
int totalincome=600;
int totaldeductions = 10;
connectionString = ConfigurationManager.ConnectionStrings["BudgetApp.Properties.Settings.MainDataBaseConnectionString"].ConnectionString;
con = new SqlConnection(connectionString);
con.Open();
cmd = new SqlCommand(#"INSERT INTO Totals(TotalIncome, TotalDeductions) VALUES (#TotalIncome, #TotalDeductions)", con);
cmd.Parameters.Add("#Number", SqlDbType.Int).Value = totalincome;
cmd.Parameters.Add("#Number", SqlDbType.Int).Value = totaldeductions;
//cmd.Parameters.AddWithValue("#TotalIncome", totalincome);
//cmd.Parameters.AddWithValue("#TotalDeductions", totaldeductions);
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}

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();

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 update table data in sql database

I am using asp.net for my project , and I am using the following code , but its not working correctly
SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=E:\\WEB_PROJECT\\App_Data\\ASPNETDB.MDF;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
cmd.CommandText = "UPDATE info SET fname = #fn, lname = #fl, phone= #ph, recoveryq=#rq, recoverya=#ra WHERE username = #un";
cmd.Parameters.AddWithValue("fn", TextBox3.Text);
cmd.Parameters.AddWithValue("fl", TextBox4.Text);
cmd.Parameters.AddWithValue("ph", TextBox5.Text);
cmd.Parameters.AddWithValue("rq",TextBox6.Text);
cmd.Parameters.AddWithValue("ra",TextBox2.Text);
cmd.Parameters.AddWithValue("un",line);
cmd.ExecuteNonQuery();
con.Close();
Advice plzz i m confused !!! :(
As I've said before on this site - the whole User Instance and AttachDbFileName= approach is flawed - at best! Visual Studio will be copying around the .mdf file and most likely, your UPDATE works just fine - but you're just looking at the wrong .mdf file in the end!
If you want to stick with this approach, then try putting a breakpoint on the con.Close() call - and then inspect the .mdf file with SQL Server Mgmt Studio Express - I'm almost certain your data is there.
The real solution in my opinion would be to
install SQL Server Express (and you've already done that anyway)
install SQL Server Management Studio Express
create your database in SSMS Express, give it a logical name (e.g. ASPNETDB)
connect to it using its logical database name (given when you create it on the server) - and don't mess around with physical database files and user instances. In that case, your connection string would be something like:
Data Source=.\\SQLEXPRESS;Database=ASPNETDB;Integrated Security=True
and everything else is exactly the same as before...
cmd.Parameters.AddWithValue("#fn", TextBox3.Text);
You have to specify the parameter name along with '#' .

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();

Categories