Click here to Skip to main content
15,888,282 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I want to insert data from the form into two mysql tables and insert the first table generated auto number into another table. I tried the below but it gives me the error in the line cmd.CommandText = str_sql

C#
An unhandled exception of type 'System.InvalidOperationException' occurred in MySql.Data.dll




pls help regards.

What I have tried:

VB
Function addrec()
       connect()
       Dim ireturn As Boolean
       Dim str_sql As String = "INSERT INTO `people`( `first_name`, `last_name`, `phone_number`,`mobile`, `email`, `address`,  `city`, `state`, `zip`, `country`, `comments`) VALUES (@firstname,@lastname,@phone,@mobile,@email,@address,@city,@state,@zip,@country,@comments)"
       cmd = New MySqlCommand
       cmd.CommandText = str_sql
       With cmd
           .CommandType = CommandType.Text
           .Parameters.AddWithValue("@firstname", txtfirstname.Text)
           .Parameters.AddWithValue("@lastname", txtlastname.Text)
           .Parameters.AddWithValue("@phone", txtphone.Text)
           .Parameters.AddWithValue("@mobile", txtmobile.Text)
           .Parameters.AddWithValue("@email", txtemail.Text)
           .Parameters.AddWithValue("@address", txtaddress.Text)
           .Parameters.AddWithValue("@city", txtcity.Text)
           .Parameters.AddWithValue("@state", txtstate.Text)
           .Parameters.AddWithValue("@zip", txtzip.Text)
           .Parameters.AddWithValue("@country", txtcountary.Text)
           .Parameters.AddWithValue("@comments", txtcomments.Text)
       End With
       Dim newAutoNumberValue As Integer
       Try
           cmd.ExecuteNonQuery()
           cmd.CommandText = "SELECT @@IDENTITY"
           newAutoNumberValue = cmd.ExecuteScalar()
           ireturn = True
           ' MsgBox("Record added successfully!",, "Succeeded")
           'ClearTextBoxes()
       Catch ex As MySqlException
           MsgBox(ex.Message.ToString)
           ireturn = False
       Finally
           ' dbcon.Close()
       End Try

       Dim str_sql2 As String = "INSERT INTO `customer`( `person_id`, `company`, `bank_name`,`account_number`)VALUES (@autonum,@company,@bank,@acc)"
       cmd = New MySqlCommand
       cmd.CommandText = str_sql2
       With cmd
           .Parameters.AddWithValue("@autonum", newAutoNumberValue)
           .Parameters.AddWithValue("@company", txtcompany.Text)
           .Parameters.AddWithValue("@bank", txtbank.Text)
           .Parameters.AddWithValue("@acc", txtaccnum.Text)
       End With

       Try
           cmd.ExecuteNonQuery()
           ireturn = True
           MsgBox("Record added successfully!",, "Succeeded")
           'ClearTextBoxes()
       Catch ex As MySqlException
           MsgBox(ex.Message.ToString)
           ireturn = False
       Finally
           dbcon.Close()
       End Try
       Return ireturn
   End Function
Posted
Updated 10-May-16 20:09pm

For starters, that should be in a transaction - if either part fails, it should roll back both INSERT operations.
I'd suggest that you should do this as a Stored Procedure with the transaction, and use LAST_INSERT_ID()[^] to insert in the second table.
 
Share this answer
 
Comments
nyt1972 10-May-16 3:21am    
Dear thanks for the reply but I get the error in the line before the Identity line which is cmd.ExecuteNonQuery(), and even if I remove the code for the 2nd table I get error in the same line.
OriginalGriff 10-May-16 3:34am    
So put a try...catch around it and look at the exception object, and particularly the Inner Exception detail. Does it give you any more info?
nyt1972 10-May-16 3:50am    
Exception detail is below:

System.NullReferenceException was unhandled
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=POS_test
StackTrace:
at POS_test.frmCustomer.addrec() in D:\Projects\vb.net\POS_test\POS_test\frmCustomer.vb:line 13
at POS_test.frmCustomer.btnAdd_Click(Object sender, EventArgs e) in D:\Projects\vb.net\POS_test\POS_test\frmCustomer.vb:line 5
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
at POS_test.My.MyApplication.Main(String[] Args) in :line 81
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
OriginalGriff 10-May-16 3:59am    
So...it's not an InvalidOperationException, it's a NullReferenceException.

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterdays shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
My apology the table name is customers and not customer. and that solved the issue.

Thanks for yours replies.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900