OracleConnection throwing exception - c#

I'm learning how to work with Oracle and am using C#/Visual Studio. Just as a reference, I'm following this simple tutorial, and have all the prerequisites done (database installed and ODAC with dev tools installed). The following code that's supposed to create an object for connection to a database throws an exception saying "Object reference not set to an instance of an object." and points to 'conn' when I try to run the program:
OracleConnection conn = new OracleConnection ();
The same thing happens regardless of whether I pass the connection string as a parameter or not. I have the needed Oracle.DataAccess reference set, so I don't know if I could be missing something else?
The database is installed and works, but that shouldn't have to do anything with this problem.

I remember having difficulties getting the Oracle Data Provider up and running with C# at first too. My tnsnames.ora file exsted in C:\oracleInstallDir\10.2.0\client_1\NETWORK\ADMIN directory.
My tnsnames.ora looked like this:
XE=
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521)))
Make sure that you have the Oracle.DataAccess reference added to your C# project.
Then also make sure that you are
using Oracle.DataAccess.Client;
public class OracleMgr{
public OracleMgr(){
string connectionStr = "Data Source=XE;User Id=user1;Password=abc";
OracleConnection conn = new OracleConnection(connectionStr);
do stuff...
}
}

Related

"Could not find installable ISAM" after adding "IMEX=1" to connection string

I'm trying to open an ADODB connection to an Access 2010 database:
public void openConnection()
{
conn = new ADODB.Connection();
string dbPath = #"T:\somePath\sigilDB.accdb";
string connString=string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"IMEX=1\"",dbPath);
conn.Open(connString);
}
The conn.Open() call gives me the error:
Could not find installable ISAM
This started when I added the Extended Properties=\"IMEX=1\" to the connection string, so that mixed data types in columns will be read as strings. Is there a different way that I need to add this option to the connection string?
As far as I can tell, IMEX simply isn't one of the extended properties for the ACE provider.
In this case, it's not necessary; so far, my testing confirms that mixed data types are handled correctly when queried from Access using ADODB.
EDIT: just spotted Gord Thompson's comment indicating the same.

Mono can't open sqlite database

I'm attempting to do a very basic connection to a sqlite v3 database and I'm using monodevelop 3.0 and Mono 2.10 and am unable to get connected to the database. I can make the app create the database, but then it immediately fails attempting to connect to it. Any suggestions? I had started with a different database, but then decided to have my app attempt to create a database empty and then connect to it. This still seems to fail.
SqliteConnection.CreateFile("db\\DataWorksProg.s3db");
SqliteConnection conn = new SqliteConnection("Data Source=file:db\\DataWorksProg.s3db");
conn.Open();
This small piece of code fails with an error about not being able to open the database file.
Mono.Data.Sqlite.SqliteException: Unable to open the database file
Permissions look OK and I have the Sqlite3.dll in the project, and it seems to be working OK. Have I missed anything obvious? I'm pretty good on the Visual Studio side, but still fairly fresh working in a Mono/Monodevelop environment.
What platform?
I don't believe you need to create a file. If it's not found, iirc, it'll make the database file.
Fwiw, on a Mac, I'm doing (note URI to a pretty standard path; I haven't used Data Source)...
using System;
using System.Data;
using Mono.Data.Sqlite;
namespace test
{
class MainClass
{
public static void Main (string[] args)
{
IDbConnection conTemp = null;
IDbCommand cmdTemp = null;
conTemp = (IDbConnection)new SqliteConnection ("URI=file:/Users/userName/mnmh.db");
conTemp.Open ();
cmdTemp = conTemp.CreateCommand ();
cmdTemp.CommandText = "SELECT * FROM employee";
IDataReader drTemp = cmdTemp.ExecuteReader ();
while (drTemp.Read()) {
Console.WriteLine (drTemp.GetString (0));
}
}
}
}
etc etc
Check the obvious -- you've referenced all the stuff you're using, etc.
Figured out my problem here. Apparently instead of using
"Data Source=file:db\\DataWorksProg.s3db"
I should have been using
"URI=file:db\\DataWorksProg.s3db"
Switched to the URI and it works as expected. I had thought from reading the docs that under the 2.0 profile, the DataSource part was needed instead of the URI, but I got the results I'm looking for.

Object fails to instantiate on Win7 x64

I've searched quite a bit and turned up nothing helpful so here I am.
I have written an app in C# (Any CPU setting) that has been running on Windows 7 and XP x86 for some time now without error.
Recently my office has upgraded my workstation to Windows 7 x64 (from x86).
When I run my application in Visual Studio 2010 I receive no errors at run or compile time. It works as designed.
My VS2010 version is 10.0.30319.1 RTMRel from our MSDN subscription, Framework is 4.0.30319 RTMRel
When I run my compiled application directly I receive an error when with the SqlConnection object. It does not matter if i choose ANY CPU or x86 the same errors occur.
In my class file this is the routine:
public static SqlConnection getDBConnection()
{
SqlConnection sqlConn = null;
try
{
sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["KpH2Oprod"].ConnectionString);
sqlConn.Open();
}
catch
{
throw;
}
finally
{
if (sqlConn == null)
{
sqlConn.Dispose();
}
}
return sqlConn;
}
Some manual tracing I found the error to be thrown not after SqlConnection sqlConn = null; when it's first instantiated but when I actually set it on the line:
sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["KpH2Oprod"].ConnectionString);
I have changed this line to:
sqlConn = new SqlConnection();
sqlConn.ConnectionString = ConfigurationManager.ConnectionStrings["KpH2Oprod"].ConnectionString;
to see if it was the SqlConnection or to Configuration manager and indeed it throws on the sqlConn = new SqlConnection(); line. In fact this was the way I started and changed it to the previous, no matter, both throw error on using the new directive.
The actual error message I get back is (some of which is my own message):
I believe that this might be related to how the SQL object are registered but the message is truncate in the center of the first few lines (not my doing) that point to the parameter g being null. Again this works in the debugger flawlessly.
RunTimeError :
Value cannot be null.
Parameter name: g
at System.Guid..ctor(String g)
at kpH2O.frmMain..ctor() (mscorlib)
ACTION :
UPDATEINCIDENT ()
PROGRESS :
WORKING ()
RunTimeError :
Object reference not set to an instance of an object.
at kpH2O.db.getDBConnection()
at kpH2O.db.getIncidentIDFromNumber(String incidentNumber)
at kpH2O.frmMain.updateHeatIncident() (kpH2O)
ERROR :
Process UPDATEINCIDENT: FAILED (doStartUp)
This is an out of the box VS2010 install without any addons. Any assistance is GREATLY appreciated.
how is the Connection string defined in your .config file for starters..?
would need to see that much
also I would look at defining your sqlConn like this
sqlConn = ConfigurationSettings.AppSettings["connectionString"]; //assuming this is what you named your connection string..
Second I would make use of Try catch {} as well as putting the using (){} within that try
if you do not want to dispose of that sqlConn.. then make it a static property
public static SQLConnection sqlConn = null;
then if you need to use it .. use the new construct within the using() {} as described above..
look at this link as well if you want to Enumerate connection string variables using your original construct ConfigurationSetting and manager
To validate functionality, I would test with a snippet like this. Your current code has a flaw in the disposition logic which is just complicating things.
string connectionString = ConfigurationManager.ConnectionStrings["KpH2Oprod"].ConnectionString;
using( SqlConnection sc = new SqlConnection( connectionString ) )
{
sc.Open();
// perform simple data access
}

SQlite & c#, unable to connect database error

SQLiteConnection conn = new SQLiteConnection("Data Source=/data/bakkal.db3;");
conn.Open();
conn.Close();
I am new at programming so maybe the problem is a very dumb one, sorry for that.
I am trying to connect my project with a database which exists in the directory listed above. But the project gives an error at "conn.Open();" line which is just "unable to connect database". Database has no passwords or etc, it is just a very small database with 2 columns.
I don't think it is going to change anything but my project is a WPF application project, maybe differs.
Thanks for any help
If the database file is located in the same folder as the executable you could try this:
using (var conn = new SQLiteConnection(#"Data Source=|DataDirectory|bakkal.db3"))
{
conn.Open();
}
If it is in a subfolder:
#"|DataDirectory|data\bakkal.db3"
If not use absolute path:
#"c:\somepath\data\bakkal.db3"
Write out the location of the database completely [drive][path][databasefile]
using (SQLiteConnection connection = new SQLiteConnection(#"Data Source=c:\data\bakkal.db3"))
{
connection .Open();
}

How to fix "The ConnectionString property has not been initialized"

When I start my application I get: The ConnectionString property has not been initialized.
Web.config:
<connectionStrings>
<add name="MyDB"
connectionString="Data Source=localhost\sqlexpress;Initial Catalog=mydatabase;User Id=myuser;Password=mypassword;" />
</connectionStrings>
The stack being:
System.Data.SqlClient.SqlConnection.PermissionDemand() +4876643
System.Data.SqlClient.SqlConnectionFactory.PermissionDemand(DbConnection outerConnection) +20
System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +117
System.Data.SqlClient.SqlConnection.Open() +122
I'm fairly new to .NET and I don't get this one. I found a lot of answers on Google, but none really fixed my issue.
What does that mean? Is my web.config bad? Is my function bad? Is my SQL configuration not working correctly (I'm using sqlexpress)?
My main problem here is that I'm not sure where to start to debug this... anything would help.
EDIT:
Failling code:
MySQLHelper.ExecuteNonQuery(
ConfigurationManager.AppSettings["ConnectionString"],
CommandType.Text,
sqlQuery,
sqlParams);
sqlQuery is a query like "select * from table". sqlParams is not relevant here.
The other problem here is that my company uses MySQLHelper, and I have no visibility over it (only have a dll for a helper lib). It has been working fine in other projects, so I'm 99% that the error doesn't come from here.
I guess if there's no way of debuging it without seeing the code I'll have to wait to get in touch with the person who created this helper in order to get the code.
Referencing the connection string should be done as such:
MySQLHelper.ExecuteNonQuery(
ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString,
CommandType.Text,
sqlQuery,
sqlParams);
ConfigurationManager.AppSettings["ConnectionString"] would be looking in the AppSettings for something named ConnectionString, which it would not find. This is why your error message indicated the "ConnectionString" property has not been initialized, because it is looking for an initialized property of AppSettings named ConnectionString.
ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString instructs to look for the connection string named "MyDB".
Here is someone talking about using web.config connection strings
You get this error when a datasource attempts to bind to data but cannot because it cannot find the connection string. In my experience, this is not usually due to an error in the web.config (though I am not 100% sure of this).
If you are programmatically assigning a datasource (such as a SqlDataSource) or creating a query (i.e. using a SqlConnection/SqlCommand combination), make sure you assigned it a ConnectionString.
var connection = new SqlConnection(ConfigurationManager.ConnectionStrings[nameOfString].ConnectionString);
If you are hooking up a databound element to a datasource (i.e. a GridView or ComboBox to a SqlDataSource), make sure the datasource is assigned to one of your connection strings.
Post your code (for the databound element and the web.config to be safe) and we can take a look at it.
EDIT: I think the problem is that you are trying to get the Connection String from the AppSettings area, and programmatically that is not where it exists. Try replacing that with ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString (if ConnectionString is the name of your connection string.)
The connection string is not in AppSettings.
What you're looking for is in:
System.Configuration.ConfigurationManager.ConnectionStrings["MyDB"]...
I stumbled in the same problem while working on a web api Asp Net Core project.
I followed the suggestion to change the reference in my code to:
ConfigurationManager.ConnectionStrings["NameOfTheConnectionString"].ConnectionString
but adding the reference to System.Configuration.dll caused the error "Reference not valid or not supported".
To fix the problem I had to download the package System.Configuration.ConfigurationManager using NuGet (Tools -> Nuget Package-> Manage Nuget packages for the solution)
I found that when I create Sqlconnection = new SqlConnection(),
I forgot to pass my connectionString variable. So that is why I changed the way I initialize my connectionString (and nothing changed).
And if you like me just don't forget to pass your string connection into SqlConnection parameters.
Sqlconnection = new SqlConnection("ConnString")
This what worked for me:
var oSQLConn = new
SqlConnection(
System.Configuration.ConfigurationManager.ConnectionStrings["Conn1"].ToString()
);
If you tried every answer mentioned above then there is the possibility that you are creating a new SQL connection based on the wrong sqlconnection check condition.
Below is the scenario :
The common method to return new SQL connection if it is not previously initialized else will return the existing connection
public SqlConnection GetSqlconnection()
{
try
{
if(sqlConnection!=null)
{
sqlConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
}
return sqlConnection;
}catch(Exception e )
{
WriteLog.WriteErrorLog(log, "GetSqlconnection() | ", e.Message, e.StackTrace);
throw e;
}
// return sqlConnection;
}
//here two methods which are using above GetSqlconnection() method
public void getUser()
{
//call to GetSqlconnection() method to fetch user from db
//connection.open()
//query execution logic will be here
//connection.close() <---here is object state changed --->
}
public void getProduct()
{
//call to GetSqlconnection() method with no connection string properties
//connection.open() ; <--- here exception will be thrown as onnectionstring-property-has-not-been-initialized
//query execution logic will be here .
//connection.close().
}
As soon as you close the connection in getUser() method there will two change in sqlconnection object
1.Status changed from 'Open' to 'Close'
2.ConnectionString property will be change to ""
hence when you call GetSqlconnection() method in getProduct() ,
accroding to if-Condition in GetSqlconnection() ,it will return the existing object of sqlConnection but with status as 'Closed' and ConnectionString as " ".
thus at connection.open() it will throw exception since connectionstring is blank.
To solve this problem while reusing sqlConnection we should check as below in GetSqlconnection() method :
try
{
if(sqlConnection==null || Convert.ToString(sqlConnection.State)=="Closed")
{
sqlConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
}
return sqlConnection;
}catch(Exception e )
{
WriteLog.WriteErrorLog(log, "GetSqlconnection() | ", e.Message, e.StackTrace);
throw e;
}
In my case, I missed a single letter in the word "ConnectionStrings" so it didn't match with the appsettings.json properties thus it gave me this error. An error could not be as deep as you may think. Start debugging by spelling mistakes.
I couldn't fix this exact problem nor have time to investigate, but in my case, it was related to Windows Server 2012 R2 or the framework version. The exact same code, app and config file worked flawlessly on other machines running other Windows versions. Tryed with at least the consumer versions (Windows 8, 10 and 11). Just Windows Server 2012 refused with the error in
System.Data.SqlClient.SqlConnection.PermissionDemand()
IN the startup.cs provide ConnectionStrings
for eg:
services.Configure<Readconfig>(Configuration.GetSection("ConnectionStrings"));
Use [] instead of () as below example.
SqlDataAdapter adapter = new SqlDataAdapter(sql, ConfigurationManager.ConnectionStrings["FADB_ConnectionString"].ConnectionString);
DataTable data = new DataTable();
DataSet ds = new DataSet();

Categories

Resources