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()
Related
I need to save data automatically without pressing any button from datagridview to sql database where admission number and names are retrieved from another table and insert score to another table.
For Each row As DataGridViewRow In DataGridView1.Rows
If cmbexam.Text = "CAT 1" And cmbpaper.Text = "Paper 1" Then
sqlSTR = "SELECT AdmNo, Name, Class, Stream, Term, Exam, Subject, Paper, Limit, Score FROM CT11 WHERE (AdmNo = '" & row.Cells(0).Value & "') AND (Name = '" & row.Cells(1).Value & "')"
ExecuteSQLQuery(sqlSTR)
If sqlDT.Rows.Count > 0 Then
sqlSTR = "UPDATE CT11 SET AdmNo ='" & row.Cells(0).Value & "', Name ='" & row.Cells(1).Value & "', Class ='" & cmbform.Text & "', Stream ='" & cmbstream.Text & "', Term ='" & cmbterm.Text & "', Exam ='" & cmbexam.Text & "', Subject ='" & cmbsubject.Text & "', Limit ='" & txtlimit.Text & "', Score ='" & row.Cells(2).Value & "' WHERE (AdmNo = '" & row.Cells(0).Value & "') AND (Name = '" & row.Cells(1).Value & "') AND (Class ='" & cmbform.Text & "') AND (Stream = '" & cmbstream.Text & "') AND (Term = '" & cmbterm.Text & "') AND (Exam = '" & cmbexam.Text & "') AND (Subject = '" & cmbsubject.Text & "')"
ExecuteSQLQuery(sqlSTR)
Else
sqlSTR = "INSERT INTO CT11(AdmNo, Name, Class, Stream, Term, Exam, Subject, SP, Paper, Limit,Score) VALUES ('" & row.Cells(0).Value & "', '" & row.Cells(1).Value & "', '" & cmbform.Text & "', '" & cmbstream.Text & "', '" & cmbterm.Text & "', '" & cmbexam.Text & "', '" & cmbsubject.Text & "', '" & CheckBox2.CheckState & "', 'Paper 1', '" & txtlimit.Text & "','" & row.Cells(2).Value & "')"
ExecuteSQLQuery(sqlSTR)
End If
End If
Next
It's all about Events:
The concept of event-oriented programming is also well suited for the implementation of graphical user interfaces, where the events are mostly user actions, such as pressing a key or clicking a button. Another important field of application are computer simulations, which are set up in such a way that state changes are only triggered by events, and which in turn trigger events (see event-oriented simulation).
Quote from Wikipedia.
I think most developers use the FocusLost-Event to handle Datatransfer if you want to update your database immediately every time you change a value you can try the CellValueChanged-Event.
I have written an insert query which inserts datetime along with other columns. It works fine for all locations except when
my German client logs in and runs the application it gives him below error. I have formatted the datevalue to yyyy-mm-dd to make
culture independent.
MS access database is stored in a server in US.
German client is running application from Germany.
strDateSubmit = dtpDateSub.Value.ToString("yyyy-MM-dd")
strSaveOSTR = "INSERT INTO " & strOSTR & " ([OSTR #],[OSTR Type],[# of Samples],[RA#],[Customer],[SKF #],[Test Description]," & _
"[TestLength],[TestUnit],[TestLengthDays],[Requestor],[Date Submitted],[Seals Avail],[Fixtures Available],[Peripherals Avail],[PO Avail]," & _
"[Machine Type],[Hours to Process],[Location],[Current Status],[ErrorsPresent],[ContaminType]" & SampleREcvd1 & ", [Emp_ID],[Industry])" & _
" Values ( '" & strOSTRNum & "', '" & cmbOSTRTypes.Text & "', " & intSamples & ", '" & strRA & "', '" & strCustomer & "', '" & strSKFNum & _
"', '" & strTestDescr & "', " & intTestLength & ", '" & strTestUnits & "', '" & txtTestLDays.Text & "', '" & strRequestor & "', #" & strDateSubmit & "#, '" & strSealAvail & _
"', '" & strFixtAvail & "', '" & strPheriAvail & "', '" & strPOAvail & "', '" & strMachineClass & "', " & intHrstoProc & ",'" & g_objProp.Location & _
"', '" & strStatus & "', '" & ErrorsPresent & "', '" & ContaminationType & "'" & SampleREcvd2 & ", '" & emp_id & "', '" & Industry & "')"
Error: Syntaxfehler in Datum in Abfrageausdruck '#01.02.2016'
Do yourself a favor: Scrap the dynamic SQL and use a parameterized query, e.g.,
sampleSQL = "INSERT INTO TableName ([Date Submitted]) VALUES (?)"
Dim cmd = New OleDbCommand(sampleSQL, conn)
cmd.Parameters.AddWithValue("?", dtpDateSub.Value)
cmd.ExecuteNonQuery()
That way you can use the actual DateTime value returned by the DateTimePicker. You don't have to be concerned with locale settings or string formats or any of those aggravations.
You may need a more strict format of the date expression string:
strDateSubmit = dtpDateSub.Value.ToString("yyyy'/'MM'/'dd")
This will always return a date like "2016/02/01" (no dots or dashes), and it will concatenate correctly here:
"', #" & strDateSubmit & "#, '"
as you intend.
Having the weirdest problem ever. I do have an sql insert statement, that properly works in sql. When i put that sql into vba it works very good from my pc. However, it does not work and shows sql error: missing comma. Where can be the problem??? I use Access 2010 plus, others use same Access version and having same ODB connections (DSN servers) . Some code example:
sql = "Driver={Microsoft ODBC for Oracle}; " & _
"CONNECTSTRING=(DESCRIPTION=" & _
"(ADDRESS=(PROTOCOL=TCP)" & _
"(HOST= ODB)(PORT=1520))" & _
"(CONNECT_DATA=(SERVICE_NAME=ABTL))); uid=IN; pwd=XXX;"
Set con = New ADODB.Connection
Set rec = New ADODB.Recordset
Set cmd = New ADODB.Command
con.Open sql
Set db = CurrentDb()
Set rst = db.OpenRecordset(strSQL)
Do While Not rst.EOF
insetSQL = con.Execute(" INSERT INTO STOCK (PNM_AUTO_KEY, PN, DESCRIPTION, HISTORICAL_FLAG, qty_oh, qty_adj, qty_available, CTRL_NUMBER, CTRL_ID, receiver_number, rec_date, serial_number,pcc_auto_key, cnc_auto_key, loc_auto_key, whs_auto_key, unit_cost, adj_cost, stc_auto_key, visible_mkt, remarks, ifc_auto_key, exp_date, unit_price, tagged_by, tag_date, owner, PART_CERT_NUMBER,ORIGINAL_PO_NUMBER, SHELF_LIFE, CTS_AUTO_KEY, MFG_LOT_NUM, AIRWAY_BILL )" & _
" VALUES ( " & rst![minimumas] & ", '" & rst![pn] & "', '" & "FROM_SCRIPT" & "', '" & "F" & "'," & rst![qty_oh] & "," & rst![qty_oh] & "," & rst![qty_oh] & "," & "G_STM_CTRL_NUMBER.nextval" & "," & "1" & ", '" & rst![receiver_number] & "', " & " TO_DATE('" & rst![rec_date] & "','YYYY-MM-DD'), '" & rst![serial_number] & "'," & rst![pcc_auto_key] & "," & rst![cnc_auto_key] & "," & rst![loc_auto_key] & "," & rst![whs_auto_key] & "," & rst![unit_cost] & "," & rst![unit_cost] & "," & "1" & ",'" & "T" & "', '" & rst![remarks] & "'," & _
"1" & ", " & " TO_DATE('" & rst![exp_date] & "','YYYY-MM-DD'), " & "0" & ",'" & rst![TAGGED_BY] & "', " & " TO_DATE('" & rst![tag_date] & "','YYYY-MM-DD'), '" & "" & "', '" & rst![PART_CERT_NUMBER] & "', '" & rst![ORIGINAL_PO_NUMBER] & "', '" & rst![SHELF_LIFE] & "', " & rst![CERT_SOURCE] & ", '" & rst![MFG_LOT_NUM] & "', '" & rst![AIRWAY_BILL] & "'" & " )")
Loop
It might be that one of the rescordset fields that is a string data type, has a value that contains a comma but you have not treated it as string.
eg
VALUES ( " & rst![minimumas] & ",
For the above code to work minimumas CANNOT contain any commas.
Are you certain that all the string fields int he recordset have been appended to the SQL string with a ' around them.
We need to see the sql string is created which then causes the error. Please provide this as requested.
=========================================================
PART 2 Viewing the SQL causing the error
replace
insetSQL = con.Execute(
with
on error resume next
strMySQl = the string currently used in the execute statement
insetSQL = con.Execute(strMySQl)
if err.number <> 0 then
stop
debug.print err.number, err.description
debug.print strMySQl
end if
then post the sql string that is printed in the immediate window to this site.
I would also suggest that you compare the SQL string generated on your machine with the other machines - just in case something weird is happening.
following is the code which is use to enter datagridview items into the table.
Dim X As DataGridViewRow
grnno = 123123
glocation = txtlocation.Text
gsupplier = txtsupplier.Text
greceivedby = txtreceivedby.Text
greceiveddate = txtreceiveddate.Text
grn_status = cmbstatus.SelectedItem
ggrossamt = txtgrossamt.Text
gdiscountamount = txtdiscount.Text
gtotalnetamount = txttotalnet.Text
sqlstr = "INSERT INTO POS_GRN_HDR(loc_code,supplier_code,created_by,created_Date,grn_status,gross_amt,disc_Amt,net_Amt) values('" & glocation & "','" & gsupplier & "','" & greceivedby & "','" & greceiveddate & "','" & grn_status & "'," & ggrossamt & "," & gdiscountamount & "," & gtotalnetamount & " )"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.ExecuteNonQuery()
For Each X In datagridItems.Rows
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) VALUES('" & grnno & "','" & X.Cells(0).Value & "','" & X.Cells(1).Value & "','" & X.Cells(2).Value & "','" & X.Cells(3).Value & "','" & X.Cells(4).Value & "','" & X.Cells(5).Value & "','" & X.Cells(6).Value & "','" & X.Cells(7).Value & "' ,'" & X.Cells(8).Value & "','" & X.Cells(9).Value & "','" & X.Cells(10).Value & "')"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.ExecuteNonQuery()
Next
the error is in the 2nd insert statement, it gives error cannot convert string to integer.. the cells from x.cell(6) are of integer type and in database also its integer type, now I want to ask should I enclose it in single quotations or not, as enclosing in single quotations give such errors like syntax '' and in double quotations it gives like cannot convert string to int type.please tell where I am doing wrong.
First of all use parametrized queries! It is safer and also more readable. You are passing some value as string but should be integer.
sqlstr = "INSERT INTO POS_GRN_HDR(loc_code,supplier_code,created_by,created_Date,grn_status,gross_amt,disc_Amt,net_Amt) _
values(#glocation, #gsupplier, #greceivedby, #greceiveddate, #grn_status, #ggrossamt, #gdiscountamount, #gtotalnetamount)"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.Parameters.AddWithValue("#glocation", glocation)
sqlcmd.Parameters.AddWithValue("#gsupplier", gsupplier) //and so on
For Each X In datagridItems.Rows
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) _
VALUES(#grnno, #item_code, #description, ...)"
sqlcmd = New SqlClient.SqlCommand(sqlstr, AppsCon)
sqlcmd.Parameters.AddWithValue("#grnno", grnno)
sqlcmd.Parameters.AddWithValue("#item_code", CType(X.Cells(0).Value, Integer)) //cast to proper type
sqlcmd.ExecuteNonQuery()
Next
Remove the single quote marks ''
For example (and referring only to x.cell(6) as per your post) use " & X.Cells(6).Value & "
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) VALUES('" & grnno & "','" & X.Cells(0).Value & "','" & X.Cells(1).Value & "','" & X.Cells(2).Value & "','" & X.Cells(3).Value & "','" & X.Cells(4).Value & "','" & X.Cells(5).Value & "', " & X.Cells(6).Value & ",'" & X.Cells(7).Value & "' ,'" & X.Cells(8).Value & "','" & X.Cells(9).Value & "','" & X.Cells(10).Value & "')"
You may also need to cast it (assuming it's always going to have a numeric value)
" & CInt(X.Cells(6).Value) &"
I will assume you know of SQL injection and this method of updating a database is generally 'outdated' and 'bad practice' now and you should use parameters instead...
Updated
Since there is a possibility of a null (and you want it to be a 0 where this is the case), you could use something like (not tested as I'm not a VB person)
dim cellSix as integer
if IsNothing(X.Cells(6).Value then
cellSix = 0
else
cellSix = CInt(X.Cells(6).Value)
end if
sqlstr = "INSERT INTO POS_GRN_DTL(GRN_KEY,ITEM_CODE,DESCRIPTION,TYPE,UOM,BATCH_NO,EXPIRY_DATE,RECEIVED_QTY,UNIT_PRICE,AMOUNT,DISCOUNT,NET_AMOUNT) VALUES('" & grnno & "','" & X.Cells(0).Value & "','" & X.Cells(1).Value & "','" & X.Cells(2).Value & "','" & X.Cells(3).Value & "','" & X.Cells(4).Value & "','" & X.Cells(5).Value & "', " & cellSix & ",'" & X.Cells(7).Value & "' ,'" & X.Cells(8).Value & "','" & X.Cells(9).Value & "','" & X.Cells(10).Value & "')"
Or, to keep the code shorter you could use the IIF
cellSix = IIf(isnothing(CInt(X.Cells(6).Value)), 0, CInt(X.Cells(6).Value))
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.