SQL Insert into statement - sql

strSQL = "INSERT INTO Accounts UserName, Password VALUES ('" & txtUsername.Text & "', '" & txtEncryptedPassword & "');"
When the code is executed and error is thrown, but there is no visible problem that i can see. Help!

The word PASSWORD is reserved in MS-Access.
You need to use square brackets around that name (Or change it to something different)
strSQL = "INSERT INTO Accounts (UserName, [Password]) VALUES (......
Said that, please use a parameterized query to build sql commands.
A string concatenation like yours is easily attacked by hackers using SQL Injection
Also, if the username or password contains a single quote, the resulting sql text built using string concatenation will be invalid.
strSQL = "INSERT INTO Accounts (UserName, [Password]) VALUES (?, ?)"
OleDbCommand cmd = new OleDbCommand(strSQL, connection);
cmd.Parameters.AddWithValue("#p1",txtUsername.Text);
cmd.Parameters.AddWithValue("#p2",txtEncryptedPassword);
cmd.ExecuteNonQuery();

You forgot parentheses:
strSQL = "INSERT INTO Accounts (UserName, Password) VALUES ('" & txtUsername.Text & "', '" & txtEncryptedPassword & "');"

try this code:
Dim strSQL As String = "INSERT INTO tblDetail VALUES('" & strPersonCode _
& "','" & strForename & "','" & strSurname & "','" & strDateOfBirth & "'," & strCurrentlyWith & ",'" & strConditions & "')"
Do it like that but change to your names.
Declare the values of text boxes as strings and just use those.

your doing () this mistake and you should must add:
your code:
strSQL = "INSERT INTO Accounts UserName, Password VALUES ('" & txtUsername.Text & "', '" & txtEncryptedPassword & "');"
you should must change code following as:
strSQL = "INSERT INTO Accounts (UserName, Password) VALUES ('" & txtUsername.Text & "', '" & txtEncryptedPassword & "');"
update1:
"INSERT INTO `test`.`users` ( `username`, `password`) " & _
"VALUES ('" & txtUsername.Text & "', '" & txtPassword.Text & "');"
update2:
"INSERT INTO users ( `username`,`password`)VALUES(#txtUsername.Text,#txtPassword.Text);"
"INSERT INTO users (Username,Password)VALUES(?,?);"
note:test means database name you should change your databasename.

Related

Syntax error when copying data from Excel userform to Access table

When trying to copy data from an Excel userform in to an Access table via SQL I am encountering an error on a field that is a Yes/No type in the database. How can I format the info correctly so that it updates the database?
I have looked at some other examples of copying data into the Yes/No fields in Access, as well as trying my code in a number of different formats, with double quotations, single quotations & as it appears below
Dim oConn As ADODB.Connection
Dim oCm As ADODB.Command
Dim iRecAffected As Integer
If Me.TBField.Visible = False Then
'Update office users
Init1 = Left(Me.TxtName1, 1) & Mid$(Me.TxtName1, InStr(Me.TxtName1, " ") + 1, 1)
Select Case Me.LblFraOffice.Caption
Case Is = "Add User"
Set oConn = New ADODB.Connection
oConn.Open sConn
Set oCm = New ADODB.Command
oCm.ActiveConnection = oConn
If RbUser.Value = True Then
oCm.CommandText = "INSERT Into Users (Name, Username, Initials, Process, FLM, FLM_ID, User, JobRole) " & _
"VALUES ('" & TxtName1.Value & "','" & TxtUname1.Value & "','" & Init1 & "','" & TxtProcess1.Value & "','" & TxtFLM.Value & "','" & TxtFLMID.Value & "', True ,'" & TxtPosition1.Value & "')"
ElseIf RbAdmin.Value = True Then
oCm.CommandText = "INSERT Into Users (Name, Username, Initials, Process, FLM, FLM_ID, JobRole, User) " & _
"VALUES ('" & TxtName1.Value & "','" & TxtUname1.Value & "','" & Init1 & "','" & TxtProcess1.Value & "','" & TxtFLM.Value & "','" & TxtFLMID.Value & "', True ,'" & TxtPosition1.Value & "')"
ElseIf RbManager.Value = True Then
oCm.CommandText = "INSERT Into Users (Name, Username, Initials, Process, FLM, FLM_ID, JobRole, User) " & _
"VALUES ('" & TxtName1.Value & "','" & TxtUname1.Value & "','" & Init1 & "','" & TxtProcess1.Value & "','" & TxtFLM.Value & "','" & TxtFLMID.Value & "', True ,'" & TxtPosition1.Value & "')"
End If
'MsgBox oCm.CommandText
oCm.Execute iRecAffected
oConn.Close
When pressing submit on the userform this should add a newly created user into the database table. If I remove the User field (and the associated true/false) it works. But my users can be users, admins or managers
At present I receive an error message
Run-time error '-2147217900 (80040e14)': Syntax error in INSERT INTO statement
Column name User is the reserved keyword. Can you add square brackets around the keyword to fix the issue:
INSERT Into Users (Name, Username, Initials, Process, FLM, FLM_ID, [User], JobRole)
or you can rename the column name to a non-reserved keyword to sovle this error.

VB.NET 2010 Inserting data to table in access

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

Insert SQL from combobox/textbox selections

I'm trying to add a row of data into the table using the selections from comboboxes and the textlabel. The error I'm receiving is in regard to the insert statement. Is this the correct way to reference the values in a combobox or textbox? I'm inserting into a table that has an autonumber primary key. Any help would be greatly appreciated.
Private Sub addResult_Click()
Dim strSQL As String
strSQL = "INSERT INTO Results (Student_ID, Class_ID, Test_Type, Student_Score, Total_Score, Level)
VALUES ('" & Me.cboStudents.Column(0) & "',
'" & Me.cboTeacher.Column(0) & "',
'" & Me.cboTestType.Column(1) & "',
'" & Me.txtTotalScore.Value & "',
'" & Me.txtStudentScore.Value & "',
'" & Me.cboTeacher.Column(2) & "')"
CurrentDb.Execute strSQL
End Sub

Insert into statement error

Try
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Jen\Documents\Jade\vb\database.accdb")
txtStatus.Text = "Active"
Dim account As String = ("Insert into Login(Username, Password, FirstName, LastName, AccountType, Status) VALUES ('" & txtUsername.Text & "' , '" & txtPass.Text & "', '" & txtFirst.Text & "', '" & txtLast.Text & "', '" & cmbType.Text & "', '" & txtStatus.Text & "')'")
conn.Open()
ole = New OleDbCommand(account, conn)
ole.ExecuteNonQuery()
MsgBox("Successfully Inserted!")
Dim strsql2 As New OleDbCommand("select * from Login", conn)
Dim sqlda = New OleDbDataAdapter(strsql2)
Dim sqldataset = New DataSet
sqlda.Fill(sqldataset)
Me.DataGridView1.DataSource = sqldataset.Tables(0)
conn.Close()
DataGridView1.Refresh()
an error shows that my insert into statement is incorrect. I already check my database many times and retype the code over but still get the same error.
I have Spotted an Extra (') qoute after closing bracket in query.Use this Query and Check
Dim account As String = ("Insert into Login(Username, Password, FirstName, LastName, AccountType, Status) VALUES ('" & txtUsername.Text & "' , '" & txtPass.Text & "', '" & txtFirst.Text & "', '" & txtLast.Text & "', '" & cmbType.Text & "', '" & txtStatus.Text & "')")
hope this helps.
Are AccountType and Status string type?
if not you should write this:
Dim account As String = ("Insert into Login(Username, Password, FirstName, LastName, AccountType, Status) VALUES ('" & txtUsername.Text & "' , '" & txtPass.Text & "', '" & txtFirst.Text & "', '" & txtLast.Text & "', " & cmbType.Text & ", " & txtStatus.Text & ")'")

VB 2012 error message

I get the following error: Operator '&' is not defined for types 'String' and 'System.Windows.Forms.TextBox'. :
in the following line of code:
cmd.CommandText = "INSERT INTO users(userid, passWord, firstName, lastName, jobTitle, SSN) VALUES (" & Me.adduseridtxtbox & ",'" & Me.addpasswordtxt & ",'" & Me.addfirstnametxt & ",'" & Me.addlastnametxt & ",'" & Me.jobcbox & ",'" & Me.addssntxt & "')"
here is the code :
Private Sub addbtn_Click(sender As Object, e As EventArgs) Handles addbtn.Click
Dim cmd As New OleDbCommand
If Not connection.State = ConnectionState.Open Then
connection.Open()
End If
cmd.Connection = connection
' add data to table
cmd.CommandText = "INSERT INTO users(userid, passWord, firstName, lastName, jobTitle, SSN) VALUES (" & Me.adduseridtxtbox & ",'" & Me.addpasswordtxt & ",'" & Me.addfirstnametxt & ",'" & Me.addlastnametxt & ",'" & Me.jobcbox & ",'" & Me.addssntxt & "')"
cmd.ExecuteNonQuery()
'refresh data in list
'close connection
connection.Close()
End Sub
You have to use Me.adduseridtxtbox.Text (which gets the value of the TextBox) rather than the TextBox directly.
Also, please, please, please read about OleDbParameter and how to use these parameters with OleDbCommand to prevent injection. Microsoft even provides examples.
Currently your code is extremely dangerous if you are letting users fill this form out themselves, as they have full control over your database. Regardless, using OleDbParameter is a good practice to get into. You appear to be handling social security numbers here -- your users deserve some form of security.
You should try to use/declare parameters in your query.
For example:
cmd.CommandText = ("INSERT INTO users(userid, passWord, firstName, lastName, jobTitle, SSN) " & _
"VALUES (#uid, #pw, #fn, #ln, #job, #ssn)")
With cmd.Parameters
.Clear()
.AddWithValue("uid", adduseridtxtbox.Text)
.AddWithValue("uid", adduseridtxtbox.Text)
.AddWithValue("pw", addpasswordtxt.Text
.AddWithValue("fn", addfirstnametxt.Text)
.AddWithValue("ln", addlastnametxt.Text)
.AddWithValue("job",jobcbox.SelectedValue)
.AddWithValue("ssn", addssntxt.Text)
End With
cmd.ExecuteNonQuery()
Your SQL Statement is not proper. How do you use an object as a string? It should be
cmd.CommandText = "INSERT INTO users(userid, passWord, firstName, lastName, jobTitle, SSN) VALUES ('" & Me.adduseridtxtbox.Text & ",'" & Me.addpasswordtxt.Text & ",'" & Me.addfirstnametxt.Text & ",'" & Me.addlastnametxt.Text & ",'" & Me.jobcbox.Text & ",'" & Me.addssntxt.Text & "')"
Use parametrised query to prevent SQL Injections and make safe your database system from malicious users.