I'm trying to get data from Oracle to a Datatable. My idea was to create a function to do all connection staff and then call it from other parts of the code.
Like:
dt = New DataTable
dt = Oracle2table(sql.ToString)
Then, I created the function:
Function Oracle2table(ByVal sql As String) As DataTable
Oracle2table = Nothing
Try
conn = New OleDb.OleDbConnection(connString)
conn.Open()
cmd = New OleDbCommand(sql, conn)
adaptador = New OleDbDataAdapter
adaptador.SelectCommand = cmd
adaptador.Fill(Oracle2table)
conn.Dispose()
Catch ex As Exception
MessageBox.Show("Error al cargar la tabla. ERROR = " + ex.ToString)
Finally
Oracle2table = Nothing
End Try
End Function
The problem with this code is initialize the variable (Oracle2table = nothing) so i didn't receive a function error.
I am not VB specialist, but this code worked fine, so it may be useful for you:
Dim dt = Oracle2table("select * from dual")
Console.WriteLine(dt.Rows(0)(0))
Function (I removed exception handling for simplicity):
Function Oracle2table(ByVal sql As String) As DataTable
Dim conn = New OleDbConnection(connString)
Oracle2table = New DataTable
conn = New OleDb.OleDbConnection(connString)
conn.Open()
Dim cmd = New OleDbCommand(sql, conn)
Dim adaptador = New OleDbDataAdapter
adaptador.SelectCommand = cmd
adaptador.Fill(Oracle2table)
conn.Dispose()
End Function
Related
I am testing Oracle database. I wrote some code but my datareader has no rows, why? My "carros" table has data and I am selecting all of them but I am getting an empty result set it seems.
string constr = "Data Source=localhost:1521/XE;User Id=System;Password=password;";
OracleConnection con = new OracleConnection(constr);
OracleCommand oracleCommand = new OracleCommand();
oracleCommand.Connection = con;
oracleCommand.CommandText = "select preco from carro";
con.Open();
OracleDataReader oracleDataReader = oracleCommand.ExecuteReader();
string resultado = String.Empty;
//My test, I got hasRows as false
if (oracleDataReader.HasRows == false)
{
resultado = "no results";
}
//never enters this loop.
while (oracleDataReader.Read())
{
resultado += (string)oracleDataReader["preco"];
}
// Close and Dispose OracleConnection
con.Close();
con.Dispose();
return resultado;
If HasRows is false after ExecuteReader, the problem is simply that the query is returning no rows so Read will return false as well. Perhaps the someValue variable is not set correctly.
From you description, it seems that your table is named carros while your query has used carro. Try to use
oracleCommand.CommandText = "select preco from carros";
A path towards solving this can include a scattering of logging commands that write to the file system.
System.IO.File.AppendAllText(#"\\server\\C\\log.txt", "put error message here" + "\r\n");
Or for printing a variable:
System.IO.File.AppendAllText(#"\\server\\C\\log.txt", ex.ToString() + "\r\n");
Pepper variations of this command throughout your script to see where failures are happening and to validate variable values.
I have this c# code
public static DataSet Get_Workflow_Def()
{
OracleConnection conn = DatabaseHelper.getOracleConnection();
DataSet dataset = new DataSet();
Log.Info("Opening connection");
conn.Open();
OracleCommand cmd = new OracleCommand("CTS.GET_WORKFLOW_DEF", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("p_Dataset", OracleDbType.RefCursor).Direction =
ParameterDirection.Output;
Log.Info("Executing query");
cmd.ExecuteNonQuery();
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.Fill(dataset);
conn.Close();
return dataset;
}
Calling this procedure
create or replace procedure CTS.GET_WORKFLOW_DEF(p_Dataset OUT
Sys_Refcursor)
as
begin
Open p_Dataset For
Select WKF_ID,
WKF_WORKFLOW_ID,
WKF_WORKFLOW_NAME,
WKF_WORKFLOW_VERSION,
WKF_WORKFLOW_SCHEMA
FROM CTS.WKF_WORKFLOW_MASTER
WHERE WKF_WORKFLOW_ACTIVE = '1'
ORDER BY WKF_ID DESC;
end GET_WORKFLOW_DEF;
If I execute the query I get the information I am looking for but the RefCursor is null. I'm an Oracle newb. Can anyone see where I am going wrong?
Found my problem I needed to add this line before the da.fill(dataset); line and after I instantiated the OracleDataAdapter in my c# code
da.TableMappings.Add("Table",
ConfigurationManager.AppSettings["DBPullTable"].ToString());
I have problem with running this:
i captured picture from my win
OleDbConnection con = new OleDbConnection();
DataTable dt = new DataTable();
con.ConnectionString = "Provider=MSDAORA;Data Source=DATA;Password=ss8_pakhsh;User ID=SHIFTS_N";
con.Open();
string sqlcommand = "INSERT INTO GROUPS(GROUP_ID, GROUP_NAME,DEPT_ID) " +
"VALUES(SEQ_MAX_GROUP_ID_NO.NEXTVAL,#groupName,SELECT
DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE
DEPARTMENT_NAME=#depName)";
OleDbCommand command = new OleDbCommand(sqlcommand, con);
command.Parameters.AddWithValue("#groupName", textBox1.Text);
command.Parameters.AddWithValue("#depName", comboBox1.SelectedItem);
OleDbDataAdapter oda = new OleDbDataAdapter(command);
oda.Fill(dt);
dataGridView2.DataSource = dt;
con.Close();
Change the sqlcommand string as shown below,
string sqlcommand = "INSERT INTO GROUPS(GROUP_ID, GROUP_NAME,DEPT_ID) " +
"VALUES(SEQ_MAX_GROUP_ID_NO.NEXTVAL,#groupName,SELECT "+
"DEPT_ID FROM PERSONNEL_TEMP.DEPARTMENT WHERE "+
"DEPARTMENT_NAME=#depName)";
This should solve the issue.
Observation: It is not a good practice to directly set the textBox1.Text value in parameter.
so this code works with just the out parameter but then when you add in parameters weird nulls start showing up and also the straight in parameters work too so it is just when there are both in and out parameters.
the part with problems is the in and out parameters do not want to coexist
cmd.Parameters.Add("PKEY", OracleDbType.Int64, ParameterDirection.Output)
For Each kvp As KeyValuePair(Of String, String) In sqlParams
Dim newParam As New OracleParameter(kvp.Key, OracleDbType.Varchar2, kvp.Value, Data.ParameterDirection.Output)
newParam.Size = 400
cmd.Parameters.Add(newParam)
Next
This works
Public Shared Sub Run_Oracle_Query(ByVal queryToRun As String, ByVal sqlParams As Dictionary(Of String, String))
Dim dbConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ITSS").ConnectionString
Dim con As OracleConnection = New OracleConnection(dbConnString)
Dim cmd = con.CreateCommand()
Try
con.Open()
cmd.CommandText = queryToRun
cmd.CommandType = CommandType.Text
For Each kvp As KeyValuePair(Of String, String) In sqlParams
cmd.Parameters.Add(kvp.Key, kvp.Value)
Next
cmd.ExecuteNonQuery()
'log all sql queryies very expensive operation
LogThisString("Log All queries: " & queryToRun, "Always")
Catch ex As OracleException ' catches only Oracle errors
OracleExceptionLogging(ex.Number, queryToRun, ex)
Catch ex As Exception
LogThisString("General Error SQL: " + ex.Message.ToString(), "Always")
' MsgBox("Could Not Perform This Database Operation")
Finally
con.Close()
cmd.Dispose()
con.Dispose()
End Try
End Sub
This works
Public Shared Function Run_Insert_Oracle_Query_Return_ID(ByVal queryToRun As String, ByVal IDcolumnName As String) As String
Dim dbConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ITSS").ConnectionString
Dim con As OracleConnection = New OracleConnection(dbConnString)
Dim cmd = con.CreateCommand()
Dim strUkey As String = ""
Try
con.Open()
cmd.CommandText = queryToRun & " RETURNING " & IDcolumnName & " INTO :UKEY"
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("PKEY", OracleDbType.Int64, ParameterDirection.Output)
cmd.ExecuteNonQuery()
strUkey = cmd.Parameters("PKEY").Value.ToString
Return strUkey
Catch ex As OracleException ' catches only Oracle errors
OracleExceptionLogging(ex.Number, queryToRun, ex)
Catch ex As Exception
LogThisString("General Error SQL: " + ex.Message.ToString(), "Always")
PopupMsgBox("Database Error", "Database Integrity Constants Violated SQL Operation Will Not Be Executed")
Finally
con.Close()
cmd.Dispose()
con.Dispose()
End Try
Return strUkey
End Function
This does not work
Public Shared Function Run_Insert_Oracle_Query_Return_ID(ByVal queryToRun As String, ByVal IDcolumnName As String, ByVal sqlParams As Dictionary(Of String, String)) As String
Dim dbConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ITSS").ConnectionString
Dim con As OracleConnection = New OracleConnection(dbConnString)
Dim cmd = con.CreateCommand()
Dim strUkey As String = ""
Try
con.Open()
cmd.CommandText = queryToRun & " RETURNING " & IDcolumnName & " INTO :UKEY"
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("PKEY", OracleDbType.Int64, ParameterDirection.Output)
For Each kvp As KeyValuePair(Of String, String) In sqlParams
Dim newParam As New OracleParameter(kvp.Key, OracleDbType.Varchar2, kvp.Value, Data.ParameterDirection.Output)
newParam.Size = 400
cmd.Parameters.Add(newParam)
Next
cmd.ExecuteNonQuery()
strUkey = cmd.Parameters("PKEY").Value.ToString
Return strUkey
Catch ex As OracleException ' catches only Oracle errors
OracleExceptionLogging(ex.Number, queryToRun, ex)
Catch ex As Exception
LogThisString("General Error SQL: " + ex.Message.ToString(), "Always")
PopupMsgBox("Database Error", "Database Integrity Constants Violated SQL Operation Will Not Be Executed")
Finally
con.Close()
cmd.Dispose()
con.Dispose()
End Try
Return strUkey
End Function
crap so i guess it does look for order asnd the output does need to be at end like this.....this works solved my own problem
For Each kvp As KeyValuePair(Of String, String) In sqlParams
Dim newParam As New OracleParameter(kvp.Key, OracleDbType.Varchar2, kvp.Value, Data.ParameterDirection.Input)
newParam.Size = 400
cmd.Parameters.Add(newParam)
Next
cmd.Parameters.Add("PKEY", OracleDbType.Int64, ParameterDirection.Output)
I am trying to call a oracle stored procedure in c# like this
OdbcDataAdapter da = new OdbcDataAdapter();
da.SelectCommand = new OdbcCommand();
da.SelectCommand.Connection = con;
da.SelectCommand.Connection.Open();
da.SelectCommand.CommandText = "KAMRAN.ATTN";
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.ExecuteNonQuery();
da.SelectCommand.Connection.Close();
Label3.Text = "Attendance Posted Successfully";
But I am showing this error
ERROR [42000] [Oracle][ODBC][Ora]ORA-00900: invalid SQL statement
Please any One Can tell what exactly i am missing to call this procedure.plz help !
You could try to inverse the statements:
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.CommandText = "KAMRAN.ATTN";
Also, maybe try to add:
da.SelectCommand.Parameters.Clear();
before
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.CommandText = "KAMRAN.ATTN";
I think that you should also use a DataTable
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
Maybe that it should also be an Oracle Data Adapter:
OracleDataAdapter da = new OracleDataAdapter();
da.SelectCommand = new OracleCommand();
So you should have:
OracleDataAdapter da = new OracleDataAdapter();
da.SelectCommand = new OracleCommand();
da.SelectCommand.Connection = con;
da.SelectCommand.Connection.Open();
da.SelectCommand.Parameters.Clear();
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.CommandText = "KAMRAN.ATTN";
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
da.SelectCommand.Connection.Close();
I hope this helps in any way.