INSERT INTO command not working - c#

Before I start, I'll let you know that I tried everything that has already been suggested on previous questions and other websites before I considered posting a question myself. As it happens, nothing seems to work and I'm just about fed up with this.
As some background information, this is for my Computing A2 project, so I'm kind of stuck for time now - i.e. I can't be changing loads of my code ideally.
Anyway, onto the issue...
I'm using SQLCe in my code to read from various tables and write to one. So far, the code for reading from the tables works fine, so that's any connection issues out the way first. The piece of code I am struggling with is as follows:
string connectionString = Properties.Settings.Default.BookingSystemDatabaseConnectionString;
using (SqlCeConnection myConnection = new SqlCeConnection(connectionString))
{
myConnection.Open();
try
{
string commandStr = "INSERT INTO bookings(username, room, time) VALUES(#username, #room, #time)";
SqlCeCommand myCommand = new SqlCeCommand(commandStr);
//Passes parameters into SQL command.
myCommand.Parameters.AddWithValue("username", StaticUser.StudentUser.username);
myCommand.Parameters.AddWithValue("room", roomBox.Text);
myCommand.Parameters.AddWithValue("time", timeBox.Text);
//Executes SQL command. Returns the number of affected rows (unecessary for my purposes; a bi-product if you will).
myCommand.ExecuteNonQuery();
}
catch
{
System.Windows.Forms.MessageBox.Show("Could not write new booking to database. This is likely because the database cannot be reached.", "Error");
Program.AccessError = true;
}
myConnection.Close();
}
This is just one of the many ways I have tried to combat the issue I am having. I have also explored:
myCommand.Parameters.Add(new SqlCeParameter("username", StaticUser.StudentUser.username));
to pass the parameters...and another method which escapes me now (using ".Value = StaticUser.StudentUser.username" I think). Furthermore, I have tried using a 'using' statement for the command to save me closing the connection myself (I will probably end up using a solution that uses 'using'). Finally (albeit this isn't a chronological recollection), I tried:
SqlCeCommand myCommand = new SqlCeCommand("INSERT INTO bookings(username, room, time) VALUES(#username, #room, #time)", myConnection)
Again, of course, to no avail.
To highlight the actual symptoms of the issue I am having: The code appears to run fine; stepping through the full method I have pasted above shows that no error is being caught (of course, the message box does not appear - I realised afterwards that stepping through was arguably an unnecessary procedure) and in the other methods I have touched on, the same thing happens. The issue, then, is that the table 'bookings' is not actually being updated.
So, my question, why?
I didn't do the obvious and check the Debug folder for an updated database.

Look for a copy of the database file in your bin/debug folder.
Use full path in connection string, and preferably do not include the sdf file in your project (or at least set build action to None)

i think you are not defining a connection for the command
try
mycommand.connection = connectiostring;

Related

AdsConnection throws EntryPointNotFoundException on second connection but works the first time

I have a piece of code that I reuse that helps me connect to an adt database and read the data.
using Advantage.Data.Provider;
...
protected DataTable FillTable(string tableName)
{
DataTable table = new DataTable();
using (var conn = new AdsConnection(connectionString))
using (var adapter = new AdsDataAdapter())
using (var cmd = new AdsCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select * from " + tableName;
adapter.SelectCommand = cmd;
conn.Open();
adapter.Fill(table);
conn.Close();
}
return table;
}
This code works perfectly the first time I go through it, but gives the following exception the second time I call it with a different table name.
System.EntryPointNotFoundException: 'Unable to find an entry point named 'AdsIsConnectionAlive' in DLL 'ace32.dll'.'
I would like an explanation.
I've tried to read up on this error, but all the possible scenario's I've found don't explain why it works the first time. They mention problems with the DLL like it being the wrong version or some incompatability with the .NET version, ...
If I change the order of the calls the code still fails on the second time, so I know the problem isn't with the name of the table or the way I call my code. The problem is probably with me not closing the connection correctly. I've tried adding more braces just to make sure that that part runs correctly and I've debugged to make sure that the first conn.Close(); is executed correctly.
I could place all my code within this code and only use one connection that I keep open as long as I need it. That would bypass my problem, but I would like to avoid that and to understand what I'm doing wrong.
This is most likely caused by loading an older version of ace32.dll from a newer version of the ado.net components. The AdsIsConnectionAlive was introduced in a later version of the DLL - not sure about the exact version probably 6.0 or later.
The first time the connection was made, the ado.net component knows that the connection was not alive so there was no need to call the IsAlive entry point. The second time around, since there was already a connection made to the same connection path, it would try to reuse it by checking to see if it is still alive. I think that there is a way to disable the connection caching but do not remember the detail. A better solution would be to make sure that the advantage DLLs are matching version.

Oracle Managed DataAccess connection object is keeping the connection open

I'm using Oracle.ManagedDataAccess Nuget package version 18.3.0. I tried many things. I tried to dispose everything I can think of, even oracle parameters objects. And wrapped everything inside a using block but to no avail. The only thing that actually worked for me is that the commented line OracleConnection.ClearPool(oracle);. Is this a bug, or some configuration related issue, or am I misunderstand things here? Also, I tried to remove the reference of Oracle.ManagedDataAccess and replaced it with a reference to System.Data.OracleClient and that actually worked for me. It automatically closed the connection, so no connection left with "In-Active" status. The code below I moved it into a simple, single button, Windows Forms application to make 100% sure nothing is interfering and the problem still occurring.
using (var oracle = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=myhost)(PORT=SomePortHere))(CONNECT_DATA=(SERVER=SHARED)(SERVICE_NAME=anotherHost)))", new OracleCredential(userName,password)))
{
oracle.Open();
using (var command = new OracleCommand())
{
var query = "SELECT x from y where z=:param1";
command.Connection = oracle;
command.CommandText = query;
command.CommandType = System.Data.CommandType.Text;
var param1 = new OracleParameter(":param1", xyz);
command.Parameters.Add(param1);
using (var reader = command.ExecuteReader())
{
if (reader.Read())
{
//read the data from the reader
}
}
param1.Dispose();
}
//If this line is commented, there will be a connection left open, with InActive status
//OracleConnection.ClearPool(oracle);
}
password.Dispose();
return myData;
And this is an image to show the opened connection through Toad.
Of course, for each click to that button, the code above will execute and a new session will remain open, until what you see in the image.
The name "TheTesterOfAllTests.exe" is the Windows Forms app.
Is this a configuration problem?
Is there any way to solve this issue other than using ClearPool method? Because it affects the performance of the app.
P.S. The application that is originally using the code above is a WCF Service that is consumed by a Web application.
P.S. 2 There is some kind of memory leakage, with each click to that button the memory usage increases
I ran into the same problem.
I solved it by changing the initialization of the OracleConnection.
from
var con = new OracleConnection(
"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=myhost)(PORT=SomePortHere))(CONNECT_DATA=(SERVER=SHARED)(SERVICE_NAME=anotherHost)))",
new OracleCredential(userName,password));
to
var con = new OracleConnection(
"USER ID=myuser;PASSWORD=mypwd;Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=myhost)(PORT=SomePortHere))(CONNECT_DATA=(SERVER=SHARED)(SERVICE_NAME=anotherHost)))");
To me, this different behavior looks like a bug.
As a result, i can no longer use OracleCredential and must store the password as a string. That's okay for me.
remark: SecureString shouldn't be used
It turns out the problem is in the way internally oracle creates connection, since for each newly created OracleConnection object, a new Connection is added to the Connection pool. I counted 91 connection entry in the connection pool.
The solution was to use one OracleConnection instance for each request "Per Request Scope". I implemented that by using a simple generic IDatabase<TConnection> interface with one TConnection GetConnection<TConnection>() method and of course for each method that will be called on that same request's instance, a pair of Open/Close call will take place so we don't keep the connection open the whole time.
Regarding the memory leak, I'm still not able to 100% confirm this, but when I used the Oracle.DataAccess.Client library instead of Oracle.ManagedDataAccess the memory usage reduced dramatically. So, I switched back to Oracle.DataAccess.Client.
P.S. I will update this answer in case of new information regarding these two issues, and contributions are very welcome, maybe I misunderstand something regarding how Oracle deals with the database connection.

"table or view does not exist", but only sometimes

A SQL select statement gets run when a user presses a button on my website, and I do this:
connection = new OleDbConnection();
connection.ConnectionString = [connection string];
connection.Open();
cmd = profile.Execute(mySQLStatement);
da = new OleDbDataAdapter(cmd);
table = new DataTable();
da.Fill(table);
90% of the time, this works just fine. But every once in a while, I get the OleDbException table or view does not exist on the line da.Fill(table). There doesn't seem to be a pattern of when this works and when it doesn't, though it's more likely to not work when the site isn't used for a minute or two... Like the session might be expiring. But the rest of the website (that does not require this database) works.
Any ideas of what might be happening or how to fix it?
I have not found a solution. As a temporary fix, whenever this happens, I just re-start the page.
Sometimes the content of mySqlStatement is not exactly correct, maybe?
Trap the exception dump mySqlStatement to a logfile (with date and time this happened), and then throw.

Update table (rows) Access 2007 and C# 2010

So this is probably the most naive question but that is what questions are for I guess;
Then, my issue is that I have no idea on how to connect Visual C# Express 2010 to Access 2007 and do the typical insert, update, delete, search in an application in C#, I have just learned the basics (finished a console tutorial, which I believe is more than enought, having previous background of VB6 using access 97), and I have been searching here and in the web, but the only thing I could find where the msdn tutorials which I dind't find really clear.
So in my app I just need to link comboboxes, query those values to obtain new ones, do calculations and then store in arrays (and maybe show these in datagrids as well as edit them from said datagrids, which is a bit more complicated I guess) and finally store them in various tables, but I haven't really found a strong (or most likely simple) manual that will guide me to create the typical app insert, update, delete using winforms.
Do you guys have any good links in order to do this?
Thanks.
You can try with this code
Here link about string connection : http://www.connectionstrings.com/access-2007
var query = "...";
var connectionString = "...";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
// The insertSQL string contains a SQL statement that
// inserts a new row in the source table.
using(var command = new OleDbCommand(query))
{
// Set the Connection to the new OleDbConnection.
command.Connection = connection;
// Open the connection and execute the insert command.
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
}

Simple SQL Insert

I'm new to databases and am trying to add a new record using SQL. The code runs fine the first time, but the second time throws an error saying that it can't write duplicates to a unique key. The third time runs fine, but the fourth time throws the error. Basically, it seems that every other time, the error is thrown. I understand why the error would be thrown if data was written, but when I examine the database, it remains empty. What am I doing wrong in my code that is causing the query to not bother writing the data?
EDIT If I enter the SQL directly within the database, it works. It doesn't work when I use the C# code below.
using (SqlCeConnection con = new SqlCeConnection(conString))
{
con.Open();
using (SqlCeCommand com = new SqlCeCommand("INSERT INTO User (Name, Age, URL) VALUES ( #name, #age, #url )", con))
{
com.Parameters.AddWithValue("#name", "James Y");
com.Parameters.AddWithValue("#age", 28);
com.Parameters.AddWithValue("#url", "www.example.com" );
com.ExecuteNonQuery();
}
}
I've partially figured it out. Apparently you have to also download SQL CE Tools for Visual Studio. I did this and I had a new option to include SQL CE 4 into my project (I was using the SQLCE option, assuming that it would use 4.0 by default since that's the one I installed). Only problem now is that when I try and add it, it says that it's not supported by the project type (Console project). I saw a post on MSDN that said that SQLCE 4 was for web-only projects but it was a post from a few months back and the current download page says it's for web or desktop applications. Either way, this is proving to be too much of a hassle to bother with and so I'm just going to look for an alternate database if I can't resolve this soon.
FIXED I uninstalled SQLCE4 and the SQLCE Tools, then reinstalled them.
Try and do the following as your SQL:
INSERT INTO [User] (Name, Age, URL) VALUES ( #name, #age, #url )
User is a reserved word in sql server. You should try not to name your table as "user".
Name is a reserved word. Wrap it in []
using (SqlCeCommand com = new SqlCeCommand("INSERT INTO User ([Name], Age, URL) VALUES ( #name, #age, #url )", con))
Since you use DataDirectory in your connection string, the file is copied to your bin/debug folder, so you have several copies of the database, one in your project and one in your debug folder. Make the connection string a full path to avoid any confusion while debugging!

Categories

Resources