I am trying to save richtextbox content to Microsoft Access in a vb 2008.
I have uploaded a rtf file to richtextbox. Now richtextbox have tables, paragraphs.
I tried richtextbox1.rtf, but when i am saving i am getting error as
"Syntax error (missing operator) in query expression ''{\rtf1\fbidis\ansi\ansicpg1252\deff0\deflang1033\deflangfe1033{\fonttbl{\f0\fswiss\fprq2\fcharset0 Calibri;}{\f1\fnil\fcharset0 Calibri;}} \viewkind4\uc1\pard\ltrpar\sa200\sl276\slmult1\f0\fs22 Estonia\rquote s economic growth c'."
Any suggestions.
Here is my code
Dim cmd As New OleDbCommand
Dim sSQL As String = String.Empty
connection.Open()
cmd.Connection = connection
cmd.CommandType = CommandType.Text
sSQL = "INSERT INTO assessment (a)"
sSQL = sSQL & " values('" & t1.rtf & "')"
cmd.CommandText = sSQL
cmd.ExecuteNonQuery()
MsgBox("Data has been saved")
Your rtf information probably contains a single quote somewhere, which messes up your string and the database engine can't figure out what is the text anymore.
You need to use parameters:
sSQL = "INSERT INTO assessment (a) values (#a)"
cmd.Parameters.AddWithValue("#a", t1.rtf)
BTW, always use parameters to avoid SQL injection. Someone can write somethine like ';DROP TABLE assessment in your textbox, and guess what, your table would mysteriously disappear. Parameters would protect your from that.
Related
I have been trying to insert a text value to a field in my MS Access Database but it shows Syntax Error in INSERT INTO.
con.Open()
Dim test As String
test = cbHotCake.Text
Dim addBF1 As New OleDbCommand("INSERT INTO TemporaryHolder (Order) VALUES ('" & test & "')", con)
addBF1.ExecuteNonQuery()
con.Close()
Here's the error message it shows:
Syntax error in INSERT INTO statement.
Connections and commands need to be disposed. Using...End Using blocks will do this for you even if there is an error. This will also close the connection. Pass the connection string to the constructor of the connection. Pass the command text and the connection to the constructor of the command.
Always use parameters. I had to guess at the datatype and field size, so check the database and correct the code.
Private Sub OPCode()
Using con As New OleDbConnection("Your connection string"),
addBF1 As New OleDbCommand("INSERT INTO TemporaryHolder (Order) VALUES (#test);", con)
addBF1.Parameters.Add("#test", OleDbType.VarChar, 100).Value = cbHotCake.Text
con.Open()
addBF1.ExecuteNonQuery()
End Using
End Sub
Most likely, you need to bracket the reserved word Order:
"INSERT INTO TemporaryHolder ([Order]) VALUES ('" & test & "')"
I am writing code to insert a username and password into a database called Users.
When I try to run the code it says there is an error in the INSERT statement's syntax but I cannot for the life of me find it.
I am running the SQL statement using another function called RunSQL that I can submit if need be but its worked fine with every other SQL statement I have run with it.
The Users table has the following columns with their data type
User_ID - Auto Number (Primary Key)
Username - Short Text
Password - Short Text
I have tried adding ' ' around the values I am going to insert into the table as well as removing the & and making it one continuous string. I have tried adding / removing the ; but nothing has worked.
Dim sql As String = "INSERT INTO Users (Username, Password) " &
"VALUES (" & username_Textbox.Text & " , " & password_Textbox.Text & ");"
RunSQL(sql)
MessageBox.Show("User Added")
Private Sub RunSQL(ByVal sql As String)
Dim conn As OleDbConnection = New
OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Paper_Gen_Database.accdb;")
conn.Open()
Dim cmd As New OleDbCommand(sql, conn)
cmd.ExecuteNonQuery()
System.Threading.Thread.Sleep(500)
End Sub
The code should take the values from the username and password textboxes and insert them into the Users table but so far it has only thrown back an SQL error.
This is what the SQL statement looks when with "bh106" being the Username and "ZLTga" being the Password
This is one way to use parameters. It is very important to use parameters because otherwise you risk SQL injection which can ruin your database. It is actually much easier to write the SQL statement this way because you don't have to worry about if you have all your quotes in the string correctly.
The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error. This is important because it releases any unmanaged resources being used.
In a real application you would never save passwords as plain text but that is a subject for another day.
Private Sub InsertUser()
Dim sql As String = "INSERT INTO Users (Username, [Password]) VALUES (#username, #password);"
Using conn As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Paper_Gen_Database.accdb;")
Using cmd As New OleDbCommand(sql, conn)
cmd.Parameters.Add("#username", OleDbType.VarChar).Value = username_Textbox.Text
cmd.Parameters.Add("#password", OleDbType.VarChar).Value = password_Textbox.Text
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
MessageBox.Show("User Added")
End Sub
In Access the order that the parameters are added must match the order that they appear in the SQL statement.
Try this (its probably because of lack of quotes, and also because password is protected word):
Dim sql As String = "INSERT INTO Users (Username, [Password]) " &
"VALUES ('" & username_Textbox.Text & "' , '" & password_Textbox.Text & "');"
RunSQL(sql)
MessageBox.Show("User Added")
Also be aware of sql injection problem.
If a user will put a quote inside a textbox, insert will still fail.
You should try converting your code into parametrized query, example:
https://learn.microsoft.com/pl-pl/dotnet/api/system.data.oledb.oledbcommand.parameters?view=netframework-4.7.2
Can someone please look at my code and possibly point me to why it is not allowing me to insert data into my Postgres database? I'm creating a Comic Book database for my collection.
Everytime I click my submit button to submit the data entered, the debugger throws an exception:
'An unhandled exception of type 'Npgsql.PostgresException' occurred in Npgsql.dll'
Which happens on the execution of myCommand.ExecuteNonQuery() function.
I've spent my day trying to figure this out, I am a complete noob at this. Any guidance would be awesome!
Dim myConnection As NpgsqlConnection = New NpgsqlConnection()
Dim myCommand As NpgsqlCommand
Dim mySQLString As String
myConnection.ConnectionString = "Server=localhost;Port=5432;Database=ComicsDatabase;User Id=postgres;Password=xxxxxxxx;"
mySQLString = "INSERT INTO Comics (IssueName,IssueNumber,PublicationDate,Publisher,IsVariant) VALUES (" & comicName & "," & issueNumber & "," & publicationDate & "," & publisher & "," & isVariant & ");"
myCommand = New NpgsqlCommand(mySQLString, myConnection)
myConnection.Open()
myCommand.ExecuteNonQuery()
myConnection.Close()
When you concatenate strings as above to form your sql command it is very easy to fall in common errors. In your code, for example, a string value should be enclosed between single quotes.
So, supposing that IssueName is a string type field, you should express the value in this way
.... VALUES ('" & comicName & "'," & ....
But this is a remedy worse than the illness. First you will have another problem if your comicName variable contains a single quote, second the concatenation of strings is the main way that leads to Sql Injection (a very dangerous code vulnerability)
The only correct way to pass a value to a database engine (...any database engine of this world) is through a parameterized query
You write the query putting parameter placeholders instead of directly the values
(No string concatenation, no weird & and single quotes....)
mySQLString = "INSERT INTO Comics
(IssueName,IssueNumber,PublicationDate,Publisher,IsVariant)
VALUES (:comicName,:issueNumber,:publicationDate,:publisher,:isVariant);"
And then you pass the value using a parameter added to the command parameters collection
myCommand = New NpgsqlCommand(mySQLString, myConnection)
myCommand.Parameters.Add(":comicName", NpgsqlDbType.Varchar).Value = comicName
Of course you need to add all the other parameters required by the placeholders, the important thing to keep in mind is to use the correct NpgsqlDbType for the specific column that you are trying to update.
I'm new to VB. It's been few weeks since I started learning VB.My question is I'm having difficulty in adding Data in to the Database (I'm using MS Access) from VB. So far I got this code but it isn't running well:
Imports System.Data.OleDb
Public Class CraeteAccount
Dim connString As String
Dim myConnection As OleDbConnection = New OleDbConnection
Dim cmd As New OleDbCommand
Dim dr As OleDbDataReader
Public Sub btnCreate_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreate.Click
connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & IO.Path.Combine(My.Application.Info.DirectoryPath, "LogIn1.accdb")
Dim cmd As New OleDbCommand
Dim cnn As OleDbConnection = New OleDbConnection(connString)
Dim str As String
Dim UserName As String
Dim Password As String
If txtPassword.Text = txtRetype.Text Then
cnn.Open()
Try
UserName = txtUserName.Text
Password = txtPassword.Text
str = "UPDATE Users SET UserName= '" & UserName & "', Password= '" & Password
cmd = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("#UserName", UserName)
cmd.Parameters.AddWithValue("#Password", Password)
cmd.ExecuteNonQuery()
MsgBox("New User has been Created!")
cnn.Close()
Me.Hide()
Catch ex As Exception
MsgBox("Error Occured!")
cnn.Close()
End Try
Me.Close()
Else
MsgBox("Check your Password!")
cnn.Close()
txtPassword.Focus()
End If
End Sub
When the code runs It donot add data and quickly goes to catch to show the Message Box which reads "Error Occured". So Can anyone Please Help me?
At a quick glance, the SQL query is broken in several ways:
str = "UPDATE Users SET UserName= '" & UserName & "', Password= '" & Password
The first thing to notice is that you're not closing the quotes after the password. However, even that isn't what you really want to do. What you want to do is this:
str = "UPDATE Users SET UserName=#UserName, Password=#Password"
This creates query parameters, which your next two lines are looking to populate with values:
cmd.Parameters.AddWithValue("#UserName", UserName)
cmd.Parameters.AddWithValue("#Password", Password)
Putting user values directly into the query is called a SQL injection vulnerability. It allows users to execute arbitrary code on your database, which is clearly a bad thing. So you're definitely going to want to stick with using these parameters instead.
The second problem here is that this query is going to update every record int he table. So it's basically going to overwrite all Users records with multiple copies of this one record.
If this really should be an UPDATE statement when you're going to want to add a WHERE clause to it which would identify the specific record you want to update.
However, I suspect based on the context that this should instead be an INSERT statement, since it's creating a new record:
str = "INSERT INTO Users (UserName, Password) VALUES (#UserName, #Password)"
Additionally, and this is important, you are storing user passwords in plain text. This is grossly irresponsible to your users. You should be obscuring user passwords with a 1-way hash so that they can never be retrieved in their original form. Not even by you as the system administrator.
(The language and emphasis used here may be a bit harsh for a beginner. Especially if you're working on a purely academic project with no actual users. But it's seriously that important. And there's no time like the present to learn about it.)
Another issue here is that you're assuming success of the query:
cmd.ExecuteNonQuery()
MsgBox("New User has been Created!")
At the very least you should be checking the return value to make sure a record was actually affected:
Dim rowsAffected As Int32 = cmd.ExecuteNonQuery()
If rowsAffected > 0 Then
MsgBox("New User has been Created!")
Else
'no record was inserted, handle error condition
End If
Another issue that you're facing, which isn't directly related to your problem but is making it much more difficult for you to debug your problem, is that you're ignoring error information:
Catch ex As Exception
MsgBox("Error Occured!")
cnn.Close()
In this code block the ex variable contains all of the information that the .NET Framework can give you about the error that took place. What you're basically doing is replacing all of that diagnostic information (error message, stack trace, etc.) with a single custom error message that contains no information.
Best not to do that.
Note that, given these issues, there may very well be other problems with the code. But this should at least get you going for a bit.
You're simultaneously trying to concatenate an update statement with user input (bad) and using parameterized values (good). Try
str = "UPDATE Users SET UserName=#UserName, Password=#Password"
cmd = New OleDbCommand(str, myConnection)
cmd.Parameters.AddWithValue("#UserName", UserName)
cmd.Parameters.AddWithValue("#Password", Password)
But this still won't work because this update statement will update all the records in the database with these values. Are you trying to update an existing record or create a new one? If you're updating an existing one, you need a WHERE clause; if you're trying to create a new one, you need to use INSERT instead.
This is my code i'm trying to update table via VB forms , I don't know what the wrong with it please help me.
This is the table:
Dim con As New OleDbConnection("provider=microsoft.ace.oledb.12.0; data source = |datadirectory|\Studen.accdb;")
con.Open()
Dim sql As String = "Update tend set StudentName='" & TextBox9.Text & "', LessonDate='" & TextBox13.Text & "', LessonTime=" & TextBox10.Text & ", Payment=" & TextBox11.Text & ", Note='" & TextBox12.Text & "' where ID=" & TextBox8.Text
Dim cmd As New OleDbCommand(sql, con)
cmd.ExecuteNonQuery()
con.Close()
The first problem is the field named NOTE. This is a reserved keyword in MS-Access and, if you want to use it, you need to encapsulate the word with square brackets
Dim sql As String = "Update tend set StudentName=...., [Note]=..."
but this is not the only problem here. A much bigger one is the string concatenation used to build the sql command. This approach leads to possible sql injections and problems in propertly quoting the values used to prepare the statement. Strings need to be examined to duplicate single quotes, decimals need to be passed with the proper decimal point, dates need to be encapsulated in the # symbol and so on....
A better way is using a parameterized query
Dim sql As String = "Update tend set StudentName=?, LessonDate=?, LessonTime=?, " & _
"Payment=?, [Note]=? where ID=?"
Using con = New OleDbConnection(...........)
Using cmd = New OleDbCommand(sql, con)
con.Open()
cmd.Parameters.AddWithValue("#p1", TextBox9.Text)
cmd.Parameters.AddWithValue("#p2", Convert.ToDate(TextBox13.Text))
cmd.Parameters.AddWithValue("#p3", Convert.ToInt32(TextBox10.Text))
cmd.Parameters.AddWithValue("#p4", Convert.ToDecimal(TextBox11.Text))
cmd.Parameters.AddWithValue("#p5", TextBox12.Text)
cmd.Parameters.AddWithValue("#p6", Convert.ToInt32(TextBox8.Text))
cmd.ExecuteNonQuery()
End Using
End Using
In a parameterized query, like the one above, you put placeholders (?) in the query text and supply the values with the Parameters collection of the command. In this way, the work to properly quote every single value is passed to the framework and db engine. They know better than you and me how to properly quote the parameters.
Note how the AddWithValue method infers the correct datatype to use for the parameter looking at the datatype of value passed. If your LessonDate field is a field with DateTime type then you need to convert the textbox text (a string) to a date. This could cause an exception if you don't check before trying the conversion. (Here I assume that you have something in place to ensure valid inputs). The same reasoning should be applied to the other NON text fields. (ID, LessonTime, Payment)