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");
Related
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;
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
I am creating an ArrayDescriptor in order to pass CLOB data to an Oracle function. I have a class in which I have injected (#Inject) a jdbcTemplate...this is an implementation class which has calls out to Oracle. I am creating the ArrayDescriptor like:
Connection conn = auditJdbcTemplate.getDataSource().getConnection();
ArrayDescriptor keyArryDesc = ArrayDescriptor.createDescriptor("VC_ARR", conn);
The error I am receiving is:
java.lang.ClassCastException: com.sun.proxy.$Proxy183 cannot be cast to oracle.jdbc.OracleConnection
at oracle.sql.ArrayDescriptor.createDescriptor(ArrayDescriptor.java:105
As I stated, I have direct calls in this class to auditJdbcTemplate.update that work successfully so I am not sure why it can't return a valid connection object from the template. I have seen several answers in StackOverflow to get the underlying connection and I have not been able to get that to work.
Maybe someone find it useful:
Connection conn = jdbcTemplate.getDataSource().getConnection().unwrap(OracleConnection.class);
I have used this code to connect to XE database:
OracleConnection con = new OracleConnection();
con.ConnectionString = "data source=XE;user id=hr;password=sdmo1365";
con.Open();
OracleCommand com = new OracleCommand();
com.CommandText = "select * from regions;";
com.Connection = con;
DataTable dt = new DataTable();
dt.Load(com.ExecuteReader());
con.Close();
grd.DataSource = dt;
grd.DataBind();
it is working in one pc while not working in another and giving this error:
oracleexception was unhandled by user code
the only difference in tnsnames.ora of those pc is in the one that is not working the host is longer(becuase the user is under domain:)
(HOST = MOSININI-9.novini.mms.sti)
is this making the problem?
thanks
I simply reinstalled it and everything get solved!(I waste 2 hours)
I have an issue when trying to start the SqlDependency.
The error informs me: Keyword not supported: 'metadata'.
The connectionstring is the following when retrieved from the immediate window right before it crashes.
?objectContext.Connection.ConnectionString
"metadata=res://*/YeagerTech.csdl|res://*/YeagerTech.ssdl|res://*/YeagerTech.msl;provider=System.Data.SqlClient;provider connection string=\"data source=Bill-PC;initial catalog=YeagerTech;integrated security=True;multipleactiveresultsets=True;App=EntityFramework\""
Here is the code. It crashes on the Start method. Apparently, it doesn't think the EF connectionstring is valid. Any idea of how I can correctly use this?
YeagerTechEntities dbContext = new YeagerTechEntities();
ObjectContext objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
SqlDependency.Start(objectContext.Connection.ConnectionString);
Because EF connection string is not valid for SqlDependency. It works only with EntityConnection but SqlDependency uses SqlConnection. So you must either use direct connection string in your dbContext or extract database connection string from entity connection.
Either:
var connectionString = dbContext.Database.Connection.ConnectionString;
Or
var connectionString = ((EnityConnection)objectContext.Connection).StoreConnection.ConnectionString;
Anyway EF doesn't play very well with SqlDependency. SqlDependency expects that you write SQL queries yourselves and have them under your control.
Actually, the code snippet that I got it to work is the following:
YeagerTechEntities dbContext = new YeagerTechEntities();
ObjectContext objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
Application["dbContext"] = dbContext;
objectContext.Connection.ConnectionString =
ConfigurationManager.ConnectionStrings["YeagerTechEntities"].ConnectionString;
SqlDependency.Start(((System.Data.EntityClient.EntityConnection)objectContext.Connection)
.StoreConnection.ConnectionString);
YeagerTechEntities is the EF connectionstring.