I'm trying to connect to remote Oracle server. My connection string -
OdbcConnection con = new OdbcConnection();
con.ConnectionString = #"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST= xxxx)(PORT=xxxxx))(CONNECT_DATA=(SERVER=dedicated)(SERVICE_NAME=abc.domain.com)));USER ID=user1;Password=pwd;";
I encountered error saying - "ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified" (System.Data.Odbc.OdbcException) Exception Message = "ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified", Exception Type = "System.Data.Odbc.OdbcException", Exception WinRT Data = ""
I specified my connection string according to my TNSNAMES.ora
Entry for my DB in TNSNAMES.ora goes like this:
DB.WORLD=
(DESCRIPTION=
(ADDRESS=
(PROTOCOL=TCP)
(HOST= xxxx)
(PORT=xxxxx)
)
(CONNECT_DATA=
(SERVER=dedicated)
(SERVICE_NAME=abc.domain.com)
)
)
Can someone explain on the error. Please help/suggest if my connection string went wrong and how to connect to Oracle server from my windows application
first install odp.net.managed using nuget packet manager:
Install-Package odp.net.managed
odp.net.managed work without preinstalled Oracle Client
next:
const string connectionString = #"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST= xxxx)(PORT=xxxxx))(CONNECT_DATA=(SERVER=dedicated)(SERVICE_NAME=abc.domain.com)));USER ID=user1;Password=pwd;";
var connection = new OracleConnection(connectionString);
connection.Open();
if you have tnsnames.ora in application folder:
const string connectionString = #"Data Source=DB.WORLD;USER ID=user1;Password=pwd;";
var connection = new OracleConnection(connectionString);
connection.Open();
or if tnsnames.ora in other folder:
Environment.SetEnvironmentVariable("TNS_ADMIN", #"path_to_tnsadmin.ora");
const string connectionString = #"Data Source=DB.WORLD;USER ID=user1;Password=pwd;";
var connection = new OracleConnection(connectionString);
connection.Open();
you need to use OracleConnection
OracleConnection conn = new OracleConnection(connectionString);
download and install Oracle Data Provider for .NET
Go to Connections Strings for Oracle
Maybe will find some help
Use following Code:
using System;
using Oracle.DataAccess.Client;
class ConnectionSample
{
static void Main()
{
OracleConnection con = new OracleConnection();
//using connection string attributes to connect to Oracle Database
con.ConnectionString = "User Id=scott;Password=tiger;Data Source=oracle";
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
// Close and Dispose OracleConnection object
con.Close();
con.Dispose();
Console.WriteLine("Disconnected");
}
}
Source ONE , TWO and THREE
Try something like this class :
public class OracleOperations
{
OracleConnection oraConn = new OracleConnection();
private bool connStatus;
public OracleOperations()
{
connStatus = false;
connect();
}
~OracleOperations()
{
disconnect();
}
public bool getConnStatus()
{
return connStatus;
}
public void connect()
{
string connString = "User Id=xxxx; Password=yyyyy; Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=10.10.10.10)(PORT=1583))(CONNECT_DATA=(SERVER=dedicated)(SID=oracledb)))";
if (oraConn.State != ConnectionState.Open)
{
try
{
oraConn.ConnectionString = connString;
oraConn.Open();
Console.WriteLine("Successful Connection");
connStatus = true;
}
catch (Exception eOra)
{
Console.WriteLine(eOra.Message+ "Exception Caught");
connStatus = false;
throw eOra;
}
}
}
public void disconnect()
{
if (oraConn.State == ConnectionState.Open)
{
try
{
oraConn.Close();
connStatus = false;
Console.WriteLine("Connection Closed");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "Exception Caught");
}
}
}
}
I would try Tnsping utility to make sure you can connect via tnsnames.ora
Try putting tnsnames.ora and sqlnet.ora in the same folder of the application and see if that addresses the issue.
With Managed ODP.Net there is one catch it does not support LDAP look up (e.g. LDAP.ora)
I'Ve Created an app.config File and configured the DB entry like this
<configuration>
<configSections>
<section name ="Environment" type="System.Configuration.NameValueSectionHandler" />
</configSections>
<Environment>
<add key ="CIT" value ="Password=pwd123;User ID=abc123;Data Source=db1;Persist Security Info=True;Provider=MSDAORA"/>
<add key ="SIT" value ="Password=pwd234;User ID=abc234;Data Source=db2;Persist Security Info=True;Provider=MSDAORA"/>
<add key ="UAT" value ="Password=pwd345;User ID=abc345;Data Source=db3;Persist Security Info=True;Provider=MSDAORA"/>
</Environment>
</configuration>
Reffered that configuration into my form using ConfigurationManager(Need to refer the assembly - system.configuration). Add namespace - using System.Collections.Specialized to avail NameValueCollection. Code goes like this
environments = ConfigurationManager.GetSection("Environment") as NameValueCollection;
string strConnString = environments[envs];
conn = new OleDbConnection(strConnString);
conn.Open();
OleDbDataAdapter objDa = new OleDbDataAdapter("select * from tblABC", conn);
DataSet ds1 = new DataSet();
objDa.Fill(ds1); dataGridView1.DataSource = ds1.Tables[0];
Using datset, i've populated datagrid using an OleDbDataAdapter. It worked for my Windowsapplication.
Related
I am getting a System.AccessViolationException error when trying to use the .Open() method on my OleDbConnection variable. But, confoundingly, it doesn't seem to happen when I run my code on a different computer.
My code is for a service that I want running on a server. It appears to work correctly when I run it on my personal computer, but it throws the AccessViolationException error when I try running it on the server.
Code Versions:
I am writing in C# using Visual Studios 2019 on Windows 10
OleDbConnection is from "Assembly System.Data, Version=4.0.0.0"
ADOX is from "Assembly Interop.ADOX, Version=2.8.0.0", System.Runtime.InteropServices
ADODB is from "Assembly Interop.ADODB, Version=2.8.0.0", System.Runtime.InteropServices
My code:
internal static bool CreateMDB(MySchemaClass schema, string filePath)
{
OleDbConnection conn = null;
bool status = true;
string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}", filePath);
try
{
// Setup new file
catalog.Create(connectionString);
((ADODB.Connection)catalog.ActiveConnection).Close();
conn = new OleDbConnection(connectionString);
conn.Open(); // <-- Error occurs here
// Write to new file
WriteDataToFile(schema, conn);
}
catch (Exception ex)
{
status = false;
}
finally
{
if (conn != null)
conn.Close();
}
return status;
}
StackTrace:
The best lead I have found so far is this post, but I'm a bit hazy about how to proceed from that starting point.
To programmatically create an Access database do the following:
Add reference to Microsoft ADO Ext. 6.0 for DDL and Security
In VS menu, click Project
Select Add Reference
Click COM
Check Microsoft ADO Ext. 6.0 for DDL and Security
CreateAccessDatabase
public static string CreateAccessDatabase(string fullyQualifiedAccessFilename, string dbPassword = "")
{
string connectionString = String.Format(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0}", fullyQualifiedAccessFilename);
if (String.IsNullOrEmpty(fullyQualifiedAccessFilename))
{
throw new Exception("Error (CreateAccessDatabase) - Database filename is null or empty.");
}
if (!String.IsNullOrEmpty(dbPassword))
{
connectionString = String.Format(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0};Jet OLEDB:Database Password='{1}'", fullyQualifiedAccessFilename, dbPassword);
}
//create new instance
ADOX.Catalog cat = new ADOX.Catalog();
//create Access database
cat.Create(connectionString);
//close connection
cat.ActiveConnection.Close();
//release COM object
System.Runtime.InteropServices.Marshal.ReleaseComObject(cat);
GC.Collect();
cat = null;
return String.Format("Database created '{0}'", fullyQualifiedAccessFilename);
}
Usage:
string result = string.Empty;
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Access Database 2000-2003 (*.mdb)|*.mdb|Access Database 2007 (*.accdb)|*.accdb";
if (sfd.ShowDialog() == DialogResult.OK)
{
//create Access database
result = CreateAccessDatabase(sfd.FileName);
}
To programmatically create a table in an Access database:
Add using statement:
using System.Data.OleDb;
CreateTableProduct:
public static int CreateTableProduct(string fullyQualifiedAccessFilename, string dbPassword = "")
{
int result = 0;
string connectionString = String.Format(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0}", fullyQualifiedAccessFilename);
if (!String.IsNullOrEmpty(dbPassword))
{
connectionString = String.Format(#"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = {0};Jet OLEDB:Database Password='{1}'", fullyQualifiedAccessFilename, dbPassword);
}
string sqlText = string.Empty;
sqlText = "CREATE TABLE Product ";
sqlText += "(ID AUTOINCREMENT not null primary key,";
sqlText += " Name varchar(50) not null,";
sqlText += " Price currency, Quantity integer);";
using (OleDbConnection con = new OleDbConnection(connectionString))
{
//open connection
con.Open();
using (OleDbCommand sqlCmd = new OleDbCommand(sqlText, con))
{
//execute command
result = sqlCmd.ExecuteNonQuery();
}
}
return result;
}
Resources:
ADO Features for each Release
Which Access file format should I use?
CREATE TABLE statement (Microsoft Access SQL)
System.Data.OleDb Namespace
The underwhelming answer to the problem is that my server was lacking some of the files my personal computer had, and only needed the correct files installed.
The missing piece in this case was the Microsoft Access Database Engine 2016 Redistributable, which I ended up finding here. Running that executable on my server got the needed files and everything worked after that.
To initialize the connection string, it needs to be a static string. Why that happens?
using System.Data.SqlClient;
namespace CDemoLib
{
public class Connecting
{
static string conString = #"connection string here";
Also when I am trying to open a connection using the conn.Open()am getting an error saying that
The name conn.Open() does not exist in the current context
Why that error occurs ?
using System.Data.SqlClient;
namespace CDemoLib
{
public class Connecting
{
static string conString = #"connection string here";
SqlConnection conn = new SqlConnection(conString);
conn.Open();
I have anwsered this question but i will replay it for you.
(Connection String Is not Working Object instance reference is null)
Put your connection string at you web.config as the foloow example:
<add name="MovieDB"
connectionString="Data Source=LocalDb)\MSSQLLocalDB;Initial Catalog=aspnet- MvcMovie;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Movies.mdf"
providerName="System.Data.SqlClient"/>
to read it within your code:
System.Configuration.Configuration rootWebConfig =System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/MyWebSiteRoot");
System.Configuration.ConnectionStringSettings connString;
if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
{
connString =
rootWebConfig.ConnectionStrings.ConnectionStrings["MovieDB"];
if (connString != null)
Console.WriteLine("MovieDB connection string = \"{0}\"",
connString.ConnectionString);
else
Console.WriteLine("No MovieDB connection string");
}
The name at your web.config tag 'name'
<add name="MovieDB".....
has to be the same one from your c# code:
connString = rootWebConfig.ConnectionStrings.ConnectionStrings["MovieDB"]
from: https://msdn.microsoft.com/en-us/library/ms178411.aspx
Here a method to open it:
private static void OpenSqlConnection(string connString)
{
using (SqlConnection connection = new SqlConnection(connString))
{
connection.Open();
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
}
}
from: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open(v=vs.110).aspx
DonĀ“t forget to secure your connection string at your web.config. Please, read this: https://msdn.microsoft.com/en-us/library/ms178372.aspx
After installing Oracle 12c Release 2, I am running into some problems with database and transaction handling. The version of the ODP.NET dll (Oracle.DataAccess.dll) is 4.122.1.0, and I am using a PC with Windows 7 Professional.
I am no longer able to use the OracleConnection.State property to monitor the state of a connection, which breaks existing code.
It seems that simply accessing the State property corrupts the OracleConnection object, but only when using IPC connections. Below is a code example that reproduces the problem. The database in this example is run on my local system.
private const string ConnectionStringIPC = #"Data Source=(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = IPC)(Key = EXTPROC1521))) (CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = GLOBAL)));User Id=TestCase;Password=TestCase;Validate Connection=true;";
private const string ConnectionStringTCP = #"Data Source=(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))) (CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = GLOBAL)));User Id=TestCase;Password=TestCase;Validate Connection=true;";
static void Main(string[] args)
{
Console.WriteLine("IPC:");
TestCase1(ConnectionStringIPC);
TestCase2(ConnectionStringIPC);
Console.WriteLine("TCP:");
TestCase1(ConnectionStringTCP);
TestCase2(ConnectionStringTCP);
}
private static void TestCase1(string connectionString)
{
try
{
OracleConnection conn = new OracleConnection(connectionString);
conn.Open();
OracleTransaction trans = conn.BeginTransaction();
Console.WriteLine("TestCase1 succesful!");
}
catch(Exception e)
{
Console.WriteLine("TestCase1 failed:");
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
}
private static void TestCase2(string connectionString)
{
try
{
OracleConnection conn = new OracleConnection(connectionString);
conn.Open();
var state = conn.State;
OracleTransaction trans = conn.BeginTransaction();
Console.WriteLine("TestCase2 succesful!");
}
catch (Exception e)
{
Console.WriteLine("TestCase2 failed:");
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
}
The output of this program is
IPC:
TestCase1 succesful!
TestCase2 failed:
Object reference not set to an instance of an object.
at Oracle.DataAccess.Client.OracleConnection.get_TxnHndAllocated()
at Oracle.DataAccess.Client.OracleConnection.BeginTransaction()
at OracleConnectionTest.Program.TestCase2(String connectionString)
TCP:
TestCase1 succesful!
TestCase2 succesful!
As you can see, simply accessing the OracleConnection.State property is enough to invalidate the object, triggering an exception in the subsequent OracleTransaction.BeginTransaction call.
Is there anything wrong with the way I try to use the OracleConnection and OracleTransaction objects?
If not, is this a known bug, and is there any good work-around?
Hi I'm new when it comes to connecting to a server/database and was wondering why this returns an error.
I have a FastHost server with a database.
I've just put in an example IP but i have been using the one given on my control panel on the site.
private void SQLTest_Click(object sender, RoutedEventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source = 123.456.789.012" +
"Initial Catalog = DiscoverThePlanet" +
"User ID = TestUser" +
"Password = Test";
try
{
conn.Open();
MessageBox.Show("Connection Established!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open Connection!");
}
}
This returns the
Can not open Connection!" message.
I get the following show in my code:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: A network-related or instance-specific error occurred while establishing a connection 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
I know my server is fine because i have connected to it on SQL Server Management studio and added tables and data.
You're missing a couple of ;
conn.ConnectionString =
"Data Source = 123.456.789.012" +
";Initial Catalog = DiscoverThePlanet" +
";User ID = TestUser" +
";Password = Test";
An even better solution is to use ConnectionStringBuilder.
System.Data.SqlClient.SqlConnectionStringBuilder builder =
new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = "123.456.789.012";
builder["Initial Catalog"] = "DiscoverThePlanet";
builder["User ID"] = "TestUser";
builder["Password"] = "Test";
Console.WriteLine(builder.ConnectionString);
Or (as #Fischermaen mentioned) you can use the properties, instead of indexes. It's even more readable!
builder.DataSource = "123.456.789.012";
builder.InitialCatalog = "DiscoverThePlanet";
builder.UserID = "TestUser";
builder.Password = "Test";
Also, in this scenario you aren't using any user input, but beware of connection string injection when manually creating your connection string. ConnectionStringBuilder can help you avoid those.
A connection string injection attack can occur when dynamic string
concatenation is used to build connection strings that are based on
user input. If the string is not validated and malicious text or
characters not escaped, an attacker can potentially access sensitive
data or other resources on the server. For example, an attacker could
mount an attack by supplying a semicolon and appending an additional
value. The connection string is parsed by using a "last one wins"
algorithm, and the hostile input is substituted for a legitimate
value.
The connection string builder classes are designed to eliminate
guesswork and protect against syntax errors and security
vulnerabilities. They provide methods and properties corresponding to
the known key/value pairs permitted by each data provider. Each class
maintains a fixed collection of synonyms and can translate from a
synonym to the corresponding well-known key name. Checks are performed
for valid key/value pairs and an invalid pair throws an exception. In
addition, injected values are handled in a safe manner.
A last (and, in my opinion, best) alternative is to move your connectionstring from code into a config. This will make it much easier for you to use the same code in different environments.
conn.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString];
And your config.
<connectionStrings>
<add name="MyConnectionString" connectionString="[ConnectionString goes here]" providerName="System.Data.SqlClient" />
</connectionStrings>
Add a semicolon after each part of your connection string code:
private void SQLTest_Click(object sender, RoutedEventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source = 123.456.789.012;" +
"Initial Catalog = DiscoverThePlanet;" +
"User ID = TestUser;" +
"Password = Test";
try
{
conn.Open();
MessageBox.Show("Connection Established!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open Connection!");
}
}
https://www.connectionstrings.com/sql-server/ should tell you more about the correct format.
Your connectionstring is not well formated, you forgot some ; :
"Data Source = 123.456.789.012;Initial Catalog = DiscoverThePlanet;User ID = TestUser;Password = Test"
An example :
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
https://www.connectionstrings.com/sql-server/
There are some ';' missing. Try this:
conn.ConnectionString =
"Data Source = 123.456.789.012;" +
"Initial Catalog = DiscoverThePlanet;" +
"User ID = TestUser;" +
"Password = Test;";
Use StringBuilder if you wants to write ConnectionString like mention,
String object it will occupy memory each time.
StringBuilder will occupy memory only once, so it will give you better performance.
SqlConnection conn = new SqlConnection();
StringBuilder sb=new StringBuilder();
sb.Append("Data Source = 123.456.789.012;");
sb.Append("Initial Catalog = DiscoverThePlanet;");
sb.Append("User ID = TestUser;");
sb.Append("Password = Test;");
conn.ConnectionString =sb.ToString();
try
{
conn.Open();
MessageBox.Show("Connection Established!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open Connection!");
}
Semi Column is missing in the Connection String. So correct it
private void SQLTest_Click(object sender, RoutedEventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source = 123.456.789.012;" +
"Initial Catalog = DiscoverThePlanet;" +
"User ID = TestUser;" +
"Password = Test;";
try
{
conn.Open();
MessageBox.Show("Connection Established!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open Connection!");
}
}
i have a problem with this c# code. I need to connect it to mysql, localhost database, Please give me the correct code to [connetionString = "Data Source=ServerName;Initial Catalog=root;User ID=root;Password="; ] connect to the localhost.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn ;
**connetionString = "Data Source=ServerName;Initial Catalog=localhost;User ID=root;Password=";**
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
It should look a little more like this:
connetionString = "Data Source=localhost;Initial Catalog=<Name of the Database>;User ID=root;Password=";
The data source property is where you put the network location, the initial catalog is the name of the database (in mysql).
Edit:
However, I believe you'll need the mysql libraries, which I notice you're not using at the beginning.
Get them from here: http://dev.mysql.com/downloads/connector/net/
The Data.SqlClient namespace is typically how you'd connect to MSSQL.
it seems you have tagged MySql connection, so preferably you want to use the mysql connection. Which you can download / install here: http://dev.mysql.com/downloads/connector/net/
Also it is wise to use the try-catch-finally approach. So that when the connection opens, and some exception occurs, the connection will always close afterwards.
As another addition, you could put the connectionstring in an App.Config or Web.Config so that you have the connectionstring available in all your files, and only have to adjust it in one place.
hope this will help you
using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient; //using the mysql dll
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=localhost;Initial Catalog=myDb;User ID=MyUser;Password=MyPass";
MySqlConnection cnn = new MySqlConnection(connectionString);
try
{
cnn.Open();
MessageBox.Show("Connection Open ! ");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
MessageBox.Show(ex.Message); //shows what error actually occurs
}
finally
{
cnn.Close();
}
}
}
}
You are using System.Data.SqlClient in your connection which I think used for SQL Server. Your connection string is also not for MySQL Database. Try this one.
using System.Data.Odbc;
string connectionString = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER=localhost;
DATABASE=dbname; UID=myuserid; PASSWORD=mypassword;OPTION=3; POOLING=false;";
OdbcConnection DBCon = new OdbcConnection(connectionString);
if (DBCon.State == ConnectionState.Open)
{
DBCon.Close();
}
DBCon.Open();
MessageBox.Show ("Connection Open ! ");
DBCon.Close();
Change the ODBC Driver version depending on what you are using.
Change the DATABASE, UID and PASSWORD value.
Here is the code you need
private void btnConnect_Click(object sender, EventArgs e)
{
string MyConStr = "Server=localhost;Database=YourDB;Username=YourUsername;Password=YourPassword";
MySqlConnection conn = new MySqlConnection(MyConStr);
conn.Open();
if (conn.State == ConnectionState.Open)
{
MessageBox.Show("Connection Opened Successfully");
conn.Close();
}
else
{
MessageBox.Show("Error Connecting to DataBase");
}
}