sql = "INSERT INTO Machine_Master(Machine_Code,Machine_Name,Status)" _
& " VALUES ('" & textmachinecode.Text & "','" & textdescription.Text & "', '" & combostatus.Text & "')"
How to change text from combobox? When it's saved in database it will be integer. In this case, text combostatus.Text active will be 1 when saved and not active will be 0.
As Patrick said, you don't need case when since you can do that on the vb.net side, but you should use parameters to avoid problems:
Dim result As String = String.Empty
sql = "INSERT INTO Machine_Master (Machine_Code,Machine_Name,Status) " & _
" VALUES (#CODE, #DESC, #STATUS)"
Using cn As New SqlConnection("connectionString"), cmd As New SqlCommand(sql, cn)
Dim status As Integer = -1
Select Case combostatus.Text.ToLower()
Case "active" : status = 1
Case "not active" : status = 0
End Select
cmd.Parameters.AddWithValue("#CODE", textmachinecode.Text)
cmd.Parameters.AddWithValue("#DESC", textdescription.Text)
cmd.Parameters.AddWithValue("#STATUS", status)
result = cmd.ExecuteScalar().ToString()
End Using
You don't need a case when, you could simple solve this client side (mind that using parameters is better, as already suggested!)
Use this condition:
IIf(combostatus.Text = "active", 1, 0)
So, totally it becomes:
sql = "INSERT INTO Machine_Master(Machine_Code,Machine_Name,Status)" _
& " VALUES ('" & textmachinecode.Text & "','" & textdescription.Text & "', " _
& IIf(combostatus.Text = "active", 1, 0) & ")"
Related
I have the Database table where the Table needs to be updated using a form.
However all the fields in the Form need not be mandatory to be filled.
I am Writing the Below VB code for inserting However I get an error stating that there is a syntax error in the statement.As i understand it is because of the Null Values in the Variable. I understand that I need to use DBNull.Value for all the null Values.
Here the Thing is there are too many fields to check if the value is null or not.
any body suggest if there is a way to do a mass check on the values entered to be null?
VBCode:
Dim StrSQL As String
Dim StrSQL1 As String
Dim tktID As Variant
Dim Assi As Variant
Dim reopened As Variant
Dim valid As Variant
Dim Reopenreason As Variant
Dim ReassignmentAG As Variant
Dim RBSCollab As Variant
Dim SMEconf As Variant
Dim Cloabag As Variant
Dim smeName As Variant
Dim Updat As Variant
Dim Closed As Variant
Dim iss As Variant
Dim ana As Variant
Dim res As Variant
Dim rVariant As Variant
' Assigining values
tktID = Ticket_number.Value
reopened = Ticket_Reopened.Value
valid = Valid_Reopen.Value
Assi = Assiginee.Value
Reopenreason = Reopen_reason.Value
ReassignmentAG = Reassignment_AG.Value
RBSCollab = RBS_Collab.Value
SMEconf = CkBxSMEConfirmation.Value
Cloabag = Collabarated_AG.Value
smeName = SME_Name.Value
Updat = Update.Value
Closed = Issue_Closed.Value
iss = Issue.Value
ana = Analysis.Value
res = Resolution.Value
rdate = Resolve_date.Value
'Insert values into the tables
StrSQL = "INSERT INTO Updates (TicketID,Assiginee,ReassignmentAG,RBSCollab,CollabAG,SMEconfirmation,SMEName,Update,IssueClosed,Issue,Analysis,Resolution,ResolveDate,TicketReopened,ValidReopen,ReopenReason) VALUES ('" & tktID & "','" & Assi & "','" & ReassignmentAG & "','" & RBSCollab & "','" & Cloabag & "','" & SMEconf & "','" & smeName & "','" & Updat & "','" & Closed & "','" & iss & "','" & ana & "','" & res & "','" & rdate & "','" & reopened & "','" & valid & "','" & Reopenreason & "' ) "
DoCmd.RunSQL StrSQL
thanks in advance for your help
I, too, setup my first Access database using lots of unbound controls and SQL statements for moving data around. But this is not the way to use Access. You should be using bound forms where the controls automatically know what the constraints are based on the table/columns they are bound to.
This means much less code for you to write (and maintain), future developers can look at your Access app and know what's going on because it will be done in the Access paradigm, and if you place as much logic into your tables/relationships as possible then if someone comes along and links to your ACCDB or opens the backend they could enter data without entering bad data.
So ultimately this is an XY problem. Get rid of all this code (especially DoCmd.RunSQL) and create a bound form. Put your validation logic in foreign keys, validation rules, and/or data macros in the table.
A simple solution to this problem could be just check for element's value before using in the inset query and if element's value is undefined than set with null.
Pass this value to database in the query.
Do this for each field:
tktID = IIF(ISNULL(Ticket_number.Value),"Null","'" & Ticket_number.Value & "'")
Then instead of this:
VALUES ('" & tktID & "',...
Do this
VALUES (" & tktID & ",...
Or if you don't mind replacing nulls with empty strings:
tktID = Nz(Ticket_number.Value)
will do it.
Of course you should at least make sure no single quotes are in the stings, so even better:
tktID = IIF(ISNULL(Ticket_number.Value),"Null","'" & Replace(Ticket_number.Value,"'","''") & "'")
After building the string for INSERT statment
strSql = "INSERT INTO tblmovimentiServizi ( msid, " _
& " msData, msIdDestinazione, msOraInizioServizio, msOraFineServizio, msAndataRitorno, " _
& " msOraVincoloEntrata, msOraVincoloUscita, msidAnagraficaAutomezzi, msServizioEseguito, msNoteCommenti) " _
& " VALUES ('" & rst!newid & "', #" & rst!msData + Me.g1 & "#, '" _
& rst!msIdDestinazione & "', #" _
& rst!msOraInizioServizio & "#, #" _
& rst!msOraFineServizio & "#, '" _
& rst!msAndataRitorno & "', #" _
& rst!msOraVincoloEntrata & "#, #" _
& rst!msOraVincoloUscita & "#, '" _
& rst!msidAnagraficaAutomezzi & "', " _
& eseguito & ", '" _
& rst!msNoteCommenti & "'" _
& ");"
I added
strSql = Replace(strSql, "''", "null")
strSql = Replace(strSql, "##", "null")
and it works.
I made a SQL statement in the add/update button in the query wizard I changed it back to SQL view to see how the program made me the code and when I copy and paste the same error on the If statement of the btnAdd it throws me a syntax error, but how?
here is the entire code:
Private Sub cmdAdd_Click()
'In the button add we have two options
'1. Insert
'2. Update
If Me.txtID.Tag & "" = "" Then
CurrentDb.Execute "INSERT INTO tblClients ( ClientID, ClientName, Gender, " & _
"City, [Address (Fisical)], [Cellphone/Telephone] ) " & _
"SELECT " & Me.txtID & ",'" & Me.txtName & "','" & Me.cboGender & "', '" & Me.cboCity & "','" & Me.txtAddress & "','" & Me.txtCellphone & "'"
Else
'Otherwise the data will be updated
CurrentDb.Execute "UPDATE tblClients SET tblClients.ClientName = [me]. [txtName], tblClients.Gender = [me].[cboGender], tblClients.City = [me].[cboCity], tblClients.[Address (Fisical)] = [me].[txtAddress], tblClients.[Cellphone/Telephone] = [me].[txtCellphone] "
WHERE (([ClientID]=[Me].[txtID].[Tag]));
End If
cmdClear_Click
tblClients_subform.Form.Requery
End Sub
it highlights me this row in red:
WHERE (([ClientID]=[Me].[txtID].[Tag]));
It appears that the following code is not on the same line
CurrentDb.Execute "UPDATE tblClients SET tblClients.ClientName = [me]. [txtName], tblClients.Gender = [me].[cboGender], tblClients.City = [me].[cboCity], tblClients.[Address (Fisical)] = [me].[txtAddress], tblClients.[Cellphone/Telephone] = [me].[txtCellphone] "
WHERE (([ClientID]=[Me].[txtID].[Tag]))
So you may want to change it to
CurrentDb.Execute "UPDATE tblClients SET tblClients.ClientName = [me]. [txtName], tblClients.Gender = [me].[cboGender], tblClients.City = [me].[cboCity], tblClients.[Address (Fisical)] = [me].[txtAddress], tblClients.[Cellphone/Telephone] = [me].[txtCellphone] " & _
"WHERE (([ClientID]=[Me].[txtID].[Tag]))"
In addition to Cableload's correct answer where the WHERE statement that was on a new code line was not connected to the previous line by the use of an underscore at the end of the first one, there is still a referncing issue.
You are referencing values in a UserForm like that were columns in a table so it is not finding the value you are looking for. To get the value into the SQL statement you need to come out of the literal string, reference the value, and then continue writing the string (not forgetting to enclose the value with '): -
CurrentDb.Execute "UPDATE tblClients SET " & _
"[ClientName] = '" & Me.txtName & "', " & _
"[Gender] = '" & Me.cboGender & "', " & _
"[City] = '" & Me.cboCity & "', " & _
"[Address (Fisical)] = '" & Me.txtAddress & "', " & _
"[Cellphone/Telephone] = '" & Me.txtCellphone & "' " & _
"WHERE [ClientID]=" & Me.txtID.Tag
I have spread it across multiple lines for ease of reading but obviously you can adjust your actual code however needed.
I would also question [ClientID]=" & Me.txtID.Tag, is the ClientID in the in the txtID.value or the txtID.Tag, they are different places. The value property is the value in the text box, the Tag property is more like a area for metadata that you can populate if needed but is not automatically populated by default.
Finally I'd like to refer you back to an answer to a previous question you had, at the bottom of the answer there was a tip about placing the resultant query into a Access Query in SQL view to get better information on the error, that would have helped you here too. To give further assistance on the 'resultant query'.
In debug mode before the while the CurrentDb.Execute is highlighted but before it is run (using F8 to step through each line until you get there, or placing a breakpoint on that line
Open the the Immediate Window if it is not already open (either Ctrl+G to from the menu bar 'View' > 'Immediate Window')
Copy all related code from the line after the CurrentDb.Execute statement, in this case it would be UPDATE ... .Tag
In the immediate window type a question mark and then paste in the rleated code and press enter
The immediate window will return the resultant string for you to try in a Query in SQL view.
Change the SELECT keyword to VALUES in your INSERT statement.
CurrentDb.Execute "INSERT INTO tblClients ( ClientID, ClientName, Gender, " & _
"City, [Address (Fisical)], [Cellphone/Telephone] ) " & _
"VALUES (" & Me.txtID & ",'" & Me.txtName & "','" & Me.cboGender & "', '" & Me.cboCity & "','" & Me.txtAddress & "','" & Me.txtCellphone & "')"
And the UPDATE should be this. The issue here was that you were trying to use Form controls in the SQL, but you needed to evaluate the controls first then concatenate their values to your literal string.
I'm wondering if you really need Me.txtID instead of Me.txtID.Tag
So sway that out if it doesn't work.
CurrentDb.Execute "UPDATE tblClients SET tblClients.ClientName = '" & me.txtName & "', tblClients.Gender = '" & me.cboGender & "', tblClients.City = '" & me.cboCity & "', tblClients.[Address (Fisical)] = '" & me.txtAddress & "', tblClients.[Cellphone/Telephone] = '" & me.txtCellphone & "' WHERE (([ClientID]=" & Me.txtID.Tag & "));"
Wondering if someone can help me with this please. I'm getting the following error message when adding data to an access database.I know it's a time issue function but I don't know how to fix it so I can add data to the database in the required format. One or more values are prohibited by the validation rule 'Time()' set for 'tblmph'. Enter a value that the expression for this field can accept.
Public Sub Add_Data()
con.Open()
Dim rs As New OleDb.OleDbCommand("Insert into tblmph(ID,ThisDate,TimeStart,TimeFinish,Notes) " _
& "values ('" & TextBox1.Text & "' , '" & TextBox2.Text & "' , '" & TextBox3.Text & "' , '" _
& TextBox4.Text & "', '" & TextBox5.Text & "')", con)
rs.ExecuteNonQuery()
con.Close()
Display_Data()
End Sub
The columns are formatted as follows
ID = Auto Number-Long Integer
ThisDate = Short Date
TimeStart = Medium Time, Default Value = Time()
TimeFinish = Medium Time, Default Value = Time()
Notes = Memo
Do not insert the value of ID. If it is truly an auto-number, Access will automatically assign a value to the newly inserted row. Trying to insert a value into the field will cause an error and prevent the insert from working.
Change your Dim statement to:
Dim rs As New OleDb.OleDbCommand( "Insert into tblmph( ThisDate, TimeStart, TimeFinish, Notes ) values ( '" & TextBox2.Text & "' , '" & TextBox3.Text & "' , '" & TextBox4.Text & "', '" & TextBox5.Text & "' ) ", con)
I have a VB.Net form which allows the user to update the customer details such as name, contact no:, etc. So when the customer enters the new name for the customer name etc. the application should update the corresponding field in the existing entry that relates to the customer ID.
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim adapter As New SqlDataAdapter
Dim dt As New DataTable
cn.ConnectionString = ("Data Source=NIMO-HP\SQLEXPRESS;Initial Catalog=FYP_db;Integrated Security=True")
cmd.Connection = cn
cn.Open()
cmd.CommandText = " UPDATE TblCustomerDetails (compID, compName, compContact, compAddress, compFax, compEmail, compPayterm, compTaxscheme, compPaymode, compRemarks ) SET Values ('" & lblCID.Text & "', '" & txtCname.Text & "', '" & txtCpno.Text & "', '" & txtCaddrs.Text & "','" & txtCfax.Text & "', '" & txtCemail.Text & "', '" & cmbPterm.Text & "','" & cmbTaxschm.Text & "',' " & cmbPmode.Text & "', '" & txtRemarks.Text & "') WHERE compID = '" & lblCID.Text & "';"
cmd.ExecuteNonQuery()
MsgBox("Account updated!!", MsgBoxStyle.Information, "Updation complete")
Your using a INSERT syntax for your UPDATE statement. Your UPDATE statement should have the form:
UPDATE tableName
SET col1 = val1,
col2 = val2,
col3 = val3
WHERE someColumn = someValue
Additionally, you are wide open to SQL Injection attacks by using non-parameterized queries. Finally, I would use a Using blocks to ensure your connection and command are properly closed and disposed of.
Putting it all together it would look something like this:
Using Dim cn As SqlConnection = New SqlConnection("Data Source=NIMO-HP\SQLEXPRESS;Initial Catalog=FYP_db;Integrated Security=True")
cn.Open()
Dim sqlQuery As String = "UPDATE TblCustomerDetails " + _
"SET compName = #compName, " + _
"compContact = #compContact, " + _
"compAddress = #compAddress, " + _
"compFax = #compFax, " + _
"compEmail = #compEmail, " + _
"compPayterm = #compPayterm, " + _
"compTaxscheme = #compTaxscheme, " + _
"compPaymode = #compPaymode, " + _
"compRemarks = #compRemarks " + _
"WHERE compID = #compID"
Using Dim cmd As SqlCommand = New SqlCommand(sqlQuery, cn)
cmd.Parameters.AddWithValue("#compFax", txtCname.Text)
cmd.Parameters.AddWithValue("#compContact", txtCpno.Text)
cmd.Parameters.AddWithValue("#compAddress", txtCaddrs.Text)
cmd.Parameters.AddWithValue("#compFax", txtCfax.Text)
cmd.Parameters.AddWithValue("#compEmail", txtCemail.Text)
cmd.Parameters.AddWithValue("#compPayterm", cmbPTerm.Text)
cmd.Parameters.AddWithValue("#compTaxscheme", cmbTaxschm.Text)
cmd.Parameters.AddWithValue("#compPaymode", cmbPmode.Text)
cmd.Parameters.AddWithValue("#compRemarks", txtRemarks.Text)
cmd.Parameters.AddWithValue("#compID", lblCID.Text)
Dim result As Integer
result = cmd.ExecuteNonQuery()
If result = 1 Then
MsgBox("Account updated!!", MsgBoxStyle.Information, _
"Updation complete")
Else
MsgBox("Account not updated!!", MsgBoxStyle.Information, _
"Updation not complete")
End If
End Using
End Using
There are a few more things to note in the above code sample:
First, I removed compID from the list of values to update. You're using that in your WHERE query, so I think you would have interesting results in your query if you're trying to update the same column you are using as part of your WHERE clause. Additionally, the source for that value is a Label, which tells me it's not supposed to be changed.
Secondly, ExecuteNonQuery() returns an int with the number of rows affected. In this case, it should be 1 - if it's not 1, I have you show a different message box.
Thirdly, cmbPTerm, cmbTaxxshm and cmbPmode sound like ComboBox to me, and you're not going to get what I think you're expecting using their Text property. I think you'll want SelectedText - hard to say without knowning how your ComboBoxes are bound. I'll leave that as an exercise for you :)
Fourth, I broke the UPDATE query up across several lines simply for readability - you don't have to do it that way, as long as the query is correct.
Finally, I'd suggest using MessagBox.Show() vs MsgBox.
Dim cnn As New SqlConnection
Dim cmd As New SqlCommand
cnn.ConnectionString = ("Data Source=NIMO-HP\SQLEXPRESS;Initial Catalog=FYP_db;Integrated Security=True")
cmd.Connection = cnn
cnn.Open()
cmd.CommandText = "update TblCustomerDetails set compName='" & txtCname.Text & "' , compContact = '" & txtCpno.Text & "' , compAddress = '" & txtCaddrs.Text & "' , compFax = '" & txtCfax.Text & "' , compEmail = '" & txtCemail.Text & "' , compPayterm = '" & cmbPterm.Text & "' , compTaxscheme = '" & cmbTaxschm.Text & "' , compPaymode = '" & cmbPmode.Text & "' , compRemarks = '" & txtRemarks.Text & "' where compID = '" & lblCID.Text & "'"
cmd.ExecuteNonQuery()
cnn.Close()
MessageBox.Show("entry updated!!!")
i want to make condition to update my table if there's already same data (in the same column) inserted in the table.
im using
If String.ReferenceEquals(hotel, hotel) = False Then
insertDatabase()
Else
updateDatabase()
End If
this is the updateDatabase() code...
Dim sql2 As String = "update infoHotel set nameHotel = N" & FormatSqlParam(hotel) & _
", streetAddress = N" & FormatSqlParam(StreetAddress) & _
", locality = N" & FormatSqlParam(Locality) & _
", postalCode = N" & FormatSqlParam(PostalCode) & _
", country = N" & FormatSqlParam(Country) & _
", addressFull = N" & FormatSqlParam(address) & _
", tel = N" & FormatSqlParam(contact) & _
"where hotel = '" & hotel & "')"
this is the formatSqlParam() code:
Function FormatSqlParam(ByVal strParam As String) As String
Dim newParamFormat As String
If strParam = String.Empty Then
newParamFormat = "'" & "NA" & "'"
Else
newParamFormat = strParam.Trim()
newParamFormat = "'" & newParamFormat.Replace("'", "''") & "'"
End If
Return newParamFormat
End Function
the function manage to go into updateDatabase() but has some error saying
"Incorrect syntax near 'Oriental'."
Oriental is the data inserted in the table. is it suitable to use ReferenceEquals?
im using vb.net and sql database..tq
You should be using parameterized queries instead of concatenating strings like so:
Dim sql2 As String = "Update InfoHotel" _
& "Set nameHotel = #nameHotel" _
& ", knownAs1 = #knownAs1" _
& ", knownAs2 = #knownAs2" _
& ", knownAs3 = #knownAs3" _
& ", knownAs4 = #knownAs4" _
& " Where hotel = #hotel"
If you used parameterized queries, you wouldn't have to worry about trying do quote replacement and potentially introducing a SQL Injection vulnerability.
You have a single quote in your data, as in:
Oriental's
Show us the code for FormatSqlParam() -- the bug is probably in there.
Or else you left out the single quotes around the hotel name:
where hotel = '" & hotel & "')"
I hope that's not it, because it would mean you're using the name as a key, a very bad idea.