Database connection succeeds for non-existent databases - c#

Looks like SQLite database connection doesn't actually try to open database connection when I call Open() function. Here's a simple test:
var factory = DbProviderFactories.GetFactory("System.Data.SQLite");
connection = factory.CreateConnection();
connection.ConnectionString = "data source=NonExistentDB.db3";
conn.Open();
The above code does not generate any kind of exception. Moreover, the connection state is Open after this. Is there a way to do "Test Connection" that would physically establish a connection with the database?

Change to
connection.ConnectionString = "data source=NonExistentDB.db3;FailIfMissing=True"
Without the last argument, it will simply create a new database if the file is not found.

Related

System.Data.SqlClient.SqlConnection unexpected result in Open() Method with incomplete ConnectionString

When calling the Open() method on a SqlConnection instance that got passed an incomplete connection string, the method does not throw an exception.
I have created the following example to showcase my problem.
var success = true;
var connectionStrings = new[]
{
"Integrated Security=SSPI;",
"Initial Catalog=awdemo;Integrated Security=SSPI;",
"Data Source=.\\sql2016;Initial Catalog=awdemo;Integrated Security=SSPI;"
};
foreach (var connectionString in connectionStrings)
{
var conn = new SqlConnection(connectionString);
try
{
conn.Open();
}
catch (Exception)
{
success = false;
}
finally
{
conn.Close();
Console.WriteLine($"{connectionString} - Success = {success}");
}
}
Result:
Integrated Security=SSPI; - Success = True
Initial Catalog=awdemo;Integrated Security=SSPI; - Success = True
Data Source=.\sql2016;Initial Catalog=awdemo;Integrated Security=SSPI; - Success = True
I would expect conn.Open() to throw an exception for the first two connection strings, since both of them are incomplete and not valid.
Why is there no exception thrown?
EDIT: as pointed out by Steve in the comments an exception is not thrown because the component connects to my default instance of SQL Server when not providing the server information.
Is there a way to force the SqlConnection component to throw an error on incomplete connection strings? In the application it is possible and allowed to create incomplete connection strings.
There's no practical way to fully validate this. You could have a connection string that has all of the components you expect, including a valid server and database name, but it's the wrong server or wrong database.
So if the expectation is that the class should fail on conn.Open() if the connection string is incorrect (not invalid, but incorrect), you can't completely achieve that.
Does it matter? Imagine a few scenarios, all of which include incorrect connection strings:
The connection string is "blarg!" and so attempting to open the connection throws an exception.
The connection string doesn't contain a server or database name. You can open the connection but when you try to execute some command it fails.
The connection string contains a server and database name, but it's the wrong server or database. It fails for the same reason as 2.
In each of the scenarios, what's the first thing you're going to do? You're going to look at the exception. Regardless of which line throws it, you're going to quickly deduce that you have the wrong connection string.
So a "validation" which can't actually validate the connection string before you open it is just going to add work. If the connection string is wrong, that truly is an "exceptional" condition so it's probably better to just let the code throw an exception where it does. You'll find the problem quickly.
All of that aside, suppose you just really want to be sure that your connection contains a server name and a database name before you try to open it. You could write an extension method like this:
// Maybe give it a better name.
public static void ValidateThatConnectionHasDataSourceAndDatabase(this SqlConnection connection)
{
if (string.IsNullOrEmpty(connection.DataSource))
throw new Exception("The connection has no datasource");
if (string.IsNullOrEmpty(connection.Database))
throw new Exception("The connection has no database");
}
After you create the connection and before you open it, call conn.ValidateThatConnectionHasDataSourceAndDatabase();

Sqlite database is accessible even with a wrong password

In the following code for a C#.Net windows/desktop application, I have given wrong password while connecting to database but message box still displays Open.
SQLiteConnection conn = new SQLiteConnection("Data Source=DMB.sqlite;Version=3;");
conn.SetPassword("password");
conn.Open();
conn.Close();
conn = new SQLiteConnection("Data Source=DMB.sqlite;Version=3;Password=cdssss;");
conn.Open();
MessageBox.Show(conn.State.ToString());
Why it is still open when password is wrong?
This behavior is by design in the .net sqlite driver:
This is by design. The error message only occurs when you try to read from -OR-
write to the underlying database file. Opening the database does not typically
perform either operation.
It is recommended that you execute a SELECT statement on some well-known table
(e.g. "sqlite_master") immediately after opening the database in order to
determine if it is in a usable state.
Cited from Ticket 3eb097e917a7740f3499aae66e9a3cd021e9f81c:
https://system.data.sqlite.org/index.html/tktview/3eb097e917a7740f3499

SSIS Script task AcquireConnection returns Null

In SSIS I have a connection defined with the following connection string:
Data Source=myserver;Initial Catalog=Spears;Provider=SQLNCLI11.1;Integrated Security=SSPI;Auto Translate=False;
i am attempting to use this connection from a script task:
ConnectionManager connectionManager = this.Dts.Connections["Spears"];
object acquireConnection = connectionManager.AcquireConnection(this.Dts.Transaction);
SqlConnection con = acquireConnection as SqlConnection;
con.Open();
On execution
connectionManager comes back as a fully populated ConnectionManager
object
acquireConnection is a System._ComObject
con is null
obviously opening con fails
Casting as OleDbConnection or OdbcConnection returns null as well.
What am I doing wrong ?
This problem occurs because you are using an OLEDB connection in the SSIS package instead of an ADO.NET one.
Once you change that, the code should work fine, even if Dts.Transaction is null.
There are a couple of issues. First, you have not instantiated new SqlConnection object as in SqlConnection con = new SqlConnection();
Second, unless the container is set to participate in a transaction, Dts.Transaction will be null and so the cast to a SqlConnection will be null. Transactions are supported by default, but unless a parent container starts it, there will be no shared transaction. This makes the examples from MS a little misleading.
I suggest going with the following. Supposing your connection manager is an OleDb connection, the add System.Data.Oledb to the usings:
OleDbConnection conn = new OleDbConnection(Dts.Connections[".\\sql2016.SSISAuditDB"].ConnectionString);
using (conn)
{
conn.Open();
OleDbCommand cmd = new OleDbCommand("SELECT 1", conn);
int val = (int)cmd.ExecuteScalar();
MessageBox.Show(val.ToString());
}
In the above code, we just grab the connection string from our connection manager and then create a new connection from it. Note that OleDbConnection implements IDisposable, so it can be wrapped in a using() block and it does not need to be explicitly closed. This is a good practice, because it means you will not need to have extra handling for closing the connection, for example if you added a catch block.
m
You're using SQLNCLI11.1 Provider with SqlConnection object. Change your DTS connection, use "ADO.NET Connection" and try it.

Connect to online MySQL database in C# desktop application

I have a problem with connecting to the database.
private static readonly string s_connectionString = "Server=db.inu.hu; Database=patientRegistry;UID=****; Password=****; Port=3306; Trusted_Connection=true";
That's my connection string and with this I can't open the connection.
using (SQLiteConnection conn = new SQLiteConnection(s_connectionString))
{
conn.Open();
}
I thought the problem might be that I have a table in the database and need to add that to the connection string.
Are you trying to connect to MySQL or SQLite? You are referencing a SQLiteConnection object, but I think you need to be using a MySqlConnection connection object instead.

Creating an SQL Server connection string without importing a datasource in C#

I am going off of this tutorial: http://www.dotnetperls.com/sqlclient . Instead of adding a data source and a having visual studio compile my connecting string - I want to do it myself. The reason being is that the database will not always be the same and I want this application to be able to use different databases depending on which I point it to.
So how can I manually create the connection string? I am using SQL Server 2005.
Step 1: Go to connectionstrings.com and find the proper format for your database.
Step 2: Plug in the appropriate values to the connection string.
Step 3: Pass that string to the constructor of SqlConnection.
I would also suggest storing your connection string in your app.config/web.config file. You can then modify them easily if needed. The proper format can be found at MSDN - connectionStrings element. You then change your code to:
SqlConnection sqlConn = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnStringName"].ConnectionString);
I don't see where the connection string is "compiled".
In the code
SqlConnection con = new SqlConnection(
ConsoleApplication1.Properties.Settings.Default.masterConnectionString)
ConsoleApplication1.Properties.Settings.Default.masterConnectionString is a field and it can be replaced with any other appropriate string.
for SQL Server format of the connection string is
"Data Source = server_address; Initial Catalog = database_name; User ID = UserId; Password = **;"
save this connection string in a string variable and use with connection object.
either way you can add in web.config file.
<ConnectionString>
<add name = "name_of_connecctionString" ConnectionString = "Data Source = server_address; Initial Catalog = database_name; User ID = UserId; Password = ****;" ProviderName = "system.Data.SqlClient"/>
</ConnectionString>
you can change the provider as needed by you.
then in code behind file access this particular connection string using configuration manager.

Categories