Access database acting randomly and inconsistently after being updated with OLEDB c# - c#

So I am having a very weird issue, At first my code to insert items into my access database stopped working, it is a simple code like this:
using (OleDbConnection myCon = new OleDbConnection())
{
OleDbCommand cmd = new OleDbCommand()
{
CommandType = CommandType.Text,
CommandText = "insert into applicationSalts ([appName],[salt]) values (?,?)"
};
cmd.Parameters.AddWithValue("#appName", appName);
cmd.Parameters.AddWithValue("#salt", salt);
myCon.ConnectionString = publicDbConnectionString;
cmd.Connection = myCon;
myCon.Open();
int result = cmd.ExecuteNonQuery();
myCon.Close();
}
So it is very straight forward, inserting those values and I checked that result = 1 (query finished successfully).
Now it gets a bit weird, The database happens to not show any new values. Which is weird, Then I tried renaming the database and then all those records appear later! I tried using the database from another location (I was using it from C:/databaseName then now used it from D:/databaseName) then it worked. I moved the database file that worked back into C, then suddenly the records that appeared before disappeared.
Much weirder is that at the beginning one of the tables in the same database used to be working with an ideantical call as the one prior to this. But this one didnt! Then when I was trying to find the issue that one also stopped working..
Also after I manually changed some records when it was working through ms access it later ignored the changes..
I am slowly going insane as I am not really understanding what is going on, This is using access 2000 file format.
Edit: After further experimentation it is still getting weirder for me, While the file is called onlineDb.mdb it had a single record, deleting that made it disappear, Now renaming it to onDb.mdb made that record come back, adding other records that were missing. Then renaming to onlineDB.mdb again made all records disappear.

Related

How to change an Oracle table schema on live web application without restarting it?

I have a quite specific question, for a quite specific problem. My dev environment is pretty simple : an Oracle 11g database, C# web application (with ASP).
To connect to my database, I use the OracleManagedDataAccess nuget package and it worked fine until last month. I was able to add columns on my tables without any problem, but now, it returns an exception : index out of range when loading my DataReader into a DataTable.
string connectionString = "myConnectionStringToTheDB";
string requete = "SELECT * FROM MyTable";
using (var connexion = new OracleConnection(connectionString))
{
connexion.Open();
using (var commande = new OracleCommand(requete, connexion))
using (var dr = commande.ExecuteReader())
using (var datatable = new DataTable())
{
datatable.Load(dr); // => crashes here
foreach (DataRow row in datatable.Rows)
{
var campagne = GetFromDataReader<Campagne>(row, connectionString);
campagne.CodeSource = row["CODE_SOURCE"].ToString();
result.Add(campagne);
}
}
}
This code works when the app is running, no problem. Then I add a column to my table. Then I run this code again, and NOPE... I have to stop and restart the app (on IIS) to get it running fine.
The fact is that when my query includes a '*', it crashes. If I list all the columns of my table, it works.
This problem suddenly occured with no reason and it is really annoying as I need to add columns to my table even when there are users connected to the app. These newly added columns won't be used until the restart of the program of course...
Do you know how to solve this problem ?
Thanks !
After a few tries, I figured out what happened.
The error came from my version of the OracleManagedDataAccess DLL.
Versions post 18.6 automatically includes Request and Metadata Pooling.
-I had to rollback from 19.1 to 18.6
-I added => "Metadata Pooling=false;Statement Cache Purge=true;" to my connection string, and now it works fine again.
So I won't be able to update this DLL any further now. Well, anyway...

C#/SQL Error "Object not set to an instance of an object"

This may not actually be a code issue, but here goes...
My C# program reads a CSV file and builds an SQL Insert statement to insert all rows of the file into a table, so the Insert statement becomes:
Insert GHP_For_CMS (GroupId, EmployeeID, etc...) values (rec1_field1, rec1_field2, etc...), (rec2_field1, rec2_field2, etc...)
SQL runs flawlessly against a Sandbox/Dev db from a Dev Server. SQL crashes with a NullReference exception ("Object not set to an instance of an object") against the same Sandbox/Dev db from a Production server. The Dev server has Framework version 4.0.30319.18052, and the Production has Framework version 4.0.30319.18063.
I know I haven't given a lot of information here, but anyone have any ideas? Or at least ideas of something to check? I've been banging my head against this one for 3-4 days and nothing is rearing it's ugly head.
TIA!
The error happens on the 'ExecuteNonQuery' below...
string dbConnString = ConfigurationManager.ConnectionStrings[targetDatabase].ToString();
if (null != dbConnString)
{
using (SqlConnection dbConn = new SqlConnection(dbConnString))
{
if (dbConn != null)
{
SqlCommand cmd = new SqlCommand(m_sqlInserts.ToString(), dbConn);
dbConn.Open();
int rowsAdded = cmd.ExecuteNonQuery();
...
So the answer to the question (because I couldn't post more details and I really wanted to know of things to try): is that it's a simple Permissions issue with the account that is running the process not being able to insert records to the table. The comment that helped me get to that conclusion came from #cdonner (Thank you, again!) in wanting to see a stack trace. I realized that I could return a StackTrace in the console log instead of just the InnerException message and it (the SQL Error) was finally revealed.

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

INSERT query OleDB 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()

Categories