VB.NET Oracle SQL "INSERT INTO" with "RETURNING INTO" gives ORA-00933 Command Not Properly Ended - vb.net

I need to update some code and as part of this I need to insert a row into a table and obtain the id (primary key) of the row just entered.
Have researched this and I believe I should be using RETURNING INTO and Oracle Parameters. I have used parameters in the past successfully to Insert values.
I have an INSERT statement that runs perfectly from VB.NET, but as soon as I add the text "" RETURNING id INTO :myId" I get ORA-00933 Command Not Properly Ended.
Here is a version of the code.
sql = "INSERT ... RETURNING id INTO :myId"
Connect()
Dim intRecsAffected As Integer = 0
Dim comm As OracleCommand = New OracleCommand(sql, _conn)
Dim param As OracleParameter
param = New OracleParameter()
param.ParameterName = ":myId"
param.OracleDbType = OracleDbType.Int32
param.Direction = ParameterDirection.Output ' Tried ReturnValue
comm.Parameters.Add(param)
intRecsAffected = comm.ExecuteNonQuery()
id = comm.Parameters(":myId").Value
Disconnect()
Any ideas?

I believe that your syntax is incorrect:
sql = "INSERT ... RETURNING id INTO myId"
Example below:
https://oracle-base.com/articles/misc/dml-returning-into-clause

Actually, realised what was going on. I cut my full SQL as it's quite long and there's some sensitive stuff in there.
The INSERT was using a SELECT rather than VALUES to get the values for the fields. That won't work - I am guessing because an INSERT with SELECT can add multiple rows even though in this case it won't.
Have re-written the SQL to use VALUES and the VB.Net code works fine.
Thanks to all who replied.

Related

Retrieving the Query used for a OleDBCommand

I'm currently using the following VB code to make a query against an Access Database, I would like to know is it possible to obtain what the SELECT statement that is being run and send that output to the console.
Dim QuestionConnectionQuery = New OleDb.OleDbCommand("SELECT Questions.QuestionID FROM Questions WHERE Questions.QuestionDifficulty=[X] AND ( Questions.LastDateRevealed Is Null OR Questions.LastDateRevealed < DateAdd('d',-2,Date() ) AND Questions.LastUsedKey NOT LIKE ""[Y]"" );", QuestionConnection)
QuestionConnectionQuery.Parameters.AddWithValue("X", questionDifficulty.ToString)
QuestionConnectionQuery.Parameters.AddWithValue("Y", strDatabaseKey)
Right now when I try to use: Console.WriteLine("Query: " & QuestionConnectionQuery.ToString)
I only get this:
Loop Question #1
Query: System.Data.OleDb.OleDbCommand
The short version comes down to this:
QuestionConnectionQuery.ToString
The QuestionConnectionQuery object is much more than just the text of your command. It's also the parameters, execution type, a timeout, and a number of other things. If you want the command text, ask for it:
QuestionConnectionQuery.CommandText
But that's only the first issue here.
Right now, your parameters are not defined correctly, so this query will never succeed. OleDb uses ? as the parameter placeholder. Then the order in which you add the parameters to the collection has to match the order in which the placeholder shows in the query. The code in your question just has X and Y directly for parameter placeholders. You want to do this:
Dim QuestionConnectionQuery AS New OleDb.OleDbCommand("SELECT Questions.QuestionID FROM Questions WHERE Questions.QuestionDifficulty= ? AND ( Questions.LastDateRevealed Is Null OR Questions.LastDateRevealed < DateAdd('d',-2, Date() ) AND Questions.LastUsedKey NOT LIKE ? );", QuestionConnection)
QuestionConnectionQuery.Parameters.Add("?", OleDbType.Integer).Value = questionDifficulty
QuestionConnectionQuery.Parameters.Add("?", OleDbType.VarChar, 20).Value = strDatabaseKey
I had to guess at the type and lengths of your parameters. Adjust that to match the actual types and lengths of the columns in your database.
Once you have made these fixes, this next thing to understand is that the completed query never exists. The whole point of parameterized queries is parameter data is never substituted directly into the sql command text, not even by the database engine. This keeps user data separated from the command and prevents any possibility of sql injection attacks.
While I'm here, you may also want to examine the WHERE conditions in your query. The WHERE clause currently looks like this:
WHERE A AND ( B OR C AND D )
Whenever you see an AND next to an OR like that, within the same parenthetical section, I have to stop and ask if that's what is really intended, or whether you should instead close the parentheses before the final AND condition:
WHERE A AND (B OR C) AND D
This will fetch the command text and swap in the parameter values. It isnt necessarily valid SQL, the NET Provider objects haven't escaped things yet, but you can see what the values are and what the order is for debugging:
Function GetFullCommandSQL(cmd As Data.Common.DbCommand) As String
Dim sql = cmd.CommandText
For Each p As Data.Common.DbParameter In cmd.Parameters
If sql.Contains(p.ParameterName) AndAlso p.Value IsNot Nothing Then
If p.Value.GetType Is GetType(String) Then
sql = sql.Replace(p.ParameterName,
String.Format("'{0}'", p.Value.ToString))
Else
sql = sql.Replace(p.ParameterName, p.Value.ToString)
End If
End If
Next
Return sql
End Function
Given the following SQL:
Dim sql = "INSERT INTO Demo (`Name`, StartDate, HP, Active) VALUES (#name, #start, #hp, #act)"
After parameters are supplied, you can get back this:
INSERT INTO Demo (`Name`, StartDate, HP, Active) VALUES ('johnny', 2/11/2010 12:00:00 AM, 6, True)
It would need to be modified to work with OleDB '?' type parameter placeholders. But it will work if the DbCommand object was created by an OleDBCOmmandBuilder, since it uses "#pN" internally.
To get or set the text of the command that will be run, use the CommandText property.
To print the results, you need to actually execute the query. Call its ExecuteReader method to get an OleDbDataReader. You can use that to iterate over the rows.
Dim reader = QuestionConnectionQuery.ExecuteReader()
While reader.Read
Console.WriteLine(reader.GetValue(0))
End While
reader.Close()
If you know the data type of the column(s) ahead of time, you can use the type-specific methods like GetInt32. If you have multiple columns, change the 0 in this example to the zero-based index of the column you want.

String.Format vs Parameter Values SQL Query

I'm trying to figure out if there is a better way to do this
Dim cmd As New SqlCommand
Dim sel As String
Dim obj As New DataHandler
sel = String.Format("SELECT * FROM Customers WHERE Country LIKE '{0}%'", txt_Input.Text)
cmd.CommandText = sel
Me.dgv_Customers.DataSource = obj.SqlDataRetriever(cmd)
Basically what im trying to do is have a textbox that whenever I type a letter, the grid refreshes itself by sending a Query to my SQL server searching for whatever its in the textbox using the LIKE() from SQL. I've been reading about SQL injection and so far everyone suggests to use parameter values (#value) for user input, but if I try to replace the {0} with that it doesn't work. I just wanna make sure that this is a valid way of doing this.
Thanks
Instead just concatenate the string like below. You should consider using parameterized query to avoid SQL Injection.
sel = "SELECT * FROM Customers WHERE Country LIKE '" + txt_Input.Text + "%'";
Use a parameterized query rather. See This Post
Dim cmd as New SqlCommand("SELECT * FROM Customers WHERE Country LIKE #param")
cmd.Parameters.Add("#param", txt_Input.Text +"%")

Display full query in statement with parameters

I have some trouble to debugging my query in vb.net.
I just wanna get full query with value inside it. I use parameters to add value in my query.
This is my code:
'Select query
Dim stm As String = "SELECT *, FORMAT(NOW(),'DD-MM-YYYY HH:NN:SS') as waktu FROM [user] WHERE [username]=? AND [password]=? AND active=TRUE"
Dim cmd As OleDbCommand = New OleDbCommand(stm, db)
'Parameters
Using md5Hash As MD5 = MD5.Create()
Dim pwd As String = GetMd5Hash(md5Hash, Me.tx_password.Text)
cmd.Parameters.Add("p1", OleDbType.VarChar, 25).Value = Me.tx_username.Text
cmd.Parameters.Add("p2", OleDbType.VarChar, 32).Value = pwd
End Using
'Execute Query
MsgBox(stm)
Dim reader As OleDbDataReader = cmd.ExecuteReader(CommandBehavior.SingleRow)
With this code, I just get result like this:
SELECT *, FORMAT(NOW(),'DD-MM-YYYY HH:NN:SS') as waktu FROM [user]
WHERE [username]=? AND [password]=? AND active=TRUE
How to get result like this:
SELECT *, FORMAT(NOW(),'DD-MM-YYYY HH:NN:SS') as waktu FROM [user]
WHERE [username]='adminUser' AND [password]='adminPassword' AND active=TRUE
Parameters are not concatenated into the command, they are sent separately to the database. Otherwise there will be no difference between using a parameterized query and using a concatenated one. (see the answer to a similar question here.)
This means that in order to debug your queries you will have to work a little harder then if your sql was concatenated by the vb.net code.
If your database supports stored procedure I recommend you start using them instead of parameterized queries. You will probably gain performance, and it will be easier to debug.
If not, you can copy the query as is to the sql editor, and use one of the debugger options to get the values of the parameters and copy them one by one to the sql editor.
Place this code below you have added the parameters and you'll have in debugSQL the SQL statement which will be executed
Dim debugSQL As String = cmd.CommandText
For Each param As SqlParameter In cmd.Parameters
debugSQL = debugSQL.Replace(debugSQL.ParameterName, debugSQL.Value.ToString())
Next

How do I query SQL data then insert or update depending on the result

I am a beginner at this. But let me explain what I need to do and show you my code
I have a CSV file.
inside the CSV I have a projectnumber, city,state,country
I have a SQL table with the same column
I want to use vb.net to check if projectnumber exists in sql table
if exists then I want to run update statement.
if it does not exists then I want to run insert statement.
I have the program working . but I am just wondering if this would be the correct way or my code is some hack way of doing it.
LEGEND:
DTTable is data table with CSV inside
DT is data table with SQL result data
First I fill insert all lines in the CSV into a data table
Dim parser As New FileIO.TextFieldParser(sRemoteAccessFolder & "text.csv")
parser.Delimiters = New String() {","}
parser.ReadLine()
Do Until parser.EndOfData = True
DTTable.Rows.Add(parser.ReadFields())
Loop
parser.Close()
then I use oledbdataadapter to run the select query and fill another data table with the result of the select statement
SQLString = "select * from tblProjects where ProjectID='" & DTTable.Rows.Item(i).Item("ProjectNumber") & "'"
da = New OleDb.OleDbDataAdapter(SQLString, Conn)
da.Fill(dt)
then I run if statement
If dt.Rows.Count = 0 then
SQLString = "INSERT STATEMENT HERE"
oCmd = New OleDb.OleDbCommand(SQLString, Conn)
oCmd.ExecuteNonQuery()
Else
SQLString = "UPDATE STATEMENT HERE"
oCmd = New OleDb.OleDbCommand(SQLString, Conn)
oCmd.ExecuteNonQuery()
End if
ALL above code is run inside a for loop, to go through all the lines in the CSV
For i = 0 To DTTable.Rows.Count - 1
what do you think?
please advise
thank you
Personally, I wouldn't use .NET. I would import the table into a temp SQL Server table and then write my queries to insert/update data from the temp table to the regular table. This is certainly the way you want to go if the dataset is large.
If this is a process you need to repeat frequently, you could make an SSIS package.
I'd run the select query using datareader = command.ExecuteReader(). Then:
If datareader.Read() then
'Update query using datareader(0) as a where predicate goes here
ElseIf datareader(0) = Nothing then
'Insert query goes here
End If
I should say, I'm a relative novice too though, so maybe others can suggest a more elegant way of doing it.

sql error - missing a (;) at the end of sql statement

I'm trying to get this bit work but it keep saying that missing a (;) at the end of a SQL statement. Basically, this code will get filename of a picture and insert into photodatabase in fileName column, if the filename already exist then just update = 1.
INSERT INTO photoDB(fileNames)
VALUES('" + Path.GetFileName(fileName) + "')
ON DUPLICATE KEY UPDATE fileNames = 1
The error is message is quite clear. You need a semi-colon at the end of your SQL string (fileNames = 1;.
Here is an example that helps to protect against SQL injection and fixes your semi colon problem.
SqlConnection conn = new SqlConnection("ConnectionString");
SqlCommand command = new SqlCommand();
command.Connection = conn;
command.CommandText = "INSERT INTO photoDB (fileNames) VALUES(#fileName) ON DUPLICATE KEY UPDATE fileNames = 1;";
command.Parameters.Add(new SqlParameter("#filename", System.Data.SqlDbType.VarChar).Value = Path.GetFileName(fileName));
command.ExecuteNonQuery();
Second answer (now that the OP has fixed the semi-colon issue).
Is this MySQL? Other databases will not support that ON DUPLICATE KEY syntax.
Your ON DUPLICATE KEY clause sets a TEXT column (fileNames) to an INTEGER value (1). Try putting quotes around the integer value.