OracleDataAdapter not filling DataTable when querying to a DBLink - c#

I'm trying to execute a query from OracleDataAdapter in C#, this query will go to a DBLink available in the DB, but for some reason when it needs to fill the datatable it throws me an error:
IndexOutOfRangeException - ndex was outside the bounds of the array
the code I'm trying to execute is:
OracleConnection conn = new OracleConnection(connectionString);
conn.Open();
DataSet dataSet = new DataSet();
OracleCommand cmd = new OracleCommand("select count(*) alive from dual#MYDBLINK");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
{
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(dataSet); //Here is where it fails
}
The query works if I execute in sql developer, and the code works if I remove the DBLink information and let the query as select count(*) alive from dual, so I asume, that the issue here is something with the DBLink or the # character.

Related

How to run SQL that has declare statements via SqlCommand?

This is a sample query:
declare #tempTable table
(
Id bigint
)
-- populating with temp Ids
select *
from TargetTable
where Id not in
(
select Id
from #tempTable
)
And this is C# code:
public DataTable Get(string sql)
{
var dataTable = new DataTable();
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand())
{
connection.Open();
command.Connection = connection;
command.CommandText = sql;
var dataReader = command.ExecuteReader();
dataTable.Load(dataReader);
}
return dataTable;
}
Running this code throws exception, complaining that:
Incorrect syntax near the keyword 'declare'.
Incorrect syntax near
')'.
I know it's possible to use join instead of #tempTable, but is there a way to run this query?
A SqlDataAdapter object can be used to populate a DataTable as follows. Instead of calling SqlCommand.ExecuteReader(), the SqlDataAdapter.Fill() method is used. In this example the argument to the Fill() method is the DataTable that will be populated. While this approach will work with the query you posted with the table variable, I'd strongly recommend converting this to a stored procedure and filling the DataTable from this instead. Additionally, unless the amount of data that's being sent into the table variable is very small using a temp table will offer more functionality (more accurate statistics, better DML performance, ROLLBACK participation, etc.) than table variables and I'd suggest using a temp table instead as well.
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataTable dataTable = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand command = new SqlCommand(cmd, connection);
da.SelectCommand = command;
connection.Open();
da.Fill(dataTable);
}
Stored Procedure Call:
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataTable dataTable = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
//use SP name for command text
SqlCommand command = new SqlCommand("usp_ProcedureName", connection);
//stored procedure command type
command.CommandType = CommandType.StoredProcedure;
da.SelectCommand = command;
connection.Open();
da.Fill(dataTable);
}
You can create a Stored Procedure of your query then add this to your code:
command.CommandType = CommandType.StoredProcedure;
Then use exec command
command.CommandText = "exec procedureName"
If your query location is in database itself.

Gridview datasource from database stored procedure

This is the database stored procedure:
ALTER PROCEDURE [dbo].[getShift]
#rfiddata VARCHAR(50)
AS
BEGIN
SELECT
pd.TP, s.s_name, dt.dt_type, dr.dr_date
FROM
TA_System_PersonalDetails pd
INNER JOIN
TA_System_DutyRequest dr ON pd.TP = DR.TP
INNER JOIN
TA_System_Duty d ON dr.d_ID = d.d_ID
INNER JOIN
TA_System_Shift s ON d.s_ID = s.s_ID
INNER JOIN
TA_System_DutyType dt ON d.dt_ID = dt.dt_ID
WHERE
pd.rfid_card = #rfiddata
AND dr.dr_date = CAST(GETDATE() AS DATE)
END
And this the C# code:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("dbo.getShift", con);
cmd.Parameters.AddWithValue("#rfiddata", data);
cmd.CommandType = CommandType.StoredProcedure;
gvDetails.DataSource = cmd.ExecuteNonQuery();
con.Close();
The gridview still not able to show the value. And this project is in windows form C#. Hence, there is no DataBind() function. Thanks in advance for the help!
I hope this code will help
First we create a connector to connect to the database
string cnStr = #"Persist Security Info=False;User ID=usr;password=pwe; Initial Catalog=theDataBase;Data Source=yourDatasource";
and create a SqlCommand and after set the CommandType to StoredProcedure:
SqlCommand cmd = new SqlCommand();
Then create a SqlConnection and Open Database:
using(SqlConnection con = new SqlConnection(cnStr))
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "dbo.getShift"; // this is the stored procedure to execute
cmd.CommandType = CommandType.StoredProcedure;
}//Connection automatically closes here without the need to call conn.Close()
Then create a dataset to be filled as the datasource for the gridview:
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
grdYourGrid.DataSource = ds;
grdYourGrid.DataBind();

Oracle Data Provider for .Net - No data querying

I am using Oracle Data Provider for .NET Assembly to query Oracle database.
Below is my code.
Though the code runs with no error. I don’t get data to my dataset dsOracleData.
However, when I run the query after connecting to SQL Developer, I can see the resulting data for the query.
OracleConnection conn = new OracleConnection(“ConnectionString”)
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = Query1.ToString();
cmd.CommandType = CommandType.Text;
OracleDataAdapter adapter = new OracleDataAdapter(cmd);
OracleCommandBuilder builder = new OracleCommandBuilder(adapter);
DataSet dsOracleData = new DataSet();
adapter.Fill(dsOracleData);
Hi u can try like this,
OracleConnection conn = new OracleConnection("Your Connection string");
Conn.Open;
DataSet dataSet = new DataSet();
OracleCommand cmd = new OracleCommand("your select query");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
{
dataAdapter.SelectCommand = cmd;
dataAdapter.Fill(dataSet);
}

C# and SQL Server: How do I get values from my SQL Table, by calling my stored procedure with C#?

I created the following stored procedure
CREATE PROCEDURE dbo.GetPoint
AS
SELECT point FROM tLocalGeo
Now I need execute that procedure from my C# Controller and save the data on a list.
As you can see the context of the problem is to get points so then I can display them on google map using javascript for that.
Can you give me some reference how to do it? Do I need SQLReader?
Thank you for your attention.
You can use SqlDataAdapter and DataSet and then can get values from dataset's first table.
SqlCommand cmd = new SqlCommand("store procedure Name", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter= new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds);
if(ds.Tables[0]!=null && ds.Tables[0].Rows.Count > 0)
{
//your code
}
Hope it helps.
String strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "GetPoint";
cmd.Parameters.AddWithValue("#EmployeeID", Empid) // ur input parameter//
cmd.Connection = con;
try
{
con.Open();
GridView1.EmptyDataText = "No Records Found";
GridView1.DataSource = cmd.ExecuteReader() ;
GridView1.DataBind();
}

Calling a SP which has Insert Statement and returns a table

Is it possible to call a stored procedure which will insert the details first and at the end will return a table. At present I have written two stored procedures for it: one for inserting and the other for getting the details. Now I'm trying to do both at the same time.
I'm using ExecuteScalar for inserting and ExecuteDataSet for selecting.
If your stored procedure returns data using a SELECT (of course, I suppose that you need to read that data) then you should use the SqlDataAdapter with its Fill method or an SqlDataReader using the ExecuteReader on the SqlCommand
ExecuteReader:
using(SqlConnection cn = new SqlConnection(...))
using(SqlCommand cmd = new SqlCommand(procName, cn))
{
cmd.CommandType = CommandType.StoredProcedure;
cn.Open()
using(SqlDataReader r = cmd.ExecuteReader())
{
while(r.Read())
{
// read every row and use the field values .....
}
}
}
SqlDataAdapter.Fill:
using(SqlConnection cn = new SqlConnection(...))
using(SqlCommand cmd = new SqlCommand(procName, cn))
{
cmd.CommandType = CommandType.StoredProcedure;
cn.Open()
using(SqlDataAdapter da = new SqlDataAdapter(cmd)
{
DataTable dt = new DataTable();
da.Fill(dt);
// DataTable filled with the data returned by the last SELECT in your SP
......
}
}
The SqlCommand.ExecuteReader or SqlDataAdapter.Fill will execute the stored procedure without looking at what the stored procedure does, but they expect that some kind of tabular data will be returned to loop over it
You write a procedure like this
CREATE PROCEDURE SP_Name
(
//PARAMETES
)
AS
BEGIN
//INSERT STATEMENT
//SELECT STATEMENT
END
and call ExecuteDataSet()
SqlConnection cn = new SqlConnectio(...)
SqlCommand cmd = new SqlCommand("procName", cn)
{
cmd.CommandType = CommandType.StoredProcedure;
cn.Open();
cmd.ExecuteScalar();
}

Categories