How to connect to Oracle database - c#

I am using below code to connect to an oracle server. I need to particularly use OdbcConnection class because I am doing enhancement of an existing application which currently connects to SQL Server using this method. So I have to use the same method for other DBMS also.
I have tried with the code below:
const string ConnectionString = #"SERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MachineName.Domain.com)(PORT=1521))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME=orcl.Domain.com)));uid=system;pwd=user";
using (OdbcConnection connection = new OdbcConnection(ConnectionString))
{
connection.Open();
}
But I get an exception when calling the Open() method as follows:
"ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"
Any idea of what I am doing wrong here?

Have a look at Oracle connection strings
You connectionString should be like this:
var DB = #"SERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MachineName.Domain.com)(PORT=1521))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME=orcl.Domain.com)))";
string ConnectionString = "Driver={Oracle in OraClient11g_home1};Dbq=" + DB + ";uid=system;pwd=user;"
The driver name might be different on your machine. You could also use the ODBC driver from Microsoft (Driver={Microsoft ODBC for Oracle};Server=...), however this is deprecated for ages.
Actually I prefer the DbConnectionStringBuilder (or even OdbcConnectionStringBuilder)
var str = new DbConnectionStringBuilder(true);
str.Add("Driver", "Oracle in OraClient11g_home1");
str.Add("Dbq", #"(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=MachineName.Domain.com)(PORT=1521))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME=orcl.Domain.com)))");
str.Add("Uid", "system");
str.Add("Pwd", "user");
string ConnectionString = str.ConnectionString;

///Your connection string should be like
string str = Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = abc )(PORT = 123))(CONNECT_DATA =(SID = xyz)));User Id=abc_xyz;Password=111;Min Pool Size=10;Connection Lifetime=120;Connection Timeout=600;Incr Pool Size=5; Decr Pool Size=2;validate connection=true;
using (OracleConnection con = new OracleConnection(str))
{
using (OracleCommand cmd = con.CreateCommand())
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = RoutineConstant.Text;
cmd.BindByName = true;
cmd.ExecuteNonQuery();
if (cmd.Parameters["Value"].Value != null && cmd.Parameters["Value"].Value != DBNull.Value)
{
return Convert.ToDecimal(cmd.Parameters["Value"].Value.ToString());
}
}
}

Related

TSQL logging inside transaction using CLR stored procedure

I'm trying to write a log into another database inside a transaction so that the log will survive even if the transaction is rolled back. I've read this answer which says:
One possibility is to use a CLR stored procedure to do the logging. This can open its own connection to the database outside the transaction and enter and commit the log data.
So I created CLR stored procedure using this article:
[SqlProcedure]
public static void Voice(SqlString procedureName, SqlInt32 id)
{
Connection = new SqlConnectionStringBuilder();
Connection.ContextConnection = true;
using (TransactionScope transScope = new TransactionScope())
{
using (SqlConnection conn = new SqlConnection(Connection.ToString()))
{
conn.Open();
SqlCommand cmdInsert = conn.CreateCommand();
cmdInsert.CommandText = sql;
cmdInsert.Parameters.Add("#id", SqlDbType.Int);
cmdInsert.Parameters[0].Value = id;
cmdInsert.Parameters.Add("#procedureName", SqlDbType.NVarChar);
cmdInsert.Parameters[1].Value = procedureName;
cmdInsert.ExecuteNonQuery();
}
transScope.Complete();
}
}
However, data is not saved afer I executed and rolled back stored procedure in SQL Server:
BEGIN TRAN
EXEC dbo.SayHelloVoice #id = 1,
#procedureName = N'FooProcedure'
ROLLBACK TRAN
We have three environments:
dev. Server name is Q-SQL001
test. Server name is Q-SQL002
prod. Server name is Q-SQL003
So this CLR stored procedure should work on all environments.
Could you say what I am doing wrong?
Any help would be greatly appreciated!
UPDATE:
So the work version looks like this. Big thanks to the #Milney:
var serverName = string.Empty;
var dbName = string.Empty;
serverName = SqlExecuteScalar("SELECT ##SERVERNAME");
dbName = SqlExecuteScalar("SELECT DB_NAME()");
SqlConnectionStringBuilder sqlConn = new SqlConnectionStringBuilder();
sqlConn.InitialCatalog = dbName;
sqlConn.DataSource = serverName;
sqlConn.IntegratedSecurity = true;
sqlConn.ContextConnection = false;
sqlConn.Enlist = false;
sqlConn.ApplicationName = "New application";
var sql = "USE FooDatabase
INSERT INTO dbo.MyTable ..."
using (SqlConnection conn2 = new SqlConnection(sqlConn.ConnectionString))
{
conn2.Open();
SqlCommand cmdInsert = conn2.CreateCommand();
cmdInsert.CommandText = sql;
cmdInsert.Parameters.Add("#id", SqlDbType.Int);
cmdInsert.Parameters[0].Value = storeTime;
cmdInsert.Parameters.Add("#messageText", SqlDbType.NVarChar);
cmdInsert.Parameters[1].Value = messageText;
cmdInsert.ExecuteNonQuery();
}
If you use:
Connection.ContextConnection = true;
Then it's going to use the same connection that the CLR Sproc is running in - you need to open a new connection.

SQL Bulk DestinationTableName

I use a .csv file to bulk insert into my SQL Server database. The problem is DestinationTableName because when I use a string for DestinationTableName, I get error exception
System.InvalidOperationException: Cannot access destination table
as you can see in the screenshot.
If a use "test" like copy.DestinationTableName = "test"; it works fine
string symbolName = dt.Rows[1][0].ToString();
string strConnection = #"Data Source =.\SQLEXPRESS; AttachDbFilename = C:\USERS\JEF\DOCUMENTS\DATABASE1.MDF; Integrated Security = True; Connect Timeout = 30; User Instance = True";
SqlConnection condb2 = new SqlConnection(strConnection);
string createTablerow ="create table ['"+symbolName+"'] (code1 VARCHAR(100) COLLATE Arabic_CI_AI_KS_WS,date1 varchar(50),open1 varchar(50),high1 varchar(50),low1 varchar(50),close1 varchar(50),vol1 varchar(50))";
using (SqlConnection connection = new SqlConnection(strConnection))
{
SqlCommand command1 = new SqlCommand(createTablerow, connection);
connection.Open();
command1.ExecuteNonQuery();
}
using (SqlConnection cn = new SqlConnection(strConnection))
{
cn.Open();
using (SqlBulkCopy copy = new SqlBulkCopy(cn))
{
copy.ColumnMappings.Add(0, "code1");
copy.ColumnMappings.Add(1, "date1");
copy.ColumnMappings.Add(2, "open1");
copy.ColumnMappings.Add(3, "high1");
copy.ColumnMappings.Add(4, "low1");
copy.ColumnMappings.Add(5, "close1");
copy.ColumnMappings.Add(6, "vol1");
copy.DestinationTableName = symbolName;
copy.WriteToServer(dt);
}
}
Just like you did when you created the table:
"create table ['"+symbolName+"']
the trick here is probably to escape the table name to compensate for the hyphen in it, so:
copy.DestinationTableName = "[" + symbolName + "]";
Note: if possible, it is usually preferable to stick to names that don't need escaping. But... if it works.

How can i write correct oracle connection string in c#?

I'm beginner in oracle and c# ,i want simple application in c# use the oracle database,i write this connection string for connect to the database:
conn.ConnectionString = "Data Source=BEHBEHZAD;User ID=SYSTEM;Password=beh1368421";
my full code is this:
OracleConnection conn = new OracleConnection();
conn.ConnectionString = "Data Source=BEHBEHZAD;User ID=SYSTEM;Password=beh1368421";
try
{
conn.Open();
conn.Close();
MessageBox.Show("Connect Successfull!!");
}
catch (Exception )
{
MessageBox.Show("Disconnect!!");
}
but when i run that program i get Disconnect Message,my TNS file detail is this:
BEHBEHZAD =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = behbehzad)
)
)
How can i solve that?thanks.
ORA-12557 is apparently not related to your connection string but to a problem with your Path variable. Please follow the instructions in this article.

Unable to read from Azure database

I'm trying to read/write to an Azure database but I receive the following error message when using the SqlDataReader in my code below:
Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.
I can connect to the database in SQL Server Management Studio. Any suggestions as to why this might be and how to resolve this?
My C# code:
string connectionString = "Server=tcp:[xxxxx].database.windows.net,1433;Database=[xxxxx];User ID=[xxxxx]#[xxxxx];Password=[xxxxx];Trusted_Connection=False;Encrypt=True;Connection Timeout=30;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
string sql = "SELECT [xxxxx], [xxxxx] FROM [xxxxx]";
using (SqlCommand cmd = new SqlCommand(sql))
{
using (SqlDataReader reader = Database.ExecuteReader(cmd))
{
if (!reader.Read())
{
throw new Exception("[xxxxx] not found.");
}
else
{
name = Database.GetStringValue(reader, "[xxxxx]", "");
}
}
}
}
Make sure the IP you are connecting to the database form is white listed on your database configuration in Azure. Sounds like a firewall problem to me.
I don't know how but rearranging my code to the following below resolved my issue and I could read the data that I wanted.
string connectionString = "Server=tcp: [xxxxx].database.windows.net,1433;Database=[xxxxx];User ID=[xxxxx]#[xxxxx];Password=[xxxxx];Trusted_Connection=False;Encrypt=True;Connection Timeout=30;";
SqlConnection myConnection = new SqlConnection(connectionString);
try
{
myConnection.Open();
SqlDataReader reader = null;
SqlCommand myCommand = new SqlCommand("SELECT [xxxxx] FROM [xxxxx]", myConnection);
reader = myCommand.ExecuteReader();
if (!(reader.Read()))
throw new Exception("[xxxxx] not found.");
else
cert = reader["[xxxxx]"].ToString();
myConnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}

SQL connection c#

I have a standart local Oracle DB to which i can connect with my sqldeveloper
using connection with :
username = system
password = orcl
hostname = localhost
port = 1521
SID = ORCL
but when i'm trying to do this in the code
try
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "localhost";
builder.InitialCatalog = "HR_ORCL";
builder.UserID = "system";
builder.Password = "orcl";
string connectionString = "Server=(local);Database=HR_ORCL;User ID=system;Password=orcl";
using (SqlConnection connection = new SqlConnection())
{
connection.ConnectionString = builder.ConnectionString;
connection.Open();
Console.WriteLine("State: {0}", connection.State);
Console.WriteLine("ConnectionString: {0}",
connection.ConnectionString);
}
}
catch(Exception error)
{
System.Console.WriteLine(error.Message);
}
I'm getting an error
"provider: Named Pipes Provider, error: 40 - Could not open a
connection to SQL server"
What am i doing wrong ?
As correctly said by Stefan you need to download and install ODP from this site
Once the installation is done you need to add a reference of the assembly Oracle.DataAccess.dll.
And then you can use it like this:
using System;
using Oracle.DataAccess.Client;
class MyClass
{
OracleConnection con;
void Connect()
{
con = new OracleConnection();
con.ConnectionString = "yourconnectionstring";
con.Open();
}
void Close()
{
con.Close();
con.Dispose();
}
static void Main()
{
//some code
}
}

Categories