Insert into statement error - vb.net

Try
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Jen\Documents\Jade\vb\database.accdb")
txtStatus.Text = "Active"
Dim account As String = ("Insert into Login(Username, Password, FirstName, LastName, AccountType, Status) VALUES ('" & txtUsername.Text & "' , '" & txtPass.Text & "', '" & txtFirst.Text & "', '" & txtLast.Text & "', '" & cmbType.Text & "', '" & txtStatus.Text & "')'")
conn.Open()
ole = New OleDbCommand(account, conn)
ole.ExecuteNonQuery()
MsgBox("Successfully Inserted!")
Dim strsql2 As New OleDbCommand("select * from Login", conn)
Dim sqlda = New OleDbDataAdapter(strsql2)
Dim sqldataset = New DataSet
sqlda.Fill(sqldataset)
Me.DataGridView1.DataSource = sqldataset.Tables(0)
conn.Close()
DataGridView1.Refresh()
an error shows that my insert into statement is incorrect. I already check my database many times and retype the code over but still get the same error.

I have Spotted an Extra (') qoute after closing bracket in query.Use this Query and Check
Dim account As String = ("Insert into Login(Username, Password, FirstName, LastName, AccountType, Status) VALUES ('" & txtUsername.Text & "' , '" & txtPass.Text & "', '" & txtFirst.Text & "', '" & txtLast.Text & "', '" & cmbType.Text & "', '" & txtStatus.Text & "')")
hope this helps.

Are AccountType and Status string type?
if not you should write this:
Dim account As String = ("Insert into Login(Username, Password, FirstName, LastName, AccountType, Status) VALUES ('" & txtUsername.Text & "' , '" & txtPass.Text & "', '" & txtFirst.Text & "', '" & txtLast.Text & "', " & cmbType.Text & ", " & txtStatus.Text & ")'")

Related

VB.NET 2010 Inserting data to table in access

PLease I need help whenever I register my form to database, it says registration successful but the last table (the TRANSACTION table) data information from my form does not input the info in my database only the table FORM and STUDENT have data from my form. Is there something wrong in my TRANSACTION code? or in database?
PLEASE HELP :((
sql = "INSERT INTO FORM VALUES ('" & txtformnum.Text & "' , '" & bcboRequest.Text & "' , '" & txtTotal.Text & "')"
da = New OleDb.OleDbDataAdapter(sql, con) '"
da.Fill(ds, "FORM")
sql = "INSERT INTO STUDENTS VALUES ('" & txtstudnum.Text & "','" & txtSurname.Text & "','" & txtGName.Text & "', '" & txtMName.Text & "', '" & txtAddress.Text & "', '" & status & "' , '" & txtYr.Text & "' , '" & cbostype.Text & "' , '" & chkClearance.Text & "', '" & txtCourse_Track.Text & "' , '" & txtCNumber.Text & "' , '" & dot.Value & "' , '" & dotdue.Value & "')"
da = New OleDb.OleDbDataAdapter(sql, con)
da.Fill(ds, "STUDENTS")
Dim sqlquery As String = "INSERT INTO TRANSACTION (Transaction_num,Stud_num,Form_num,Total Fee)" + "VALUES (" & txttransactionno.Text & ",'" & txtstudnum.Text & "'," & txtformnum.Text & "," & txtTotal.Text & ");"
Dim sqlcommand As New OleDb.OleDbCommand(sqlquery)
I don't know what database you're using, but if you're using MySQL or MS SQL Server then the keyword TRANSACTION is reserved and must be escaped to work within your statement.
If using MySQL, try changing your statement to INSERT INTO "TRANSACTION"
If using SQL Server, change your statement to INSERT INTO [TRANSACTION]
If you're not using either of those, post what database system you're using and I'll post the proper escape syntax.
Try changing this line
Dim sqlquery As String = "INSERT INTO TRANSACTION (Transaction_num,Stud_num,Form_num,Total Fee)" + "VALUES (" & txttransactionno.Text & ",'" & txtstudnum.Text & "'," & txtformnum.Text & "," & txtTotal.Text & ");"
To
Dim sqlquery As String = "INSERT INTO TRANSACTION ([Transaction_num],[Stud_num],[Form_num],[Total Fee]) " + "VALUES ('" & txttransactionno.Text & "','" & txtstudnum.Text & "','" & txtformnum.Text & "','" & txtTotal.Text & "');"
This should work fine.
Add the following to your code:
sqlcommand.ExecuteNonQuery()

keep getting a "System.Data.OleDb.OleDbException: 'Syntax error in UPDATE statement" error

Good day, I keep getting a "System.Data.OleDb.OleDbException: 'Syntax error in UPDATE statement" error.
Can someone please assist with why and where?
Any help will be greatly appriciated
Below is the code
Try
conec.Open()
Dim cmd As New OleDbCommand("UPDATE tblCreate Set Username = '" & txtUserName.Text & "', EMail = '" & txtEmail.Text & "', FirstName = '" & TxtName.Text & "', LastName = '" & txtSurname.Text & "', Access = '" & cmbAccess.SelectedItem & "', CreatedBY = '" & Label9.Text & "', DateCreated = '" & Label10.Text & "', ChangedBY = '" & Label6.Text & "', DateChanged = '" & Date.Now.ToString("yyyy-MMMM-dd hh:mm tt") & "' WHERE UserName = " & txtUserName.Text & ";")
cmd.CommandType = CommandType.Text
cmd.Connection = conec
cmd.ExecuteNonQuery()
MessageBox.Show("Data Updated" & vbCrLf & "Done")
conec.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Looks like you're missing apostrophes in your where clause, try:
Dim cmd As New OleDbCommand("UPDATE tblCreate Set Username = '" & txtUserName.Text & "', EMail = '" & txtEmail.Text & "', FirstName = '" & TxtName.Text & "', LastName = '" & txtSurname.Text & "', Access = '" & cmbAccess.SelectedItem & "', CreatedBY = '" & Label9.Text & "', DateCreated = '" & Label10.Text & "', ChangedBY = '" & Label6.Text & "', DateChanged = '" & Date.Now.ToString("yyyy-MMMM-dd hh:mm tt") & "' WHERE UserName = '" & txtUserName.Text & "';")
I recommend using SQL Parameters however, they're a lot easier to maintain.

Syntax error in INSERT INTO statement. OledbException was unhandled... did everything i saw here in stack but nothing seems to work

Dim cmd As New OleDbCommand
OpenConnection()
cmd.Connection = con
cmd.CommandText = "INSERT INTO [StudentInfo] ([Stud_Num], [Stud_FName], [Stud_LName], [Stud_ContactNum], [Stud_Email], [Stud_Address], [Stud_Username], [Stud_Password], [Stud_ConfirmPassword]) VALUES (" & _
txtStudNum.Text & ", '" & txtFname.Text & "', '" & txtLname.Text & "', '" & _
txtNum.Text & "', '" & txtEmail.Text & "', '" & txtAddress.Text & "' , '" & txtUsername.Text & "', '" & txtPassword.Text & "', '" & txtConPassword.Text & "')"
cmd.ExecuteNonQuery()
The error was the cmd.ExecuteNonQuery() I'm still a student and a noob in using vb.net so please could you tell me what I did wrong ?

Save when new record and update when edit on data occurs

I have my code for save button and update button but is there a way I can combine the two
commands in one button?
For example When I click 'SAVE/UPDATE Button' it will save on the database if it is a new record and it will rather update if the system found that there is already record on the database and save the edited data's
CODE FOR SAVE BUTTON
Dim sqlconn As New SqlClient.SqlConnection
sqlconn.ConnectionString = "server = SKPI-APPS1;" & _
"Database = EOEMS;integrated security=true"
Try
Dim myCommand As New SqlCommand
sqlconn.Open()
myCommand = New SqlCommand("INSERT INTO tblOfficeEquipmentProfile(OE_Category,OE_SubCategory,OE_ID,OE_Name,OE_User,OE_Brand,OE_Model,OE_Specs,OE_SerialNo,OE_PropertyNo,OE_MacAddress,OE_Static_IP,OE_Vendor,OE_PurchaseDate,OE_WarrantyInclusiveYear,OE_WarrantyStatus,OE_Status,OE_Dept_Code,OE_Location_Code,OE_Remarks) VALUES('" & cmbCategory.Text & "','" & cmbSubCategory.Text & "','" & txtOEID.Text & "','" & txtName.Text & "','" & txtUser.Text & "','" & cmbBrand.Text & "','" & cmbModel.Text & "','" & txtSpecs.Text & "','" & txtSerialNo.Text & "','" & txtPropertyNo.Text & "','" & txtMacAddress.Text & "','" & txtStaticIp.Text & "','" & txtVendor.Text & "','" & txtPurchaseDate.Text & "','" & txtWarrantyInclusiveYear.Text & "', '" & txtWarrantyStatus.Text & "','" & txtStatus.Text & "','" & cmbDeptCode.Text & "','" & cmbLocationCode.Text & "','" & txtRemarks.Text & "')", sqlconn)
myCommand.ExecuteNonQuery()
MessageBox.Show("Office Equipment Profile Successfully Added")
sqlconn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
CODE FOR UPDATE BUTTON (NOTE: but still my update button has some error still trying to fix)
Dim sqlconn As New SqlClient.SqlConnection
sqlconn.ConnectionString = "server = SKPI-APPS1;" & _
"Database = EOEMS;integrated security=true"
Dim myCommand As New SqlCommand
Try
'update command
sqlconn.Open()
myCommand = New SqlCommand("UPDATE tblOfficeEquipmentProfile SET OE_Category = '" & cmbCategory.Text & "',OE_SubCategory = '" & cmbSubCategory.Text & "', OE_Name = '" & txtName.Text & "', OE_User = '" & txtUser.Text & "', OE_Brand = '" & cmbBrand.Text & "', OE_Model = '" & cmbModel.Text & "', OE_Specs = '" & txtSpecs.Text & "', OE_SerialNo = '" & txtSerialNo.Text & "', OE_PropertyNo = '" & txtPropertyNo.Text & "', OE_MacAddress = '" & txtMacAddress.Text & "', OE_Static_IP = '" & txtStaticIp.Text & "', OE_Vendor = '" & txtVendor.Text & "', OE_PurchaseDate = '" & txtPurchaseDate.Text & "', OE_WarrantyInclusiveYear = '" & txtWarrantyInclusiveYear.Text & "', OE_WarrantyStatus = '" & txtWarrantyStatus.Text & "', OE_Status = '" & txtStatus.Text & "', OE_Dept_Code = '" & cmbDeptCode.Text & "', OE_Location_Code = '" & cmbLocationCode.Text & "', OE_Remarks ='" & txtRemarks.Text & "' WHERE OE_ID ='" & txtOEID.Text & "'", sqlconn)
Dim iCnt As Integer = myCommand.ExecuteNonQuery()
MessageBox.Show("Office Equipment Profile Successfully Updated " & iCnt & " Records")
Catch ex As Exception
MsgBox(ex.Message)
End Try
You could create an enum that contains the state:
Enum DataState
Editing
Adding
None
End Enum
Then set a class-level variable:
private mDataState as DataState
Then set this according to whether you are adding or editing a record, then in the Save_Click subroutine, use an If-Then.
Write a stored procedure that checks to see if the record exists. If it does, update it. Otherwise, insert it.
Call this stored procedure from your vb.net code. Also, change your .net code so that it sends query parameters to your stored procedure.
Yours is a perennial favorite question here on SO: how to update an existing row or else insert it? And the answers are perennially wrong.
The standard SQL to do this does not have an if statement. The standard way is to insert the row subject to the constraint that it does not exist, and then update it:
insert into T values (...)
where not exists (
select 1 from T as t
where T.key = t.key
)
optionally check the rowcount and only update if it's 0
update T set ...
where T.key = value
If you don't check the rowcount from insert, the update is redundant.
It's better to put all that in a stored procedure but, even if you don't, you should be able to put both statements in one prepared statement, and attach that to one button in your GUI.

Update sql command in vb.net flaws?

i have this code made by myself researching,
it returns no error, it update(s) some of the data entered in textboxes but not all the fields
i check the codes near the field that is updating to compare it to the textboxes that do not
update.
but i dont see the difference, it just not update all fields, only some fields
Dim sqlconn As New SqlClient.SqlConnection
sqlconn.ConnectionString = "server = SKPI-APPS1;" & _
"Database = EOEMS;integrated security=true"
Dim myCommand As SqlCommand
Try
'update command
sqlconn.Open()
myCommand = New SqlCommand(
"UPDATE tblOfficeEquipmentProfile SET OE_Category = '" & cmbCategory.Text
& "',OE_SubCategory = '" & cmbSubCategory.Text
& "', OE_Name = '" & txtName.Text
& "', OE_User = '" & txtUser.Text
& "', OE_Brand = '" & cmbBrand.Text
& "', OE_Model = '" & cmbModel.Text
& "', OE_Specs = '" & txtSpecs.Text
& "', OE_SerialNo = '" & txtSerialNo.Text
& "', OE_PropertyNo = '" & txtPropertyNo.Text
& "', OE_MacAddress = '" & txtMacAddress.Text
& "', OE_Static_IP = '" & txtStaticIp.Text
& "', OE_Vendor = '" & cmbVendor.Text
& "', OE_PurchaseDate = '" & txtPurchaseDate.Text
& "', OE_WarrantyInclusiveYear = '" & cmbWarrantyInclusiveYear.Text
& "', OE_WarrantyStatus = '" & txtWarrantyStatus.Text
& "', OE_Status = '" & txtStatus.Text
& "', OE_Dept_Code = '" & cmbDeptCode.Text
& "', OE_Location_Code = '" & cmbLocationCode.Text
& "', OE_Remarks ='" & cmbRemarks.Text
& "' WHERE OE_ID = '" & txtOEID.Text & "'", sqlconn)
' ^^ (edited to separate lines for ease of viewing )
myCommand.ExecuteNonQuery()
MessageBox.Show("Office Equipment Profile Successfully Updated Records")
Catch ex As Exception
MsgBox(ex.Message)
End Try
Some troubleshooting suggestions:
Try a pattern like this:
Dim SQL As String = "UPDATE STaff Set Initials='RCH' WHERE Initials = 'RCH'"
myCommand = New SqlCommand(SQL, sqlconn)
Dim iCnt As Integer = myCommand.ExecuteNonQuery()
MessageBox.Show("Office Equipment Profile Successfully Updated " & iCnt & " Records")
Place a breakpoint on the second line and use the Text Visualizer to look at the SQL. You can also copy it and use in some other query tool to work on it and find the errors.
Also, capture the number of records changed (iCnt above) and do some QA and/or debug.
Injection: While your project may not be exposed to an injection attack you can step on your self by not making sure that the .Text values don't break the SQL. For example if any of the .Text contains an apostrophe the SQL will fail. You can write a Function to replace ' with '' and you'll be safe.
Or do each: OE_Location_Code = '" & cmbLocationCode.Text.replace("'","''")
This will convert "Fred's Room" to "Fred''s Room"