How To Use ODAC With Visual Studio 2015 Call Oracle DB (Stored-Function) - oracle

There is a strange problem that has been found in Oracle DB with Visual Studio by my project. First I open my Toad to check Oracle function like as below picture:
When I have put 3 parameter's value into SF_GET_COMP_SVAL, it is working ,and then when I have tried it in my project as following, it also works very well.
using (OracleConnection con = new OracleConnection(ConfigurationManager.ConnectionStrings["OracleDbContext"].ToString()))
{
using (OracleCommand cmd = new OracleCommand())
{
cmd.CommandText = "select PG_AIS.SF_GET_COMP_SVAL('3','2','1') from dual";
try
{
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
}
catch
{
}
}
}
However it can't be working when I use Paramters mode like as following code
cmd.CommandText="select PG_AIS.SF_GET_COMP_SVAL(:a1,:a2,:a3) from dual"; cmd.Parameters.Add("a2", "1");
cmd.Parameters.Add("a3", "2");
cmd.Parameters.Add("a1", "3");
why????

I wasted half day and have found the ODAC problem in my case, why can't insert into data with paramters in Visual Studio platform , because of parameters name , if fact in my MySql and MSSql there don't need to follow the sequence with parameter , but unfortunately in the Oracle it can't change ordering ,the parameter's depends on index sequence so that you can change any parameter's name
cmd.CommandText="select PG_AIS.SF_GET_COMP_SVAL(:a1,:a2,:a3) from dual";
cmd.Parameters.Add("a1", "3");
cmd.Parameters.Add("a2", "2");
cmd.Parameters.Add("a3", "1");
or
cmd.CommandText="select PG_AIS.SF_GET_COMP_SVAL(:a1,:a2,:a3) from dual";
cmd.Parameters.Add("xx", "3");
cmd.Parameters.Add("a2", "2");
cmd.Parameters.Add("a3", "1");
parameter a1 or xx is the same (depends on index sequence not parameter name)
both codes can get the same result.
PS: Hopefully it will be modify soon by Oracle Provider.

I have found another method to deal with this problem , please try it
OracleCommand command = new OracleCommand(query, connection)
{ CommandType = CommandType.Text, BindByName = true };
PS:http://www.codeproject.com/Articles/208176/Gotcha-sharp-Using-Named-Parameters-with-Oracl <-- it could be a great way to deal with

Related

The provider is not compatible with the version of oracle (ASP.NET Core MVC)

I'm really frustrated and i do not know what to do.
I'm trying to connect to an Oracle 11g database but every time I try to connect Visual Studio 2019 throws an error message. I already tried a lot of different things but nothing really helped me.
I have already made sure the app set to run in 32 bit mode in the IIS console. I still can't figure out why is not working.
By the way, here is my code:
readonly string connectionString = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=xxxxxxxxx)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=PROD)));User Id=xxx;Password=xxxx;"
public IEnumerable<Person>GetPersonList
{
var listPerson = new List<Person>();
using (OracleConnection con = new OracleConnection(connectionString))
{
OracleCommand cmd = new OracleCommand("select * from myview", con);
cmd.Connection = con;
cmd.InitialLOBFetchSize = 1000;
cmd.CommandType = CommandType.Text;
con.Open();
OracleDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
var list = new Person();
list.CODE = Convert.ToInt32(dr["CODE"].ToString());
list.NAME = dr["NAME"].ToString();
list.LASTNAME = dr["LASTNAME"].ToString();
listPerson.Add(list);
}
con.Close();
}
return listPerson;
}
What should I do?
My problem was solved: needed to install instant client for Oracle 11g and everything worked just fine

Query Oracle using .net core throws exception for Connect Identifier

I'm quite new to Oracle and never used that before, now, I'm trying to query an Oracle database from a .Net Core Web Application having nuget package oracle.manageddataaccess.core installed and using an alias as the Data Source but I'm receiving the following error:
If I use the full connection string the query will work correctly
ORA-12154: TNS:could not resolve the connect identifier specified
at OracleInternal.Network.AddressResolution..ctor(String TNSAlias, SqlNetOraConfig SNOConfig, Hashtable ObTnsHT, String instanceName, ConnectionOption CO)
at OracleInternal.Network.OracleCommunication.Resolve(String tnsAlias, ConnectionOption& CO)
at OracleInternal.ConnectionPool.PoolManager`3.ResolveTnsAlias(ConnectionString cs, Object OC)
at OracleInternal.ServiceObjects.OracleConnectionImpl.Connect(ConnectionString cs, Boolean bOpenEndUserSession, OracleConnection connRefForCriteria, String instanceName)
So, from a few links I could understand that there is a tsnnames.ora file which must contain the map between connect identifiers and connect descriptors. And that this file can be found at the machine on which the Oracle has been installed with the path ORACLE_HOME\network\admin.
Question is:
Does the alias name that I'm using in my connection string which reads as Data Source: <alias_name>; User ID=<user>; Password=<password> need to be specified in the tsnnames.ora file? I don't have access to the machine where the Oracle database resides on otherwise I would have checked it earlier.
Here's the code snippet for more info: connection string and query values are mocked out
public static string Read()
{
const string connectionString = "Data Source=TestData;User ID=User1;Password=Pass1";
const string query = "select xyz from myTable";
string result;
using (var connection = new OracleConnection(connectionString))
{
try
{
connection.Open();
var command = new OracleCommand(query) { Connection = connection, CommandType = CommandType.Text };
OracleDataReader reader = command.ExecuteReader();
reader.Read();
result = reader.GetString(0);
}
catch (Exception exception)
{
Console.WriteLine(exception);
throw;
}
}
return result;
}
Is this enough or something else needs to be added/changed in here? Or probably the issue is with the tsnNames.ora file which might not contain the alias name here?
Thanks in advance
For the Data source
Data Source=TestData;User Id=myUsername;Password=myPassword;
Your tnsnames.ora probably should have the below entry
TestData=(DESCRIPTION=
(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost) (PORT=MyPort)))
(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)))
Since
Data Source=TestData;User Id=myUsername;Password=myPassword;
is same as
Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=MyHost) (PORT=MyPort)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=MyOracleSID)));User Id=myUsername;Password=myPassword;

How to read columns of SQL Server tables in Visual Studio?

In Microsoft Access functions like DLookup - DMax or Dcount help the programmer to read a column from a table of a SQL Server database.
How do you do the same task in Visual Studio?
For example how can I find the ID of a user (John) in tblUsers table.
tblUsers columns: ID, Username, Password, .....
I've already added the SQL Server database to the Data Source.
Any kind of advice is much appreciated.
ow. Even in Access, that isn't proper.
Go read up on DAO, ADO, and, if you're using Visual Studio to write .Net applications, the system.data namespace.
in general, when accessing relational data via non-database program code, including the vba you're using in Access, you'd retrieve a reference to a Recordset object and query each record's fields as object properties.
If you want to visualize all of the data, click Database Explorer (see the tab at the bottom of the solution explorer), then expand your data connections and right click the name of the table, then click 'show table data'. If you want only the id's or names etc, I usually just create an SQL script to run, and run it when I want to browse certain data.
To simply create a script, while you're viewing all the data, click the script button above the table your viewing. Then you can execute your script
SELECT * FROM tblUsers WHERE User = 'John';
I hope I've understood your questions correctly.
I followed DougM and ended up with the following code. I will add it here just in case somebody else has the same question:
using System.Data.SqlClient; should be added to the reference section
private void button1_Click(object sender, EventArgs e)
{
string fltr = "UserName='Ando'";
MessageBox.Show(ReadOrderData(fltr));
}
public string ReadOrderData(string filter)
{
string connectionString = "Data Source=sqlServer-servername;Initial Catalog=database name;Integrated Security=True";
string queryString = "SELECT User_ID, UserName FROM tblUsers WHERE " + filter + ";";
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(
queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
return reader[0].ToString();
//Console.WriteLine(String.Format("{0, {1",
// reader[0], reader[1]));
}
}
finally
{
// Always call Close when done reading.
reader.Close();
}
}
return "Null";

Create Pervasive Database using Distributed Tuning Objects (DTO)

I am writing an application in C# (.NET 4.0) which has to integrate with another, much older application. Part of the requirement is to integrate with a much older program that uses Pervasive PSQL Version 9. I asked this question about accessing the database without having to install an ODBC DSN. Part of the answer (thanks very much) is that I need to create a database using DTO.
I've used COM interop to access the dto2.dll COM library, and have read the samples, but I am having problems creating the database. Here is a summary of the code I'm using.
var session = new DtoSession();
var result = session.Connect("localhost", "", "");
Assert.AreEqual(dtoResult.Dto_Success, result);
testDB = new DtoDatabase {
Session = session,
Name = "Test1",
Ddfpath = #"C:\TEMP\DATA\DDF",
DataPath = #"C:\TEMP\DATA",
};
result = session.Databases.Add(testDB);
Assert.AreEqual(dtoResult.Dto_Success, result);
No matter what values I use for the Name and paths, that final Assert always fails. The error code is Dto_errDuplicateName. If I do not include the Session property I get a different error code (7039).
Has anyone done this successfully? What am I doing wrong?
I believe you are missing the Flags property of the DtoDatabase object. I had the following code in my archive as an example of adding a database with DTO. This code was probably written when DTO was first released but it works and the only difference I can see is the Flags property.
DtoSession session = new DtoSession();
dtoResult result;
result = session.Connect("localhost", "","");
if (result != dtoResult.Dto_Success)
{
Console.WriteLine("Error connecting. Error code: " + result.ToString());
return;
}
DtoDatabase testDB = new DtoDatabase();
testDB.Name = "Test1";
testDB.DataPath = #"C:\DATA";
testDB.DdfPath = #"C:\DATA";
testDB.Flags = dtoDbFlags.dtoDbFlagNotApplicable;
result = session.Databases.Add(testDB);
if (result != dtoResult.Dto_Success)
{
Console.WriteLine("Error Adding. Error code: " + result.ToString());
return;
}
Console.WriteLine("DB Added.");

Oracle and Transaction naming

I've been programing with SQL Server and C# for quite some time and I have some code that I need to change to work with Oracle:
SqlConnection connection = (SqlConnection)CreateDBConnection();
IDbTransaction transaction = connection.BeginTransaction(level, "name");
The problem is: if I use OracleConnection instead of SqlConnection there is no way to specify a name for my transaction. I know that the syntax in Oracle allows named transactions, but I don't seem to find a way to do it through .net code.
You can not set the transaction name.
But it is possible to specify a name for the SAVEPOINT.
OracleConnection oracleConnection = new OracleConnection((string.Format("Data Source={0};User Id={1};Password={2}", DATABASE, USERNAME, PASSWORD));
oracleConnection.Open();
OracleCommand oracleCommand = oracleConnection.CreateCommand();
oracleConnection.BeginTransaction();
OracleTransaction oracleTransaction = oracleCommand.Transaction;
oracleTransaction.Save("name");
//...
oracleTransaction.Rollback("name");

Resources