Executing Stored Procedure using C# - c#

I have a procedure named as Get_Added_Request_ID and using this procedure I need to get returned the Request_ID value (VARCHAR2). I have referrd plenty of docs released by Oracle and Microsoft but still I could not find a good solution may be because I am a new learner for Oracle and ASp.NET. Please someone help me in this issue. Thanks in advance
-- Parameter Type Mode Default?
-- ATTR_ VARCHAR2 IN
-- REQUEST_ID VARCHAR2 OUT

Please view this link for the documentation on how to connect to oracle by using oracle data provider
You should use oracle data provider from this link for connecting oracle.
the example code for your scenario will be
Using System;
using System.Collections.Generic;
using System.Text;
using System.Data.OracleClient;
using System.Data;
namespace CallingOracleStoredProc
{
class Program
{
static void Main(string[] args)
{
using (OracleConnection objConn = new OracleConnection("Data Source=*your datasource*; User ID=*Your UserID*; Password=*Your Password*"))
{
OracleCommand objCmd = new OracleCommand();
objCmd.Connection = objConn;
objCmd.CommandText = "Get_Added_Request_ID";
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.Parameters.Add("ATTR_", OracleType.NVarChar).Value = "test";
objCmd.Parameters.Add("REQUEST_ID", OracleType.NVarChar).Direction = ParameterDirection.Output;
try
{
objConn.Open();
objCmd.ExecuteNonQuery();
System.Console.WriteLine("The Request ID is {0}", objCmd.Parameters["REQUEST_ID"].Value);
}
catch (Exception ex)
{
System.Console.WriteLine("Exception: {0}",ex.ToString());
}
objConn.Close();
}
}
}
}

use execute scalar which return 1 row - 1 column value & store it in appropriate variable
For e.g :- SqlHelper.ExecuteScalar(_connectionString, CommandType.StoredProcedure, "Get_Added_Request_ID", null);
note :- ExecuteScalar is came from nuget Microsoft.Application Block

Related

Oracle SQL statement returns no rows when executed from C# application

Following SQL statement returns data when executed in Oracle SQL Developer:
SELECT TC_GUID FROM TBLBUF WHERE TC_DEST = 'aaaaaaa' AND TC_STATE <= 20
but when it is executed in a following C# code, reader returns no rows.
using Oracle.ManagedDataAccess.Client;
using System;
using System.Data;
using System.Data.Common;
using System.Threading;
using System.Threading.Tasks;
namespace OracleQuery
{
public class Program
{
public static DbDataReader QueryReader()
{
OracleConnection connection = new OracleConnection(".........");
connection.Open();
using (OracleCommand command = connection.CreateCommand())
{
command.InitialLOBFetchSize = -1;
command.InitialLONGFetchSize = -1;
((IDbCommand)command).Transaction = null;
command.CommandText = "SELECT TC_GUID FROM TBLBUF WHERE TC_DEST = 'aaaaaaa' AND TC_STATE <= 20";
command.CommandType = CommandType.Text;
return command.ExecuteReader(CommandBehavior.Default | CommandBehavior.CloseConnection);
}
}
public static void Main(string[] args)
{
DbDataReader reader = QueryReader();
while (reader.Read())
{
string s = (string)reader["TC_GUID"];
Console.WriteLine(s);
}
}
}
}
When I leave only one part of WHERE clause, either TC_DEST = 'aaaaaaa' or TC_STATE <= 20, it returns rows.
What could be a reason for such behaviour?
What could be a reason for such behaviour?
Rows which have been INSERTed but not COMMITted are only visible inside the session in which they were created. Therefore, if you have created some new rows but have not issued a COMMIT command in the SQL Developer session, you will not be able to see that uncommitted data from any other session (even if you connect as the same user, as it will create a different session).
If this is the the case, the solution would be to COMMIT the data in the SQL Developer session and it would then be visible to other sessions.

C# Error Selecting Table in OleDbCommand ...*LIBL not found

I'm trying to make a connection to a DB2 Database sitting on our AS400 (ISeries). I can connect to is successfully using the connection string but once I try to access the Tables I get this error: CPF9812: File SELECT in library *LIBL not found.
At this point I'm just trying to see if i can access the data in the table GLPCT.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Data;
namespace Testing_Connection_to_GLDBFA
{
class Program
{
static void Main(string[] args)
{
string connectionstring = "Provider=IBMDARLA.DataSource.1;Data Source=INFINIUM;Persist Security Info=True;Password=MyPassword;User ID=UserID;Initial Catalog=S06947A4;Default Collection=GLDBFA";
string querySTring = "";
DataTable schema;
int i = 0;
using( OleDbConnection cn = new OleDbConnection(connectionstring))
{
querySTring = "SELECT * FROM GLPCT";
OleDbCommand command = new OleDbCommand(querySTring, cn);
cn.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0].ToString());
i++;
if (i == 20)
break;
}
cn.Close();
}
}
}
}
Any help or guidance is greatly appreciated.
Thanks in advance.
I'd expect to see the following error:
CPF9812: File GLPCT in library USERID not found.
As by default when using SQL naming the system will implicitly qualify unqualified table names with the user ID. For details, see here
It appears you are using an OLE DB provider instead of the .NET provider
If you want to use the library list, you'll need use system naming and ensure that the library list is configured on the connection.
For the OLEDB providers, you want to set the Library List and Naming Convention
<connection>.Open('Provider=IBMDA400;Data Source=SystemA;Library List=lib1,lib2, *USRLIBL;Naming Convention=1', 'Userid', 'Password');
For .NET provider, it's LibraryList and Naming properties.
Lastly, if you want to stay with the OLE DB provider, you might consider using the IBMDASQL instead of the IBMDARLA one.

Strange behaviour of OracleDataReader in Read() method

Hi all Oracle experts,
I have a rather strange behaviour of a very very simple program only intended to test basic data acquisition from a remote Oracle database with C#.
I have created a simple C# program as follows:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Oracle.ManagedDataAccess.Client;
class Program
{
static void Main(string[] args)
{
var connectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP) (HOST={{Server}})(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME={{DataSource}})));User Id={{Username}};Password={{Password}};";
connectionString = connectionString.Replace("{{DataSource}}", "Actual service name");
connectionString = connectionString.Replace("{{Server}}", "Actual Server IP");
connectionString = connectionString.Replace("{{Username}}", "Actual username");
connectionString = connectionString.Replace("{{Password}}", "Actual password");
using (connection = new OracleConnection {ConnectionString = connectionString})
{
connection.Open();
using ( var cmd = connection.CreateCommand() )
{
cmd.CommandText = "SELECT * FROM Table";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
i++;
}
}
}
}
}
}
The table I am reading from has 220.000 entries, and the problem with the code is, that after an amount of "rows" the reader.Read() just stops. It is supposed to return "false" if there are no more records, and there are still records to come, but the Read() function is called and never returns. Even after letting it try for hours it does not come back.
Does anyone have had a similar experience?
I already heard not to use the Microsoft Oracle Data Driver, so I am using the one from oracle. But still the problem does not go away.
The amount of rows retrieved changes if you change the SQL Command, but also not in a very understandable way: I thought if this has to do with the network buffers I can reduce the columns to get more rows, but it works in the opposite direction. More columns result in more rows.
Any help is deeply appreciated.

.NET and sql server database link

I'm a real noob in .NET and i'm trying to link a simple command line application (in C#) with a SQL server database. I'm now able to connect the program with the database but not to recover the data that are in it. Here is my code :
using System;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
string queryString = "SELECT USER_ID FROM dbo.ISALLOCATEDTO;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = queryString;
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
int i = 0;
while (reader.Read())
{
i++;
Console.WriteLine("Field "+i);
Console.WriteLine("\t{0}",reader[0]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//Console.WriteLine("Hello world");
string x = Console.ReadLine();
}
static private string GetConnectionString()
{
return "Data Source=FR401388\\SQLEXPRESS;Initial Catalog=Test;";
+ "Integrated Security=SSPI";
}
}
}
But when i'm running it and even if my table is not empty (I've seen it in the sql server studio), I cannot recover the data by using the read() method.
What I've done so far : try to change the name of the datatable with a fake one : the datatable is not found (so the link between sql server database and programm seems to be valid).
I'm using Windows Authentication in sql server, dunno if it's changing anything... (Once again : i'm very new to all of that).
Thanks !
Your code should work.
A possible cause is: You are looking at a different database.
This is quite common if you use Server Explorer inside VS with a connectionstring different from the one used in code.

what is wrong in my code to call a stored procedure

I Have created a Stored procedure dbo.test as follows
use sample
go
create procedure dbo.test as
DECLARE #command as varchar(1000), #i int
SET #i = 0
WHILE #i < 5
BEGIN
Print 'I VALUE ' +CONVERT(varchar(20),#i)
SET #i = #i + 1
END
Now i am created a c# console application to call the stored procedure as follows
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace AutomationApp
{
class Program
{
public void RunStoredProc()
{
SqlConnection conn = null;
SqlDataReader rdr = null;
try
{
conn = new SqlConnection("Server=(TEST\\SQL2K5EXPRESS);DataBase=sample,IntegratedSecurity=SSPI");
conn.Open();
SqlCommand cmd = new SqlCommand("sample.dbo.test", conn);
cmd.CommandType = CommandType.StoredProcedure;
//cmd.ExecuteNonQuery();
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
rdr[0], rdr[1]));
}
}
catch(Exception ex)
{
Console.writeLine(ex.message);
}
finally
{
if (conn != null)
{
conn.Close();
}
if (rdr != null)
{
rdr.Close();
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Hello World");
Program p= new Program();
p.RunStoredProc();
Console.Read();
}
}
}
O/P:
Hello World
//Could not find stored procedure 'test'.
A network-related or instance-specific error occurred while establishing a conne
ction to SQL Server. The server was not found or was not accessible. Verify that
the instance name is correct and that SQL Server is configured to allow remote
connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Serve
r/Instance Specified)
But when i try to run the program it was closing so i debugged the program then at exactly at executeReader() method it was showed that can not find the stored procedure "dbo.test"
and when i give the "EXEC dbo.test" at SSMS it display the result as i expected.
waht is wronng with this any Help greatly Appreciated.
Why are you looking in the master database?
Also, your code needed some cleanup:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace AutomationApp
{
class Program
{
public void RunStoredProc()
{
Console.WriteLine("\nTop 10 Most Expensive Products:\n");
using (SqlConnection conn =
new SqlConnection(
"Server=(local);DataBase=master;IntegratedSecurity=SSPI"))
{
conn.Open();
using (SqlCommand cmd =
new SqlCommand("dbo.test", conn) {
CommandType = CommandType.StoredProcedure})
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
rdr[0], rdr[1]));
}
}
}
}
}
}
}
I would suggest it is related to teh permissions granted to the stored procedure.
Check out "GRANT EXECUTE <storedProc> TO <User>" you could also check the permissions in SSMS by right clicking on the stored proc.
I understand this is a test stored proc but it is not optimal to create stored procedures in the master database.
All the best :)
Just change your connection string:
conn = new SqlConnection("Server=(local);DataBase=master;IntegratedSecurity=SSPI");
You're hitting the master database. You want to hit whatever your database is called.
Alternatively, call the stored proc as dbname.dbo.test.
First of all - there's typo in your connection string - you need to use all semicolons - not semicolon once and commas the other time. Between DAtaBase= and IntegratedSEcurity, you have a comma - plus, it has to be "Integrated Security" (with a space!). Check out www.connectionstrings.com for the details on how to properly create a connection string.
Your original connection string in your post:
conn = new SqlConnection(
"Server=(TEST\\SQL2K5EXPRESS);DataBase=sample,IntegratedSecurity=SSPI");
should really be:
conn = new SqlConnection(
"Server=(TEST\\SQL2K5EXPRESS);DataBase=sample;Integrated Security=SSPI");
Once that would work, I think the main problem is that you're trying to pass in a SQL statement in the parameter #command to the stored procedure, which you execute inside the stored procedure (not in your current post, but in others you've posted), and you want to read out the rows returned by that statement.
But you have no way of being sure (short of parsing the SQL statement you're passing in) whether or not that SQL statement will actually indeed return values or whether it's a DDL statement like INSERT, CREATE TABLE or something.
So you have ADO.NET, calling a stored proc, which dynamically executes an arbitrary SQL statement, and you still want to be able to retrieve those results....
In my opinion, you need to rearchitect your approach - this will never work reliably - find another way to do what you're trying to do - there must be a way to do this with less dynamic execution of SQL inside a stored proc and stuff........ there's gotta be an easier way!
Marc
Have you tried just using "test" instead of "dbo.test"?
Your stored procedure doesn't return any results. Change your PRINT into SELECT.
You may be getting the error because ADO.NET doesn't know how to react to the status messages the print statement causes.
The SQL error you see is connecting to the server. It doesn't even get that far, so it isn't related to permissions at all. As far as your client goes, you'd get the same error if you connected to "Server=GroverCleveland\Instance1" (assuming it doesn't exist on your network).
I think that the problem is that you are wrapping the server name in parens, if you can connect to it fine using other SQL clients on the same client box. Try the following:
conn = new SqlConnection("Server=TEST\\SQL2K5EXPRESS;DataBase=sample;IntegratedSecurity=SSPI");
Marc is right about the semicolon, btw. Check out connectionstrings.com for details on that...

Categories

Resources