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

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!

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)

Inserting byte() along side strings to SQL database

So here is the predefined SQL statement that is stored in the DAO file. The values are coming from a class. The picture value is an image converted to a byte(). This class is written in VB.net. I'm in a new job and in my previous i used angular and the entity framework so writing SQL statements is new to me. I'm trying to follow existing examples from co workers but they have never inserted images into the database before so i'm kinda on my own. Yes i know i could just store the files in the server and save the paths to them in the database but for whatever reason my network team wants it stored in the database as blobs. So, here is the SQL statement.
"INSERT INTO AuthAccessID" &
"(" &
"FName," &
"MName," &
"LName," &
"Suffix," &
"Address," &
"AddressExt," &
"City," &
"State," &
"Zip," &
"LawFirm," &
"Picture," &
"AddedDate," &
"AddedBy," &
")" &
"VALUES(" &
"" & ReplaceApostrophes(pp.FName) & ", " &
"'" & ReplaceApostrophes(pp.MName) & "', " &
"'" & ReplaceApostrophes(pp.LName) & "', " &
"'" & ReplaceApostrophes(pp.Suffix) & "', " &
"'" & ReplaceApostrophes(pp.Address) & "', " &
"'" & ReplaceApostrophes(pp.AddressExt) & "', " &
"'" & ReplaceApostrophes(pp.City) & "', " &
"'" & ReplaceApostrophes(pp.State) & "', " &
"'" & ReplaceApostrophes(pp.Zip) & "', " &
"'" & ReplaceApostrophes(pp.LawFirm) & "', " &
"'" & pp.Picture & "', " &
"'" & pp.AddedDate & "', " &
"'" & ReplaceApostrophes(pp.AddedBy) & "')
the pp.Picture is the Byte(). The error i'm getting is:
Operator '&' is not defined for types 'String' and 'Byte()'
i have googled around but cannot find anything. Does anyone have any idea how to correct this? or is there a better way to write the SQL statement? If i can't get this to work the network team said i can use the server file method but they are really pushing the blob in SQL storage instead. Thanks in advance.
Always use Parameters to avoid sql injection, make you sql statement easier to write and read, and make sure you are sending the correct datatypes. Parameters will also allow apostrophes. Use the .Add method. See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
Here is another
https://andrevdm.blogspot.com/2010/12/parameterised-queriesdont-use.html
In the code below, I had to guess at the SqlDbType and Size. Check your database for the correct information.
Connections and commands are using unmanaged resources. They release these resources in their .Dispose method so this method must be called. Using...End Using blocks take care of closing and disposing objects even if there is an error.
I assumed pp was an instance of a class. I gave the class the name Person. Correct this to the real class name.
Private ConStr As String = "Your connection string"
Private Sub InsertAuthAccessID(pp As Person)
Dim sql = "INSERT INTO AuthAccessID (
FName,
MName,
LName,
Suffix,
Address,
AddressExt,
City,
State,
Zip,
LawFirm,
Picture,
AddedDate,
AddedBy)
VALUES (
#FName,
#MName,
#LName,
#Suffix,
#Address,
#AddressExt,
#City,
#State,
#Zip,
#LawFirm,
#Picture,
#AddedDate,
#AddedBy)"
Using cn As New SqlConnection(ConStr),
cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("#FName", SqlDbType.VarChar, 50).Value = pp.FName
cmd.Parameters.Add("#MName", SqlDbType.VarChar, 50).Value = pp.MName
cmd.Parameters.Add("#LName", SqlDbType.VarChar, 100).Value = pp.LName
cmd.Parameters.Add("#Suffix", SqlDbType.VarChar, 20).Value = pp.Suffix
cmd.Parameters.Add("#Address", SqlDbType.VarChar, 200).Value = pp.Address
cmd.Parameters.Add("#AddressExt", SqlDbType.VarChar, 50).Value = pp.AddressExt
cmd.Parameters.Add("#City", SqlDbType.VarChar, 100).Value = pp.City
cmd.Parameters.Add("#State", SqlDbType.VarChar, 50).Value = pp.State
cmd.Parameters.Add("#Zip", SqlDbType.VarChar, 20).Value = pp.Zip
cmd.Parameters.Add("#LawFirm", SqlDbType.VarChar, 200).Value = pp.LawFirm
cmd.Parameters.Add("#Picture", SqlDbType.VarBinary).Value = pp.Picture
cmd.Parameters.Add("#AddedDate", SqlDbType.Date).Value = pp.AddedDate
cmd.Parameters.Add("#AddedBy", SqlDbType.VarChar, 50).Value = pp.AddedBy
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
EDIT:
In older versions of VB that did not support multiline String literals, you can use an XML literal instead:
Dim sql = <sql>
INSERT INTO AuthAccessID (
FName,
MName,
LName,
Suffix,
Address,
AddressExt,
City,
State,
Zip,
LawFirm,
Picture,
AddedDate,
AddedBy)
VALUES (
#FName,
#MName,
#LName,
#Suffix,
#Address,
#AddressExt,
#City,
#State,
#Zip,
#LawFirm,
#Picture,
#AddedDate,
#AddedBy)
</sql>
Using cn As New SqlConnection(ConStr),
cmd As New SqlCommand(sql.Value, cn)
Too long and involved for a comment. You have the following snippet in your code:
")" &
"VALUES(" &
"" & ReplaceApostrophes(pp.FName) & ", " &
"'" & ReplaceApostrophes(pp.MName) & "', " &
That is an error. FName is a string and must be treated in exactly the same manner as you do with MName. It is missing the single quote delimiters.
More generally, this approach relies on converting all your "fields" into literals to embed them as strings within your tsql statement. So the question now becomes how do you "write" a binary literal in tsql. You would do that by generating a string like this: 0x69048AEFDD010E. Documentation for tsql constants is here. Knowing that, the next issue is how to do that in your dev language - which is not something I can answer. This look promising.
But before you go down this path, use parameterization and you NEVER have to deal with this ever again.
I come from a MSAccess background, so I code quite much the same way I did in VBA or now with VB.net
Here the code I would use:
Dim sFields() As String
sFields = Split("FName,MName,LName,Suffix,Address,AddressExt,City,State,Zip,LawFirm,AddedDate,AddedBy", ",")
Dim rst As DataTable
Dim da As SqlDataAdapter
rst = MyrstEdit("select * from AuthAccessID where id = 0", da, strcon)
With rst.Rows.Add
For Each s In sFields
.Item(s) = GetValue(pp, s)
Next
End With
da.Update(rst)
And I have two helper routines. The first one gets any class property by a "string" value.
Since by luck, you have field names and the class members are the same!
Public Function GetValue(ByRef parent As Object, ByVal fieldName As String) As Object
Dim field As FieldInfo = parent.[GetType]().GetField(fieldName, BindingFlags.[Public] Or BindingFlags.Instance)
Return field.GetValue(parent)
End Function
And then I have a datable routine - that gets me the data table, and is this:
Public Function MyrstEdit(strSQL As String, ByRef oReader As SqlDataAdapter) As DataTable
Dim mycon As New SqlConnection(strCon)
oReader = New SqlDataAdapter(strSQL, mycon)
Dim rstData As New DataTable
Dim cmdBuilder = New SqlCommandBuilder(oReader)
Try
oReader.Fill(rstData)
oReader.AcceptChangesDuringUpdate = True
Catch
End Try
Return rstData
End Function
So, to get all the data types and structure? I pass a dummy sql that returns no rows. (no rows are returned, but we DO GET the valuable table data types when we do this dummy table pull!). In most cases, if the PK is a autonumber, then I use id = 0.
that same MyRstEdit() code bit has tons of uses! You can now deal with a table in a nice structure, loop it, shove it into a combo box, or datagrid. And as it shows, also allows editing of the data - all with type checking.
The REAL trick and tip I am sharing here? Break out your common data routines to about 2-3 routines like MyRstEdit().
That way, you really don't have to deal with messy in-line sql, or every time you need to work on a table, you don't wire truckloads of code. And the real beauty here is that data typing is done for you - you don't have line after line of parameters, nor line after line of data typing for each column.
So, I hope this post gives you some ideas. But it also nice since I get to code much like I did in MSAccess, and that includes writing VERY little code for updates such as this.
The ideas here are just that - a different approach. The other approaches here are also just fine. (but are quite a bit more code then I perfer).
There are times when using a data table is a rather nice - and I think this is such an example.
And while I am oh so often used to referencing columns as a table collection? The cool trick here is I am also referencing each member of the class with a string too!

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 :)

Im trying to INSERT data on a database with VB

I'm trying to Insert data on a access DataBase using Visual Basic with OleDbCommand, but it keeps returning me this error:
Here's my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
myconnection.ConnectionString = connString
Dim sql As String
myconnection.Open()
sql = "INSERT INTO Atletas ( Nome, Contacto, Email, dataNascimento, Morada, idEscalao ) VALUES( " & Text_Nome.Text & "','" & Text_Contacto.Text & "','" & Text_Email.Text & "','" & Data_Picker.Text & "','" & Text_Morada.Text & "','" & Combo_Escalao.Tag & ")"
Dim cmd As OleDbCommand = New OleDbCommand(sql, myconnection)
cmd.ExecuteNonQuery()
myconnection.Close()
End Sub
Firstly, I suggest you take a serious look at using parameters. As you can see, had you been using parameters you would not have had the syntax error. It will also eliminate problems with names such as O'Hara or O'Kelly as Steve pointed out.
Secondly It also protects you from SQL injection attacks - see Bobby Tables.
Finally, implementing a using block is good practice when it comes to using database connections, just in case you forget to close a connection, it will be disposed of at the end of the using block.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using con As New OleDb.OleDbConnection
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0;" & _
"Data Source = database path here"
con.Open()
Dim sql As String = "INSERT INTO Atletas (Nome, Contacto, Email, dataNascimento, Morada, idEscalao) VALUES (#nome, #contacto, #email, #datanascimento, #morada, #idescalao);"
Dim sql_insert As New OleDbCommand
With sql_insert
.Parameters.AddWithValue("#nome", Text_Nome.Text)
.Parameters.AddWithValue("#contacto", Text_Contacto.Text)
.Parameters.AddWithValue("#email", Text_Email.Text)
.Parameters.AddWithValue("#datanascimento", Data_Picker.Value.ToString("yyyy/MM/dd")) '''Assuming the value needed is a date only
.Parameters.AddWithValue("#morada", Text_Morada.Text)
.Parameters.AddWithValue("#idescalao", Cstr(Combo_Escalao.Tag))
.CommandText = sql
.Connection = con
.ExecuteNonQuery()
End With
con.close()
End Using
End Sub
You are missing two apostrophes, one at the beginning and another at the end. It's also good practice to end it with a semicolon. Try this:
sql = "INSERT INTO Atletas ( Nome, Contacto, Email, dataNascimento, Morada, idEscalao ) VALUES( '" & Text_Nome.Text & "','" & Text_Contacto.Text & "','" & Text_Email.Text & "','" & Data_Picker.Text & "','" & Text_Morada.Text & "','" & Combo_Escalao.Tag & "');"
However, as Plutonix suggested in his comment: Do Not concat string to make SQL. Use SQL parameters.

Issues trying to add records to an access database through vb.net

I am trying to add a record to a table in a Microsoft Access database through Visual Basic.
This is the code I'm using at the moment: (Within a sub)
Dim OleDbConstring As String = My.Settings.CMDataBaseConnectionString & ";"
Dim Con As OleDbConnection = New OleDbConnection(OleDbConstring)
Dim Cmd As New OleDbCommand
MsgBox("Adding?")
Cmd.Connection = Con
Cmd.CommandText = "INSERT INTO Users (Username, [Password], IsAdmin, TeacherID) VALUES ('" &
NewUsername.Text & "', '" &
NewPassword.Text & "', " &
NewIsAdmin.Checked().ToString & ", " &
NewTeacher.SelectedValue & ")"
Con.Open()
Cmd.ExecuteNonQuery()
Con.Close()
There are no errors thrown and the program doesn't stop at all, I can see the message box so I know the code is being run. However there are no changes made to the database each time. I have checked the field data types and everything is as it should be.
The scenario is a user selects a user, a username (turned into TeacherID), a password, and ticks if they're an admin or not. When they click a button, that code is run.
Also; I am aware that I should be using parameters to avoid SQL string injection, I am only writing it like this to be sure incorrect parameter coding (etc.) isn't contributing to the problem