This is my Code I want to Enter First_Name,Middle_name and Last_Name in one Fieldname
Try
MysqlConn.Open()
Dim Query As String
Query = "INSERT INTO residentrecords.info (id,last_name,first_name,middle_name,age,address,contact_no,date_of_birth,religion,civil_status,education_attainment,occupation,fathers_name,mothers_name,mothers_occupation,fathers_occupation,gender,purok,blotter,docu,voter) values ('" & add.TextBox_ID.Text & "','" & add.TextBox_LN.Text & "','" & add.TextBox_FN.Text & "','" & add.TextBox_MN.Text & "','" & add.TextBox_Age.Text & "','" & add.TextBox_Address.Text & "','" & add.TextBox_Contact.Text & "','" & add.DateTimePicker1.Text & "','" & add.ComboBox_religion.Text & "','" & add.ComboBox_CS.Text & "','" & add.TextBox_Educ.Text & "','" & add.TextBox_Occu.Text & "','" & add.TextBox1_FathersName.Text & "','" & add.TextBox1_MothersName.Text & "','" & add.TextBox_mothersocc.Text & "','" & add.TextBox_fathersocc.Text & "','" & add.ComboBox_gender.Text & "','" & add.rpurok.Text & "','0','0','" & add.voter.Text & "')"
COMMAND = New MySqlCommand(Query, MysqlConn)
READER = COMMAND.ExecuteReader
MessageBox.Show("Successfully Registered!", "REGISTERED", MessageBoxButtons.OK, MessageBoxIcon.None)
If vbOK = MsgBoxResult.Ok Then
Me.Dispose()
add.Dispose()
add.Enabled = True
residents.Show()
End If
MysqlConn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
MysqlConn.Dispose()
End Try
End Sub
That's quite easy in .net. You need to split one string on it's whitespaces and insert the substrings seperately.
Use somethiing like this
Dim names as String()
Dim firstName as String
Dim middleName as String
Dim lastName as String
names = add.TextBox_Name.Text.Split(" ")
firstName = names(0)
middleName = names(1)
lastName = names(2)
You might check the array length by forehand to make sure the user really has a middle name. Or even more than one. I have two. Just check for names.length.
I hope i didn't misinterpreted your question. It was quite short explained.
Related
I'm using Microsoft Visual Studio 2010 Express and I'm trying to make a enrollment form using VB.NET. This is my code so far:
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim cardStr As String
Dim formStr As String
Dim birthStr As String
Dim goodmoralStr As String
If cbcard.Checked Then
cardStr = "OK"
Else
cardStr = ""
End If
If cbform.Checked Then
formStr = "OK"
Else
formStr = ""
End If
If cbbirth.Checked Then
birthStr = "OK"
Else
birthStr = ""
End If
If cbgoodmoral.Checked Then
goodmoralStr = "OK"
Else
goodmoralStr = ""
End If
Dim cmd As New OleDbCommand
Dim conn As New OleDbConnection(conStr)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
cmd.CommandText = "insert into tblEnroll(StudID,StudLevel,StudFName,StudMName,StudLName,StudGender,StudBirthday,StudNationality,StudContact,StudPOB,StudCitizenship,StudReligion,MomName,MomContact,MomOccupation,DadName,DadContact,DadOccupation,PrevSchool,Card,F137,BirthCertificate) values ('" & txtID.Text & "','" & lbGrade.Text & "','" & txtFName.Text & "','" & txtMName.Text & "','" & txtLName.Text & "','" & lbGender.Text & "','" & dtpBirthDate.Text & "','" & txtNationality.Text & "','" & txtStudContact.Text & "','" & txtPOB.Text & "','" & txtCitizen.Text & "','" & txtReligion.Text & "','" & txtMom.Text & "','" & txtMomContact.Text & "','" & txtMomOccupation.Text & "','" & txtDad.Text & "','" & txtDadContact.Text & "','" & txtDadOccupation.Text & "','" & txtPrevSchool.Text & "','" & cardStr & "','" & formStr & "','" & birthStr & "','" & goodmoralStr & "')"
cmd.ExecuteNonQuery()
conn.Close()
MessageBox.Show("Student Successfully Enrolled!")`
What could be the solution here?
You have one too many columns in your INSERT statement values. The value goodmoralStr does not have a corresponding column to insert into.
As a slight aside, you really should use parameterised SQL in your code to avoid issues with SQL injection.
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 don't know how to avoid SQL injection, could someone help me with my problem?
Here is my current code:
Private Function INSERT() As String
Dim SQLcon As New SqlConnection
Dim SQLdr As SqlDataReader
Try
SQLcon.ConnectionString = "Data Source=#####;Initial Catalog=OJT;Persist Security Info=True;User ID=####;Password=#####"
Dim SQLcmd As New SqlCommand("INSERT INTO dbo.Patients(pIDNo,pLName,pFName,pMI,pSex,pStatus,pTelNo,pDocID,pAddr,pStreet,pBarangay,pCity,pProvince,pLNameKIN,pFNameKIN,pMIKIN,pRelationKIN) VALUES('" & LabelPNumber.Text & "','" & txtLname.Text & "','" & txtFname.Text & "','" & txtMI.Text & "','" & txtPatientSex.Text & "','" & txtPatientSex.Text & "','" & txtPatientTelNo.Text & "','" & txtPatientDoctor.Text & "','" & txtStreetNumber.Text & "','" & txtStreetName.Text & "','" & txtBarangay.Text & "','" & txtCity.Text & "','" & txtProvince.Text & "','" & txtKinLname.Text & "','" & txtKinFname.Text & "','" & txtKinMI.Text & "','" & txtRelationToPatient.Text & "') ", SQLcon)
SQLcon.Open()
MsgBox("Patient Added!", MsgBoxStyle.Information)
SQLdr = SQLcmd.ExecuteReader()
Catch ex As Exception
MessageBox.Show("Error Occured, Can't Add Patient!" & ex.Message)
Finally
SQLcon.Close()
End Try
Return "done"
End Function
Basically anywhere you're concatenating strings together to create your SQL statement, especially that which comes from user input, is vulnerable.
Instead of doing this use SQL parameters, which can be added to the Parameters property of your SQL command (SQLcmd here).
I'll show you an example with one of your parameters - change your SQLCommand text to:
INSERT INTO dbo.Patients(pIDNo, ...)
VALUES(#pIDNo, ...)
Where #pIDNo is a "placeholder" in the string for the parameter value, which is sent separately from the command in the SQLParameters collection.
Then you can add a parameter with the same name as this "placeholder", and the value (it will derive the type from the value provided for you).
Here's the example from earlier:
SQLcmd.Parameters.AddWithValue("#pIDNo", LabelPNumber.Text)
this piece of code works fine....
Private Sub save()
Dim con As New SqlClient.SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Chuttu VB\Projects\LIC\LIC.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True")
Dim sql As New SqlClient.SqlCommand("INSERT INTO ProposerDetails " & _
"VALUES (" & Convert.ToInt32(PolicyNumberTextBox.Text) & ",'" & NameTextBox.Text & "','" & AgeTextBox.Text & "','" & PhoneTextBox.Text & "','" & AddressTextBox.Text & "','" _
& NomineeTextBox.Text & "','" & NomineeRelationTextBox.Text & "'," & PlanID() & ",'" & PolicyTermTextBox.Text & "','" & PremiumAmountTextBox.Text & "','" _
& PremiumTypeComboBox.Text & "','" & SumProposedTextBox.Text & "','Date' )", con)
MsgBox(sql.CommandText)
con.Open()
MsgBox(con.State.ToString)
Dim i As Integer = sql.ExecuteNonQuery
MsgBox(i.ToString)
con.Close()
sql.Dispose()
con.Dispose()
ToolStripStatusLabelMessage.Text = "Saved"
End Sub
as soon as i change the connection string to the connection string from app.config it stops working(adding data to DB)
Private Sub save()
Dim con As New SqlClient.SqlConnection(LIC.My.Settings.LICConnectionString)
Dim sql As New SqlClient.SqlCommand("INSERT INTO ProposerDetails " & _
"VALUES (" & Convert.ToInt32(PolicyNumberTextBox.Text) & ",'" & NameTextBox.Text & "','" & AgeTextBox.Text & "','" & PhoneTextBox.Text & "','" & AddressTextBox.Text & "','" _
& NomineeTextBox.Text & "','" & NomineeRelationTextBox.Text & "'," & PlanID() & ",'" & PolicyTermTextBox.Text & "','" & PremiumAmountTextBox.Text & "','" _
& PremiumTypeComboBox.Text & "','" & SumProposedTextBox.Text & "','Date' )", con)
MsgBox(sql.CommandText)
con.Open()
MsgBox(con.State.ToString)
Dim i As Integer = sql.ExecuteNonQuery
MsgBox(i.ToString)
con.Close()
sql.Dispose()
con.Dispose()
ToolStripStatusLabelMessage.Text = "Saved"
End Sub
NOTE: I get no errors.
Here is a short deal explanation.
This is how you use a connection string from the config file.
Dim sqlConn as SqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings("myConnectionString").ConnectionString)
Here is a link to how to do a parameterized queries
Try changing LIC.My.Settings.LICConnectionString
to ConfigurationManager.ConnectionStrings["LICConnectionString"].ConnectionString
I am using an Access database and vb.net 2010. I have created a table in the database with columns for title, datein, dateout and roomnymber. In vb.net 2010 I made a distinguished title = combobox, datein and dateout = DateTimePicker. When I click on F5, an error occurs: INSERT INTO Syntax Error in statement. Here's my code:
Dim sql As String
sql = "INSERT INTO tcekin(title,firstname,lastname,address,country,company,roomnumber,datein,dateout,rommtype,note)" & "VALUES('" & ComboBox1.Text & _
"','" & txtFirstName.Text & "','" & txtLastName.Text & "','" & txtAddress.Text & "','" & cboCountry.Text & "','" & txtCompany.Text & "','" & txtNumber.Text & _
"','" & dptDateIn.Text & "','" & dptDateOut.Text & "','" & cboRoom.Text & "','" & txtNotes.Text & "')"
cmmd = New OleDbCommand(sql, cnn)
The first problem here is never NEVER NEVER use string concatenation to build your queries like that. Do it like this instead:
Dim sql As String = _
"INSERT INTO tcekin " &_
"(title,firstname,lastname,address,country,company,roomnumber,datein,dateout,rommtype,note)" &_
"VALUES(?,?,?,?,?,?,?,?,?,?,?)"
cmmd = New OleDbCommand(sql, cnn)
cmmd.Parameters.AddWithValue("Title", Combobox1.Text)
cmmd.Parameters.AddWithValue("FirstName", txtFirstName.Text)
''# ...
''# ...
This will also make it easier to spot and avoid syntax errors like the one you're complaining about.