Exception Occur in VB.NET code - sql

I was doing VB.NET and use it to connect my SQL database.
Right now I want to insert the data into my database, yet after I finish my code it comes out this error:
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
What does it means and what do I do wrong in my code?
Here is my code:
Imports System.Data.SqlClient
Public Class AddNew
Public con As New SqlConnection("Data Source=localhost;Initial Catalog=Tuition_Information;Integrated Security=True")
Public cmd As New Data.SqlClient.SqlCommand
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
cmd.CommandType = System.Data.CommandType.Text
cmd.CommandText = "Insert Into Student_Info Value ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & ComboBox1.SelectedValue & "','" & ComboBox2.SelectedValue & "','" & TextBox7.Text & "','" & TextBox8.Text & "')"
cmd.Connection = con
con.Open()
cmd.ExecuteNonQuery()
MsgBox("New Student Added", MsgBoxStyle.Information, "add")
Catch ex As Exception
MessageBox.Show("Error occured, please try again.")
End Try
End Sub
My Form looks like this:
My Database looks like this:

You're going to blow things up if you go about it the way you've got listed. What you need to do is to parameterize the query in some fashion - easiest way would be to create a stored procedure with named parameters. I say this will blow up because you do not account for the case wherein someone's name contains an apostrophe (and you can't tell me you won't have an O'Shannon or something), nor do you account for when a student is already registered. Something about that student must make them unique - like, maybe, Social Security Number? Which I assume you'll have during registration?
At that point, you could do something like:
create procedure SaveStudent
#Student_Name nvarchar(128) ,
#Home_Address nvarchar(256) ,
#Contact_Number varchar(32) ,
#Social_Security_Number char(11)
...
as
set nocount on
set rowcount 0
if exists ( select * from dbo.Students where Social_Security_Number = #Social_Security_Number )
begin
raiserror('Student with SSN %s already exists.', 16, 1, #Social_Security_Number) with nowait
end
else
begin
insert into dbo.Students (
Student_Name ,
Home_Address ,
Contact_Number ,
Social_Security_Number ,
... )
select
#Student_Name ,
#Home_Address ,
#Contact_Number ,
#Social_Security_Number ,
...
end
go
grant execute on SaveStudent to WhateverApplicationUserYouAreUsing
With that stored procedure in place, you'd then be able to bind those parameters, and you wouldn't be vulnerable to someone maliciously entering data, nor would you fall over when you get the first name with an apostrophe in it.
Obviously, you'd have to then bind to the stored procedure, which would mean preparing parameters & setting their values. But you'd be in better shape, and not vulnerable to the Little Bobby Tables problem.

Related

System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'.' / cmd.ExecuteNonQuery()

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If NamaBukuBox.Text = " " Or PngrngBukuBox.Text = " " Or PnrbtBukuBox.Text = " " Or JmlhBukuBox.Text = " " Then
MsgBox("Isi Semua Kolom Informasi")
Else
Con.Open()
Dim query = "Insert into BukuTbl values('" & NamaBukuBox.Text & "','" & PngrngBukuBox.Text & "','" & PnrbtBukuBox.Text & "'," & JmlhBukuBox.Text & ")"
Dim cmd As SqlCommand
cmd = New SqlCommand(query, Con)
cmd.ExecuteNonQuery() '** this line is error
MsgBox("Buku Telah Ditambahkan")
Con.Close()
End If
End Sub
I don't know what to do
what makes the error and how to solve it?
This is a very risky way of writing code. User input would be inserted directly into SQL. If your user inputs any apostrophe, your SQL will fail.
For example, try entering Abc's into the NamaBukuBox text box. Check your resulting SQL. In the worst case scenario, a user could inject SQL and delete data and tables.
In your case, it is likely the input from the user that is causing the SQL to fail. Please use parameters to input user data into SQL. Do not concatenate user input direct in SQL. You SQL should look something like:
Insert into BukuTbl values(#NamaBukuBox,#PngrngBukuBox,#PnrbtBukuBox,#JmlhBukuBox)

vb.net how to display Selected data from postgresql?

why is it even though i declared correctly the database name and its table, the error always saying TracingApp_fmemployeesuppliersfeedbackquestions is not exists, I just want that if the firstname and lastname exist in the database the record of that i search will show in the DataGridView1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As New DataTable
Dim firstname = firstnametextbox.Text.Trim()
Dim lastname = lastnametextbox.Text.Trim()
Try
Using MyCon As New Odbc.OdbcConnection("Driver={PostgreSQL ANSI};database=contacttracing;server=localhost;port=5432;uid=*****;sslmode=disable;readonly=0;protocol=7.4;User ID=*****;password=*****;"),
cmd As New Odbc.OdbcCommand("SELECT firstname= '" & firstname & "', lastname= '" & lastname & "' FROM TracingApp_fmemployeesuppliersfeedbackquestions ", MyCon)
MyCon.Open()
dt.Load(cmd.ExecuteReader)
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
DataGridView1.DataSource = dt
End Sub
Here is my postgresql tree
this is the error i get
UPDATE
ive tried this also
Odbc.OdbcCommand("SELECT firstname= '" & firstname & "', lastname= '" & lastname & "' FROM public.TracingApp_fmemployeesuppliersfeedbackquestions ", MyCon)
it didnt work also...
I suggest to surround the table name in quotes:
"SELECT * FROM ""TracingApp_fmemployeesuppliersfeedbackquestions"" "
"" being what one uses to get a single " into a VB string
I suggest this because I'm aware that PG converts all non quoted table names to lowercase (as can be seen in your "relation does not exist" error message) but the query tool tree shows that some letters in the table names are upper case, so I suspect the table names were created as case sensitive, and TracingApp_fmemployeesuppliersfeedbackquestions is different to tracingapp_fmemployeesuppliersfeedbackquestions
It might be less annoying for you to change your table names, if no other app is using the database, so you don't have to fill your VB strings up with lots of ""

Er : Syntax error in INSERT INTO statement Visual Basic 2017 using MC Access 2016 , oleDb 4.0

I am trying to insert data in my access database but i am getting a Syntax error in INSERT statemnt exception.Can someone please help me troubleshoot this error...Maybe my inset statement is not correct ?
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Try
If cmbTo.Text = "" Or cmbfrom.Text = "" Or cmbDay.Text = "" Or cmbMonth.Text = "" Or cmbYear.Text = "" Or cmbListBus.Text = "" Then
MsgBox("Please Insert Your Destination")
Else
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Hacke\source\repos\Student\Database\studentdatabase.mdb")
Dim insert As String = "INSERT INTO [BUSTICKET] VALUE ('" & cmbfrom.Text & "','" & cmbTo.Text & "','" & cmbDay.Text & "','" & cmbMonth.Text & "','" & cmbYear.Text & "','" & cmbListBus.Text & "');"
Dim cmd As New OleDbCommand(insert, conn)
conn.Open()
cmd.ExecuteNonQuery()
MsgBox("Success")
conn.Close()
End If
Catch ex As Exception
MsgBox("Err : " & Err.Description)
End Try
End Sub
End Class
A few mistakes in your post has made it a bit difficult for us to understand.Anyway,i've submitted an edit of your post.
The problem i see so far is that you haven't defined which table you want to insert the data in.For example,if your table name is Students ,then a sample sql/OleDb statement might look like
"Seletct * from Students",ConnectionString
Note : In the following statement,i used (*) which means i am not selecting/targeting any particular column/cell but all the columns/cells.This statement is used for various purposes specially when retrieving data from the database.
However,your motive is to insert data in the database.
The INSERT statement for any database software(AFAIK) must include the Table name you are targeting,the Column/Cell headers/names.Let's assume your Table name is Students and you want to insert data in FirstName,LastNmae columns.Then a sample Insert statement may look like :
"Insert into Students(FirstName,LastName)values(#fname,#lname)", ConnectionString
Now,NOTE THAT i am not adding the values directly in the statement.you can do that if you want.However,in this sample insert statement,i am rather defining some parameter names like#Fname and #Lname.This will be used later on to finally insert data into the table's columns.
Now,if you go with my sample code,you must assign some values to these parameters from your application.We have 2 parameters now and they are #Fname and #Lname.We now need to add literal values to them.Let's assume the values are coming from TextBoxes.
MyOledbCommand.Add("#Fname",OledbDatatype.VarChar).Value = FNameTxtBox.Text
'Or you can use :
MyOledbCommand.AddWithValue("#Fname",FNameTxtBox.Text)
After you are done assigning the textboxes(or some string or whatever) as the values,it is time to execute the command so that the data inserts.For that,we generally call :
MyOleDbCommand.ExecuteNonQuery()
So,here's a full sample :
Dim con as New oleDbConnection = "ConnectionStringHere"
Con.open
Dim MyOleDbCommand as new OleDbCommand("Insert into Students(FirstName,LastName)values(#fname,#lname)", con)
MyOledbCommand.AddWithValue("#Fname",FNameTxtBox.Text)
MyOledbCommand.AddWithValue("#Lname",LNameTxtBox.Text)
MyOleDbCommand.ExecuteNonQuery
Con.Close
Hope this helps :)

How do I update a specific row in access using SQL update? In my current code I keep getting the error data type mismatch

In my current code, I keep getting the error data type mismatch most of it worked before I added the SQL where statement to select a specific id
Private Sub UpdateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpdateButton.Click
'tells your program the data source
provider = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" 'refrences to the provider
datafile = "C:\Users\Abdulaleem\Documents\Books.accdb" 'refers to the location of the file
connectstring = provider & datafile ' combines the 2 variables
myconnect.ConnectionString = connectstring ' this class allows you to connect to the database
myconnect.Open() ' opens the databse
Dim sqlupdate As String
sqlupdate = "Update BooksTbl set BookName='" & TitleTEXT.Text & "' , [BookAuthor]='" & AuthorTEXT.Text & "',[Genre] ='" & GenreTEXT.Text & "',[IsAvailable] = " & status & ",[DatePublished] = '" & DateTimeCHANGER.Text & "' , [PictureLocation] = '" & PiclocTEXT.Text & "' WHERE [ID] = '" & idshower.Text & "'"
Dim cmd As OleDbCommand = New OleDbCommand(sqlupdate, myconnect) 'creating new database object
Try
cmd.ExecuteNonQuery() ' executes our sql query
cmd.Dispose() 'deleting from ram to stop interferences
myconnect.Close() 'closes database and connection
TitleTEXT.Clear()
AuthorTEXT.Clear()
GenreTEXT.Clear()
Catch ex As Exception ' if the programs crashes then it will be caught here and put into the ex variable
MsgBox(ex.Message) ' shows what error occured
myconnect.Close()
End Try
myconnect.Close()
Assuming that your [ID] column is an integer, try changing it from:
...WHERE [ID] = '" & idshower.Text & "'"
to
...WHERE [ID] = " & idshower.Text
In access, attempting to compare a number with a string results in the message "Data type mismatch in criteria expression".
Note: Unless you are certain the idshower.text actually contains a number, it'd be good practice to check this before executing the query, or access will think you're trying to use a parameter.
Also: You might want to look into parameterised queries which, although they usually result in more lines of code, protect you against things like SQL injection attacks and can perform some basic type conversion for you.

ASP.NET(VB) How to insert textbox.text into SQL database?

I am designing a register form.
The following is my codes:
but after I do it, then the SQL table display is not the user's data....?
The database table display &username&, &password&
(username, password...are textboxes name)
Protected Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
Dim Conn As SqlConnection = New SqlConnection(".....")
Conn.Open()
Dim sqlstr As String = "Insert Into user_profile(username,password,nickname,realname,email) Values('" & username.Text & "','" & password.Text & "','" & nickname.Text & "','" & realname.Text & "','" & email.Text & "')"
Dim cmd As New SqlCommand(sqlstr, Conn)
cmd.ExecuteNonQuery()
cmd.Cancel()
Conn.Close()
Conn.Dispose()
End Sub
Ok, first, I'll take a stab at your question. Then, we NEED to talk about SQL Injections.
Try this:
Dim MyValues as String = String.Format("'{0}', '{1}', '{2}', '{3}', '{4}'", username.Text, password.Text, nickname.Text, realname.Text, email.Text )
Dim sqlstr As String = "Insert Into user_profile(username,password,nickname,realname,email) Values(MyValues)"
(I've not tested that code. Watch for syntax errors.)
Now, that having been said, it is VITAL that you understand the danger of the way you are trying to do this. The serious problem here is that you are wide open to a SQL Injection attack. Google it. But in short, using this approach, someone can put commands like 'drop table' into your textbox, and those commands will be executed in your database.
The proper way to do this would be to create a stored procedure that contains the INSERT statement, and then pass your values to it with parameters. The web is littered with tutorials on how to do this. You'll find one easy enough.
Good luck!