473,783 Members | 2,286 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Syntax error in OLEDB Insert statement with parameters

5 New Member
Hullo,

I have a quite simple piece of code that returns a syntax error in the query execution: Have you got any idea about what might be wrong?

Expand|Select|Wrap|Line Numbers
  1.          public void SQLCommandWithParam(string name, byte[] image)
  2.             {
  3.             OleDbCommand sqlCommand1 = new OleDbCommand();
  4.             System.Data.OleDb.OleDbConnection myOleConnection = new System.Data.OleDb.OleDbConnection();
  5.             myOleConnection.ConnectionString=connectionString();
  6.             myOleConnection.Open();
  7.             sqlCommand1.Connection = myOleConnection;
  8.             try
  9.                 {
  10.                 if (sqlCommand1.Parameters.Count ==0 )
  11.                     {
  12.                     sqlCommand1.CommandText = "INSERT INTO Image (Name, Immagine) " + 
  13.                            "VALUES(@Name, @Picture);";
  14.                     sqlCommand1.Parameters.Add("@Name",
  15.                              System.Data.OleDb.OleDbType.VarChar, 200);
  16.                     sqlCommand1.Parameters.Add("@Picture",
  17.                              System.Data.OleDb.OleDbType.Binary);
  18.                     }
  19.                 sqlCommand1.Parameters["@Name"].Value = name;
  20.                 sqlCommand1.Parameters["@Picture"].Value = image;
  21.                 sqlCommand1.Connection = myOleConnection;
  22.                 int iresult=sqlCommand1.ExecuteNonQuery();
  23.                 MessageBox.Show(Convert.ToString(iresult));
  24.                 }
  25.             catch(Exception ex)
  26.             {
  27.             MessageBox.Show(ex.Message);
  28.             }
  29.  }
Mar 23 '10 #1
6 5298
tlhintoq
3,525 Recognized Expert Specialist
TIP: When you are writing your question, there is a button on the tool bar that wraps the [code] tags around your copy/pasted code. It helps a bunch. Its the button with a '#' on it. More on tags. They're cool. Check'em out.
Mar 23 '10 #2
fbartolom
5 New Member
I immediately follow your suggestion in posting another try, this time with an ODBCDrvriver: here the error appears at connection time and reports a reference to an unassigned object. This is the new code:

Expand|Select|Wrap|Line Numbers
  1.  
  2. public void SQLCommandWithParam(string name, byte[] image)
  3.          {
  4.             OdbcConnection conn = new OdbcConnection();
  5.             conn.ConnectionString = @"Dsn=.\DataBase\BRP.mdb";
  6.             conn.Open();
  7.             string sqlQuery = "INSERT INTO Image ([Name], [Picture]) " +
  8.                            "VALUES(@Name, @Picture);";
  9.             OdbcCommand dbcommand = new OdbcCommand(sqlQuery, conn);
  10.             dbcommand.Parameters.Add("@Name", OdbcType.VarChar,200).Value = name;
  11.             dbcommand.Parameters.Add("@Picture", OdbcType.VarBinary).Value = image;
  12.  
  13.             try
  14.             {
  15.                 int count = dbcommand.ExecuteNonQuery();
  16.             }
  17.             catch (OdbcException ex)
  18.             {
  19.                 MessageBox.Show(ex.Message);
  20.             }
  21.           }
  22.  
Mar 23 '10 #3
tlhintoq
3,525 Recognized Expert Specialist
reports a reference to an unassigned object
"How do I fix a 'object reference not set to an instance of an object' error?
The line your code stopped on while debugging holds all your answers.
One of the variables/objects was created but not initialized. For example:
Expand|Select|Wrap|Line Numbers
  1. string TempString;// Created but not initialized so this is still null
  2. //versus
  3. string TempString = string.empty;
Debug your project again. This time, when it breaks on a line look at the Locals pallet to see which variable/object is null. You can also hover your mouse over each variable and the hothelp will shows its value. One of them will be null.
Mar 23 '10 #4
fbartolom
5 New Member
So far I can get myself on my own feet..., after all I am in programming since my graduation 20 years ago, albeit not in the .Net environment and with gaps.

The problem is that the error is returned _inside_ the opening of the connection where the debugger has no way to enter.
In the previous case it was _inside_ the query execution, exactly in the same situation.
Mar 23 '10 #5
fbartolom
5 New Member
In the following the revised message: please delete the present one if possible, I am not able to do it myself.
Mar 23 '10 #6
fbartolom
5 New Member
In brief the only involved variable is conn, the connection, which has all values assigned but the Server Version and Base that cannot be otherwise because the connection is closed: what is not suprising given what is applied to the conn variable is the open operation. This is the expanded pallette.
Of course that might all boil down to the connection string I got from various internet sites: another one I found is the following, returning the same error: at the bottom the pallette for this other configuration:

Alternative connection string:
Expand|Select|Wrap|Line Numbers
  1.             OdbcConnection con = new OdbcConnection(@"{Microsoft Access Driver (*.mdb)};DSN=.\DataBase\BRP.mdb;Uid=Admin;Pwd=;");
  2.  
First pallette:

Expand|Select|Wrap|Line Numbers
  1.  
  2. -        conn    {System.Data.Odbc.OdbcConnection}    System.Data.Odbc.OdbcConnection
  3. +        base    {System.Data.Odbc.OdbcConnection}    System.Data.Common.DbConnection {System.Data.Odbc.OdbcConnection}
  4.         ConnectionString    "Dsn=.\\DataBase\\BRP.mdb"    string
  5.         ConnectionTimeout    15    int
  6.         Database    ""    string
  7.         DataSource    ""    string
  8.         Driver    ""    string
  9. -        ServerVersion    'conn.ServerVersion' ha generato un'eccezione di tipo 'System.InvalidOperationException'    string {System.InvalidOperationException}
  10. -        base    {"Operazione non valida. La connessione è chiusa."}    System.SystemException {System.InvalidOperationException}
  11. -        base    {"Operazione non valida. La connessione è chiusa."}    System.Exception {System.InvalidOperationException}
  12. +        Data    {System.Collections.ListDictionaryInternal}    System.Collections.IDictionary {System.Collections.ListDictionaryInternal}
  13.         HelpLink    null    string
  14. +        InnerException    null    System.Exception
  15.         Message    "Operazione non valida. La connessione è chiusa."    string
  16.         Source    "System.Data"    string
  17.         StackTrace    "   in System.Data.ProviderBase.DbConnectionClosed.get_ServerVersion()\r\n   in System.Data.Odbc.OdbcConnection.get_ServerVersion()"    string
  18. +        TargetSite    {System.String get_ServerVersion()}    System.Reflection.MethodBase {System.Reflection.RuntimeMethodInfo}
  19. +        Membri statici        
  20. +        Membri non pubblici        
  21.  
Second pallette:

Expand|Select|Wrap|Line Numbers
  1. -        con    {System.Data.Odbc.OdbcConnection}    System.Data.Odbc.OdbcConnection
  2. -        base    {System.Data.Odbc.OdbcConnection}    System.Data.Common.DbConnection {System.Data.Odbc.OdbcConnection}
  3. +        base    {System.Data.Odbc.OdbcConnection}    System.ComponentModel.Component {System.Data.Odbc.OdbcConnection}
  4.         ConnectionString    "{Microsoft Access Driver (*.mdb)};DSN=.\\DataBase\\BRP.mdb;Uid=Admin;Pwd=;"    string
  5.         ConnectionTimeout    15    int
  6.         Database    ""    string
  7.         DataSource    ""    string
  8. -        ServerVersion    '((System.Data.Common.DbConnection)(con)).ServerVersion' ha generato un'eccezione di tipo 'System.InvalidOperationException'    string {System.InvalidOperationException}
  9. +        base    {"Operazione non valida. La connessione è chiusa."}    System.SystemException {System.InvalidOperationException}
  10.         State    Closed    System.Data.ConnectionState
  11. +        Membri non pubblici        
  12.         ConnectionString    "{Microsoft Access Driver (*.mdb)};DSN=.\\DataBase\\BRP.mdb;Uid=Admin;Pwd=;"    string
  13.  
Mar 23 '10 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

7
6672
by: kosta | last post by:
hello! one of my forms communicates with a database, and is supposed to add a row to a table using an Insert statement... however, I get a 'oledb - syntax error' exception... I have double checked, and the insert works fine (tried to use it from access)... im using visual C# express 2k5... what could be wrong? thanks!
4
3667
by: Robert Hanson | last post by:
Hi All, I am trying to add a record to a datatable that is connected to an Access database. I had no trouble with string and date fields, but for this record, I have two Long Integer field types and I get the following error: "Data type mismatch in criteria expression." I am using OleDbType.Integer as the type which matched the Int32 size for the Long Integer in Access, but I can't seem to get past the error.
2
2853
by: Joe | last post by:
Hello All, I am trying to insert a record in the MS Access DB and for some reason I cannot get rid of error message, System.Data.OleDb.OleDbException: Syntax error in INSERT INTO statement. And the line it shows in red is cmd.ExecuteNonQuery()
3
2500
by: Nathan Sokalski | last post by:
When trying to submit data to an Access database using ASP.NET I recieve the following error: System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(Int32 hr) +41 System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) +174 System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) +92
1
5427
by: Joe | last post by:
Hello All, I am trying to insert a record in the MS Access DB and for some reason I cannot get rid of error message, System.Data.OleDb.OleDbException: Syntax error in INSERT INTO statement. And the line it shows in red is cmd.ExecuteNonQuery()
3
6737
by: brianbasquille | last post by:
Hello all, Strange little problem here... am just trying to insert some basic information into an Access Database using OleDB. I'm getting a "Syntax error in Insert Into statement" when it tries to execute the SQL. The strange thing is if i take the exact SQL being executed from the debugger and insert and execute it using the MS Access query engine, it works fine!
4
2284
by: Warex | last post by:
Maybe someone can help, my code works untill it gets to update when it tells me Syntax error in INSERT INTO statement. Thought this was automaticaly created according to MS. Im lost, my code is below to copy and paste. Just change to your database, tablename, fields to edit and sql. AGGHHHHHH thanks Public Sub insertit(ByRef Msql As String)
2
4209
by: slinky | last post by:
I'm getting a error when I open my . aspx in my browser... line 34: da.Fill(ds, "Assets") Here's the error and my entire code for this .aspx.vb is below that ... I need some clues as to what is causing the error... Thanks!!! Server Error in '/' Application. ---------------------------------------------------------------------------­----- Multiple-step OLE DB operation generated errors. Check each OLE DB
1
2706
by: gilesy | last post by:
Hi, I have a ploblem with an insert statement using an access database, I have the same code with a sql database which works but it doesn't seem to work on access. Could someone please help. For i = 0 To dg.Rows.Count - 1 Main.Command.CommandText = "INSERT INTO Diary (Date1, Time, Appointment) VALUES (?, ?, ?)" Dim param1 As System.Data.OleDb.OleDbParameter = New System.Data.OleDb.OleDbParameter("Date1", dg(1,...
3
5238
by: gilesy | last post by:
Hi, I have a ploblem with an insert statement using an access database, I have the same code with a sql database which works but it doesn't seem to work on access. Could someone please help. For i = 0 To dg.Rows.Count - 1 Main.Command.CommandText = "INSERT INTO Diary (Date1, Time, Appointment) VALUES (?, ?, ?)" Dim param1 As System.Data.OleDb.OleDbParameter = New System.Data.OleDb.OleDbParameter("Date1", dg(1, i).Value) Dim param2 As...
0
10315
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10083
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9946
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8968
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5379
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4044
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2877
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.