How to call a Oracle stored procedure (PL/SQL) from .NET? - c#

I am new to Oracle. There is a requirement in our firm for a project using Oracle and .Net. So I was trying to run a demo application. I am using Oracle 10g XE as DB and VS2010.
I wrote a procedure with a simple select query, which got compiled (got this procedure format by googling).
I ran the stored procedure from the SQL command prompt from XE Dashboard itself. This was the result:
Now I wrote code in C# to call that stored procedure:
string sqlCon = "Data Source=xe;Persist Security Info=True;User ID=sa;Password=password;Unicode=True;Provider=OraOLEDB.Oracle;";
OleDbConnection Con = new OleDbConnection(sqlCon);
OleDbCommand cmd = new OleDbCommand();
DataSet ds = null;
OleDbDataAdapter adapter;
try
{
Con.Open();
////Stored procedure calling. It is already in sample db.
cmd.CommandText = "TESTPROC";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = Con;
ds = new DataSet();
adapter = new OleDbDataAdapter(cmd);
adapter.Fill(ds, "Users");
return ds.Tables[0];
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
This code block didn't throw any exceptions. It got executed but what I received was an empty Dataset. But when I tried to fetch data using the query directly I got the result.
So, is the way I am trying to access the stored procedure correct? or Is there any mistake in my stored procedure? Can anyone point out the error or the best way to do this?
Thanks in advance.

Suggestion: try declaring "result" as an "out" parameter:
https://forums.oracle.com/forums/thread.jspa?messageID=4566433
Here's one other link that might help:
http://support.microsoft.com/kb/309361

There is another link that might help:
http://www.akadia.com/services/ora_return_result_set.html

Related

How to show data in a datagridview in oracle using c#

I am trying to to execute stored procedure that I have created in my oracle and trying to show data from stored procedure into datagridview using C#.Someone please help me how do i execute stored procedure.
It is actually pretty simple. You just call the stored procedure, use a DataAdapter and load/populate a DataTable from the adapter and finally bind the DataSource property of the DataGridView or similar control to the DataTable.
Here's a sample code :
using (var conn = new OracleConnection(connectionString))
using (var cmd = new OracleCommand("ProcedureName", conn) {
CommandType = CommandType.StoredProcedure }) {
conn.Open();
using(OracleDataAdapter da = new OracleDataAdapter (cmd))
{
DataTable dataTable = new DataTable();
da.Fill(dataTable);
dataGridView1.DataSource = dataTable;
}
conn.Close();
I personally never used Oracle, the code above is actually the general-ish code for such tasks. I hope this works.

How To create a stored procedure for SQL Server from C# code?

I am trying to create a stored procedure in SQL server from a C# winforms application.
This is the function I have so far.
public void CreateStoredProcedure(string SPname)
{
try
{
string query = "CREATE PROCEDURE " + SPname + " AS SELECT * FROM People WHERE Address='Mumbai'";
connection.Open();
var command = new SqlCommand();
command.CommandType = CommandType.Text;
command.CommandText = "EXEC " + query;
command.ExecuteNonQuery();
}
finally
{
connection.Close();
}
}
Am I doing this right? I get an error message every time I try to achieve this.
Hey thanks a lot guys!! Its working now..
This is the code that finally did it..
public void CreateStoredProcedure(string SPname)
{
try
{
string query = "CREATE PROCEDURE " + SPname + " AS SELECT * FROM People WHERE Address='Mumbai'";
connection.Open();
var command = new SqlCommand();
command.Connection = connection;
command.CommandText = query;
command.ExecuteNonQuery();
var adapter = new SqlDataAdapter(command);
adapter.Fill(dt);
dgv.DataSource = dt;
}
finally
{
connection.Close();
}
}
much appreciated! :)
You do not need EXEC when creating a stored procedure
and you need an active connection
You can try:
command.CommandType = CommandType.StoredProcedure;
Initialize connection property of your command:
command.Connection = connection;
Alternatively, you can create a Stored Procedure using Common Language Run-time integration in stead of doing it on the fly.
How to: Create and Run a SQL Server Stored Procedure by using Common Language Run-time Integration
Deploy CLR Stored Procedure to database
In your attempt above the code will only be able to run as a once off as it contains a CREATE command. It must then change to ALTER there after or you need to drop it every time and re-created. this would not be the best practice but just keep in mind.
You need to define a connection object and link it with the command object
CommandObject.Connection= ConnectionObject;
Also the CommandType.Text is by default.
You could also check if you connection is open using
if(ConnectionObject.State== ConncetionState.Closed)
{
ConnectionObject.Open();
}
If it is closed, you will need an active Open connection to pass a query.

C# SQL Server old data

I have the following code in a dll that I use to query a SQL Server 2008 database
connectionString = #"Server=totmobdb-bod\live_mobile_data;Database=TM5Admin;User Id=ourusername;Password=ourpassword;MultipleActiveResultSets=true;";
dbConn.ReturnSingleTable("select Detail from dbo.Details where Name = 'RepairsReport'", mainConnectionString).Rows[0].ItemArray[0].ToString();
public DataTable ReturnSingleTable(string query, string connectionString)
{
DataSet dataSet = new DataSet();
using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlDataAdapter adapter = new SqlDataAdapter())
{
adapter.SelectCommand = new SqlCommand(query, conn);
adapter.Fill(dataSet);
};
};
DataTable dataTable = dataSet.Tables[0];
return dataTable;
}
I recently changed a value in the database through SQL Server Management Studio.
The problem is that the query in my code is some times bringing back the old value and sometimes bringing back the new value.
When I connect to the database using the same username/password as the query does I can see the correct value.
Any ideas folks?
Although SQL Server Management Studio has implicit commit turned on,There might be a chance that changes which you made through your update query might not have committed data in the table,use commit after you execute the query.

Microsoft Access OleDb Connection Error

I am trying to access an Access 2003 database remotely from my ASP.NET application. My code is:
DataSet dsImportedData = new DataSet();
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
conn.ConnectionString = #"Provider=MS Remote;Remote Provider=Microsoft.Jet.OLEDB.4.0;Remote Server=http://myIp;Data source=C:\myDatabase.mdb;";
try
{
System.Data.OleDb.OleDbCommand command = conn.CreateCommand();
command.CommandText = "SELECT * FROM myTable";
conn.Open();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(command);
adapter.Fill(dsImportedData);
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
However, I am always getting an exception stating: {"[Microsoft][ODBC Microsoft Access Driver] Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'."}
My command is basic, I have no idea what could be wrong with it. Did anyone confront with the same issue? Thanks!
Try this ....
String command = "SELECT * FROM myTable";
conn.Open();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(command, conn);
adapter.Fill(dsImportedData);
Apparently the error can be caused by the specified table not existing. Just a thought...
Another thought would be to remove the remoting complexity and try to get to the most simple working code, possibly with a new access database just to start to narrow down what is causing the problem.
If you set the command type to Stores procedure it works for me.
command.CommandType = System.Data.CommandType.StoredProcedure;

When using an OracleCommand in .net must the OracleClient be installed on the machine or does .net cover this?

I want to make a simple query on an Oracle database from .net using similar code to this.
using System;
using System.Data;
using Oracle.DataAccess.Client;
class Sample
{
static void Main()
{
// Connect to Oracle
string constr = "User Id=scott;Password=tiger;Data Source=AKI1.WORLD";
OracleConnection con = new OracleConnection(constr);
con.Open();
// Display Version Number
Console.WriteLine("Connected to Oracle " + con.ServerVersion);
// Read REF CURSOR into DataSet
DataSet ds = new DataSet();
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = "GetComplexTabPkg.GetEmp";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("p_dep", OracleDbType.Int16).Value = 20;
cmd.Parameters.Add("p_ref", OracleDbType.RefCursor).Direction
= ParameterDirection.Output;
OracleDataAdapter da = new OracleDataAdapter(cmd);
da.TableMappings.Add("Emp", "Emp");
da.Fill(ds);
// Close and Dispose OracleConnection
con.Close();
con.Dispose();
// Show Message
Console.WriteLine("DataSet filled");
}
}
My only concern is does the Oracle Client need to be installed on the web server that is running this code? It's my first time using this and I would like to avoid any obvious issues that can be prevented. Thanks.
Yes, Oracle Client need to be installed in web server. The work around will be to ship your application with Instant Oracle Client
On my Own I just install 64-bit Oracle Data Access Components (ODAC) Downloads, which seems to be lighter than Oracle Client.

Categories