Cannot executing a SQL query through ODP.NET - invalid character error - oracle

I'm trying to execute a SQL query through ODP.NET to create a table, but I always get an ORA-00911 'invalid character' error. The Errors object in the exception always has the text "ORA-00911: invalid character\n", even if there are no linebreaks in the SQL query itself.
The code I'm executing the SQL is this:
using (OracleConnection conn = new OracleConnection(<connection string>) {
using (OracleCommand command = conn.CreateCommand()) {
conn.Open();
command.CommandText = queryString;
command.ExecuteNonQuery(); // exception always gets thrown here
}
queryString contains a single CREATE TABLE statement, which works fine when executed through SQL Developer
EDIT: the SQL I am executing is this:
CREATE TABLE "TESTSYNC"."NEWTABLE" (
"COL1" NUMBER(*,0) NULL,
"COL2" NUMBER(*,0) NULL
);
with linebreaks removed

Other people have come across this issue - ODP.NET does not support multiple SQL statements in a text command. The solution is to wrap it in a PL/SQL block with EXECUTE IMMEDIATE around each statement. This lack of support for ; seems incredibly boneheaded to me, and has not improved my opinion of the oracle development team.
Furthermore, this seems to be an issue with oracle itself, as I have the same problems with the MS and ODBC oracle clients.

I had this issue for some reason you have to have code on one line.
I had strSQL = "stuff" +
" more stuff"
I had to put it on one line.
strSQL = "stuff more stuff"
It some how reads the cr/lf.

Wrap your sql in a Begin block.
Dim sqlInsert As String = ""
For i = 1 To 10
sqlInsert += "INSERT INTO MY_TABLE (COUNT) VALUES (" & i & "); "
Next
Call ExecuteSql("BEGIN " & sqlInsert & " END;")

Your quotes are OK (it just forces Oracle to treat your object names as case sensitive i.e. upper case the way you've written it) but I'm not at all sure you're allowed to define NUMBER that way with a *.

I wonder if it is the "*" in the sql have you tried the call without an * in the create? I bet it is yet another "feature" of the ODP.Net driver

Related

Format dates using Windows form in Visual Studio

I am trying to update the database with the following query, but I am having difficulty formatting dates. What should I do?
string query = "update employee_info set FirstName ='txtfirstName.Text',LastName ='txtlastName.Text' ,Address1='txt_address', City = 'combo_city' ,Country='combo_Country',ReportsTo='txt_reportTo' WHERE Bday='dtp_birthDate.Value.ToShortDateString()' and HireDate='dtp_hireDate.Value.ToShortDateString()'";
You should use a parameterized query instead. This gets you around having to format the strings for the where clause correctly and also prevents you from being vulnerable to SQL injection attacks (https://en.wikipedia.org/wiki/SQL_injection)
Something like this (the below sample has a shortened version of your query and lacks setting up a db connection).
strQuery = "update employee_info set FirstName=#firstName, LastName=#lastName WHERE Bday=#birthDate and HireDate=#hireDate";
cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#firstName", txtfirstName.Text);
cmd.Parameters.AddWithValue("#CompanyName", txtLastName.Text);
cmd.Parameters.AddWithValue("#birthDate", dtp_birthDate.Value);
cmd.Parameters.AddWithValue("#hireDate", dtp_hireDate.Value);
cmd.ExecuteNonQuery();

Update Does Not Work in VS2010 Using IDB2

I have no problem when trying to execute and insert or a delete SQL Command. However, this update command does not seems to work well and I am having a hard time to figure it out. Kindly help me please.
I am using an i Series or AS/400 database.
Imports IBM.Data.DB2
Imports IBM.Data.DB2.iSeries
Public conn As New iDB2Connection
Public str As String = "Datasource=10.0.1.11;UserID=edith;password=edith;DefaultCollection=impexplib"
Dim cmdUpdate As New iDB2Command
Dim sqlUpdate As String
conn = New iDB2Connection(str)
conn.Open()
sqlUpdate = "UPDATE impexplib.expusers SET loginDate=#loginDate, loginTime=#loginTime WHERE username=#username"
cmdUpdate.Parameters.Add("username", iDB2DbType.iDB2VarChar)
cmdUpdate.Parameters.Add("loginDate", iDB2DbType.iDB2Date)
cmdUpdate.Parameters.Add("loginTime", iDB2DbType.iDB2Time)
cmdUpdate.Parameters("username").Value = txtUsername.Text
cmdUpdate.Parameters("loginDate").Value = Now.ToString("d")
cmdUpdate.Parameters("loginTime").Value = Now.ToString("T")
cmdUpdate.Connection = conn
cmdUpdate.CommandText = sqlUpdate
cmdUpdate.ExecuteNonQuery()
conn.Close()
Please help me what I am doing wrong? The update code does not really work. Even a simple update of password does not work to.
Thanks!
Assuming no error messages anywhere, if no update is occurring, then the WHERE clause is not being satisfied. Make sure that the user name in DB2 exactly matches the parameter used in the WHERE clause. Very often, DB2 columns are CHAR, not VARCHAR or the other way round. You may also have a situation where the DB2 column is all upper case and the parameter is mixed case. Imagine the DB2 column has "FRED BLOGGS " and your parameter has "Fred Bloggs". This won't satisfy the WHERE clause and no rows will be updated.

Oracle database query throws error on second run

i have an VBA code where i am calling oracle to retrieve data twice using ODBC.
First data retrieval is fine. But 2nd time it is saying ,
**RunTime Error '-2147467259 (80004005)'; Unspecified error**
My Code is as follows,
Note: Same code works for connecting Teradata but failed when i use
Oracle
'First Data retrieval
Query1 = "Select TableName from all_tables"
CmdSQLData.CommandText = Query1
CmdSQLData.CommandType = adcmdText
CmdSQLData.Timeout=0
set rs = CmdSQLData.Execute()
'Then code to store data ...
'This part gives proper result ...
rs.close()
'Second Data retrieval
Query2 = "Select * from db.Event"
CmdSQLData.CommandText = Query2
CmdSQLData.CommandType = adcmdText
CmdSQLData.Timeout=0
set rs = CmdSQLData.Execute() 'This line Gives Error - RunTime Error '-2147467259 (80004005)'; Unspecified error
Also i tried creating new command object as cmdSQLData1 but still same
error
May i know why the error is coming for second query ?
There is no problem with query as i have tested in oracle directory.
Please let me know
You won't see this documented much of anywhere, but reusing Command objects with different comamndText is actually a bad practice. You don't say what kind of connection you're using, but for example if it's ODBC, this will internally send a fake invalid SQL to Oracle to force a cleanup of some kind. So instead, throw away your Command object after use and create a new one.
Reusing Command objects is a good practice when you're re-executing the same query with different parameter values, but that's not the case here.
You do not need to use command text at all for those types of queries what you could do is :-
` Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
con.Open "DSN=Oracle", "User", "Password"
rs.Open "select * from table_a", con
' Read all results
rs.Close
rs.Open "select * from table_b", con
' Read all results
rs.Close
con.Close
You only need to use "Command" if you plan to use a store procedure or a query with bound parameters.

Oracle db gives ORA-01722 for seemingly NO REASON AT ALL

I'm trying to use an Oracle database with ado.net, and it is proving a painful experience. I use Oracle Client (Oracle.Data namespaces).
The following query runs fine from a query window:
UPDATE PRINT_ARGUMENT
SET VALUE = 'Started'
WHERE REQUEST_ID = 1 AND KEYWORD = '{7D066C95-D4D8-441b-AC26-0F4C292A2BE3}'
When I create an OracleCommand however the same thing blows up with ORA-01722. I can't figure out why.
var cmd = cnx.CreateCommand();
cmd.CommandText = #"
UPDATE PRINT_ARGUMENT
SET VALUE = :value
WHERE REQUEST_ID = :requestID AND KEYWORD = :key";
cmd.Parameters.Add(new OracleParameter("requestID", (long)1);
cmd.Parameters.Add(new OracleParameter("key", "{7D066C95-D4D8-441b-AC26-0F4C292A2BE3}");
cmd.Parameters.Add(new OracleParameter("value", "Started");
cnx.Open();
try { int affected = cnx.ExecuteNonQuery(); }
finally { cnx.Close(); }
When I inspect the command in the debugger, the parameters appear to have mapped to the correct types: requestID has OracleDbType.Int64, key and value are both OracleDbType.Varchar2. The values of the parameters are also correct.
This gets even stranger when you consider that I have other queries that operate on the exact same columns (requestID, keyword, value) using the same approach - and they work without a hiccup.
For the record, the column types are requestID NUMBER(10,0); key VARCHAR2(30); value VARCHAR2(2000).
According to Oracle, ORA-01722 'invalid number' means a string failed to convert to a number. Neither of my string values are numbers, neither of the OracleParameters created for them are numeric, and neither
By default, ODP.NET binds parameters by position, not by name, even if they have actual names in the SQL (instead of just ?). So, you are actually binding requestID to :value, key to :requestID and value to :key.
Correct the order of cmd.Parameters.Add in your code, or use BindByName to tell ODP.NET to use the parameter names.
Since you are using named parameters, you have to tell the Oracle client about it. Otherwise your parameters are mixed up (key is assigned to :value):
OracleParameter parameter = new OracleParameter("requestID", (long)1);
parameter.BindByName = true;
cmd.Parameters.Add(parameter);
It's a strange and unexpected behavior, but that's how it is.

DAO recordset with substring function

i have a vb6 application that i am using DAO to create a connection to a database and trying to open a recordset. the database is a foxpro database and i have refernece to Microsoft DAO 2.5/3.5 Compatibility Library.
my code is as follows
Dim gdbSMS As Database
If gdbSMS Is Nothing Then
Set gdbSMS = OpenDatabase("C:\Work\M2M Test\DATA", False, False, "Foxpro 2.6;")
End If
Dim sql As String
sql = "select *, substr(lineitem,8,6) as aa from shippers where shipper = '001322' order by aa"
Dim rsShipper As DAO.Recordset
Set rsShipper = gdbSMS.OpenRecordset(sql)
Do While Not rsShipper.EOF
Beep
rsShipper.MoveNext
Loop
rsShipper.Close
when i execute teh line for openrecordset i get an error "undefinied function 'substr' in expression
i run the exact same query in foxpro and it works fine. any thoughts on what i need to do to get this to work with substring functions?
thanks
Try using the T-SQL SUBSTRING function instead.
SUBSTRING ( value_expression , start_expression , length_expression )
Without using DAO recordsets, but instead using DataTables, and data adapters using OleDBProvider for Foxpro data (definitely not going back to Fox 2.x) gives you more current flexibility in querying....
That said, you could try by doing what SUBSTR() actually does... Try changing to
RIGHT( LEFT( LineItem, 14 ), 6 ) as AA

Resources