I need to connect to oracle from my .Net application.
I'm thinking of using ODP.NET
Is there a way to connect to Oracle without any dependency on the tnsnames.ora file? Reason I ask is because I'll have hundreds of different connections and I wouldnt want to be dependant on that file.
Yes, if you use a connection string that contains the data of tnsname.ora.
Say your tnsname entry looks like this:
YourTnsName =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = YourHost)(PORT = 1521))
)
(CONNECT_DATA =
(SID = YourSid)
)
)
instead of using YourTnsName in the connection string, you can write it like this:
var constr = new OracleConnectionStringBuilder()
{
DataSource = #"(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = YourHost)(PORT = 1521)))(CONNECT_DATA =(SID = YourSid)))",
UserID = "userid",
Password = "password",
}.ConnectionString;
using (var con = new OracleConnection(constr))
{
...
}
hence no entry in tnsname.ora is needed.
Related
Installed Plesk on my VS. After this I can't setup SSH-tunnel to get data from other server-database. Using SSH.NET with below code. (This code works locally). Configured to allow communication for port 3306 in Plesk firewall. Any suggestions on how to solve this issue?
Error:
[SocketException (0x271d): An attempt was made to access a socket in a
way forbidden by its access permissions]
Code:
DataTable dt = new DataTable();
string IP = "ssh.xxxxxxxx.xxx";
string Username = "xxxxxxxxxx";
string password = "xxxxxxxxxx";
var connInfo = new Renci.SshNet.PasswordConnectionInfo(IP, Username, password);
using (var sshClient = new Renci.SshNet.SshClient(connInfo))
{
sshClient.Connect();
if (sshClient.IsConnected)
{
Renci.SshNet.ForwardedPortLocal port =
new Renci.SshNet.ForwardedPortLocal("127.0.0.1", 3306, "xxxxxxxx", 3306);
sshClient.AddForwardedPort(port);
port.Start();
using (MySqlConnection con = new MySqlConnection("SERVER=127.0.0.1;PORT=3306;UID=xxxxxx;PASSWORD=xxxxxxx;DATABASE=xxxxxxx; convert zero datetime=True"))
{
string tmpsql = "Select fname,lname,username FROM tbluser Where id=#id";
using (MySqlCommand cmd = new MySqlCommand(tmpsql, con))
{
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("id", MySqlDbType.Int16).Value = UserID;
da.Fill(dt);
}
}
}
sshClient.Disconnect();
}
The local port which you are trying to forward is most probably already used by another application (like a local MySQL database server).
Use another port. Or even better, let the system pick any free local port:
var port = new ForwardedPortLocal("127.0.0.1", "dbserver.example.com", 3306);
client.AddForwardedPort(port);
port.Start();
var connectionString =
$"SERVER={port.BoundHost};PORT={port.BoundPort};" +
"UID=xxxxxx;PASSWORD=xxxxxxx;DATABASE=xxxxxxx; convert zero datetime=True";
using (MySqlConnection con = new MySqlConnection(connectionString))
{
// ...
}
Related: C# SSH tunnel Postgres database connection
In my TnsNamesOra I have
TEST11.12.13.14 =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = 11.12.13.14)(PORT = 1234))
)
(CONNECT_DATA =
(SERVICE_NAME = TESTNAME)
)
)
If my connection string looks like this:
Data Source = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 11.12.13.14)(PORT = 1234)))(CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = TEST))); User Id = admin; Password = admin ; DBA Privilege = SYSDBA ; Pooling = false; Connection Timeout = 30" providerName="Oracle.DataAccess.Client
Everything works fine.
But I want to do something like this:
Data Source = TEST11.12.13.14; User Id = admin; Password = admin ; DBA Privilege = SYSDBA ; Pooling = false; Connection Timeout = 30" providerName="Oracle.DataAccess.Client
But getting error
ORA-12154: TNS:could not resolve the connect identifier specified
Currenlty I am using the following connection string to connect to oracle database
string Source = new OracleConnectionStringBuilder()
{
DataSource = #"(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = YOURHOST)(PORT = 1521)))(CONNECT_DATA =(SID = TESTORACLE)))",
}.ConnectionString;
private IDbConnection databasecon= new OracleConnection(Source);
I have no idea how to specify that connect using os authentication
Finally found the way to create Non TNS windows authentication connection stringstring Source = new OracleConnectionStringBuilder()
{
DataSource = #"(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = YOURHOST)(PORT = 1521)))(CONNECT_DATA =(SID = TESTORACLE)))",
UserID = #"/",
}.ConnectionString;
private IDbConnection databasecon= new OracleConnection(Source);
without user id and password just use UserID = #"/" for windows authentication
I'm just trying to return a list of columns and their attributes through a system stored procedure. What documentation I have seems to say the below code should work, but I get "Pervasive.Data.SqlClient.Lna.k: [LNA][Pervasive][ODBC Engine Interface]Invalid or missing argument." on the execute. This is PSQL v11, .NET 4.5.
using (PsqlConnection conn = new PsqlConnection(cs))
{
PsqlCommand locationCmd = new PsqlCommand();
PsqlParameter tableParam = new PsqlParameter();
PsqlParameter returnParam = new PsqlParameter();
returnParam.Direction = ParameterDirection.ReturnValue;
locationCmd.CommandText = "psp_columns";
locationCmd.Connection = conn;
locationCmd.CommandType = CommandType.StoredProcedure;
locationCmd.Parameters.Add(tableParam).Value = table;
locationCmd.Parameters.Add(returnParam);
conn.Open();
locationCmd.ExecuteNonQuery();
}
I would think the problem is this line:
locationCmd.Parameters.Add(tableParam).Value = table;
You should set the value before adding the parameter, not afterwards.
tableParam.Value = table;
locationCmd.Parameters.Add(tableParam);
I don't know about Psql but for MSSQL normally you also need to define the parameter name as its found in the stored procedure, or at least that's what I do.
SqlParameter param = new SqlParameter("#tableParam", value);
The psp_Columns system stored procedure is defined as call psp_columns(['database_qualifier'],'table_name', ['column_name']). I know that it says the database qualifier is optional, but I think it's required. You could try passing an empty string for the qualifier. Something like:
using (PsqlConnection conn = new PsqlConnection(cs))
{
PsqlCommand locationCmd = new PsqlCommand();
PsqlParameter dbParam = new PsqlParameter();
PsqlParameter tableParam = new PsqlParameter();
PsqlParameter returnParam = new PsqlParameter();
returnParam.Direction = ParameterDirection.ReturnValue;
locationCmd.CommandText = "psp_columns";
locationCmd.Connection = conn;
locationCmd.CommandType = CommandType.StoredProcedure;
locationCmd.Parameters.Add(dbParam).Value = ""; //might need two single quotes ('')
locationCmd.Parameters.Add(tableParam).Value = table;
locationCmd.Parameters.Add(returnParam);
conn.Open();
locationCmd.ExecuteNonQuery();
}
You should try to get the information of the table SCHEMA using the provided GetSchema method from the Psqlconnection. I have searched a bit on their support site and it seems that this method is supported although I haven't find a direct example using the Tables collection.
This is just an example adapted from a test on mine on SqlServer, I don't have Pervasive install, but you could try if the results are the same
using(PsqlConnection cn = new PsqlConnection("your connection string here"))
{
cn.Open();
string[] selection = new string[] { null, null, table };
DataTable tbl = cn.GetSchema("Columns", selection);
foreach (DataRow row in tbl.Rows)
{
Console.WriteLine(row["COLUMN_NAME"].ToString() + " " +
row["IS_NULLABLE"].ToString() + " " +
row["DATA_TYPE"].ToString()
);
}
}
i was trying to figure this out as well, but with the tables procedure. even though the database and table names are optional, you still have to provide values. for optional parameters, pass in DBNull.Value
this worked for me:
PsqlCommand cm = new PsqlCommand();
cm.CommandText = "psp_tables";
cm.CommandType = CommandType.StoredProcedure;
cm.Connection = new PsqlConnection();
cm.Connection.ConnectionString = <your connection string>;
cm.Parameters.Add(":database_qualifier", DBNull.Value);
cm.Parameters.Add(":table_name", DBNull.Value);
cm.Parameters.Add(":table_type", "User table");
I have multiple SQL databases with the same schema .Say(Database1,Database2....)
How do i dynamically select a database in Entity framework model in runtime?.Since they have the same schema, it does not make sense to import all the data models before hand.
You can change database connection string like this:
DataModelContainer context = new DataModelContainer(
ConnectionOperation.CreateEntityConnection());
And this is CreateEntityConnection Method:
internal static EntityConnection CreateEntityConnection()
{
// Start out by creating the SQL Server connection string
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
// Set the properties for the data source. The IP address network address
sqlBuilder.DataSource = System.Configuration.ConfigurationManager.AppSettings["Connection"];
// The name of the database on the server
sqlBuilder.UserID = "sa";
sqlBuilder.Password = "12345";
sqlBuilder.InitialCatalog = "DatabaseName";
sqlBuilder.IntegratedSecurity = true;
sqlBuilder.MultipleActiveResultSets = true;
// Now create the Entity Framework connection string
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
//Set the provider name.
entityBuilder.Provider = "System.Data.SqlClient";
// Set the provider-specific connection string.
entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
// Set the Metadata location.
entityBuilder.Metadata = #"res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl";
// Create and entity connection
EntityConnection conn = new EntityConnection(entityBuilder.ToString());
return conn;
}