Error Opening Access Database with C# Application - c#

I'm updating a C# (.NET 3.5) application to interact with an Access database, but I keep getting this error:
ERROR: Unrecognized database format
This is the code I'm using to open a connection to the database:
String connectionString = "Provider=Microsoft.Jet.OLEDB.4.0; " +
"Data Source=" + filePath;
try
{
this.conn = new OleDbConnection(connectionString);
this.conn.Open();
}
catch (Exception e)
{
Console.WriteLine("ERROR: " + e.Message);
Console.WriteLine(e.ToString());
}
I know that the file path is correct. I suspect that the Provider=Microsoft.Jet.OLEDB.4.0; is incorrect. How do I find out what the database format is? I did not make the database in question, but I do have read-access to it. Thanks.

You must add Data Source , user/password parametters . You can see http://connectionstrings.com/access

Related

failed to connect to database using c#

I want to ask about connecting db with c#.
I have read http://csharp.net-informations.com/data-providers/csharp-sql-server-connection.htm and written my code, but the connection doesn't seem to be working.
This is my code:
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
SqlDataReader dataReader;
connetionString = "Data Source=localhost;Initial Catalog=dbabc;User ID=admin;Password=qwerty";
sql = "UPDATE ppd,brg,cmp SET WHERE";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
MessageBox.Show(dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + " - " + dataReader.GetValue(2));
}
dataReader.Close();
command.Dispose();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
Did I write something wrong? The error message shown always says "Can not open connection"!
The Exception thrown should be a SqlException. Check the ErrorCode on the SqlException and look it up here...
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-develop-error-messages
Rather than catch(Exception ex) your code should do this...
try
{
connection.Open();
....
connection.Close();
}
catch (SqlException ex)
{
MessageBox.Show($"Can not open connection ! ErrorCode: {ex.ErrorCode} Error: {ex.Message}");
}
catch (Exception ex)
{
MessageBox.Show($"Can not open connection ! Error: {ex.Message}");
}
I think you should check server name
if you install SQL server (Standard) on your computer, server name named is (local) or .
If you are using VS create a data source and test the connection string. Go to data> Add new data source. There is find your database server and create the correct string.
Your code is working. I can verify it. Please check your connection string and SQL query. Especially your SQL query. It seems to be wrong.
Try to execute the query in Microsoft SQL Server Management Studio. If there is an error in your query, you can easily find it there.
SQL Update Syntax
UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];
Recommended Readings
https://www.tutorialspoint.com/sql/sql-update-query.htm
https://www.w3schools.com/sql/sql_update.asp
To verify the connection string,
Open the Server Explorer pane. ("View" menu, "Server Explorer" or
use the key shortcut CTRL+Alt+S).
Right-click on the Data Connections, Select Add connection and then
press continue after selecting Microsft SQL Server as the Data source.
Select Refresh and click down arrow and then select your SQL server.
If you cannot find it, enter the server name manually.
You may also have to enter the SQL server credentials.
Select or enter your database name & then press Test Connection.
If you see a Test connection succeeded message, then your SQL server is working.
If you want, you can also get connection string by pressing Advanced.. button and then copying the connection string
In addition, try to an add exception message to catch block. That way, you can easily find the error.
MessageBox.Show("Can not open connection ! \n" + ex.Message);

WPF, What's the best way to store a constant to be used at startup?

I have a WPF application that accesses a database instance. I develop on my personal machine and the application will run on another machine and database instance. Is there a way or best practice for storing the instance name outside of the WPF application that I can read upon app startup? Currently I have comment and uncomment the database instance name as I move from machine to machine. I would like to have something stored on the local machine that I can just read when the application is launched.
Here is what I currently do:
try
{
if (sqlConn != null)
{
sqlConn.Close();
}
strConnection = "Data Source=" + strDBInstance + "; Initial Catalog=NBFoodPantry;Integrated Security=true; MultipleActiveResultSets = True";
//strConnection = "Data Source=CASS-LAPTOP\\SQLEXPRESS; Initial Catalog=NBFoodPantry;Integrated Security=true; MultipleActiveResultSets = True";
//strConnection = "Data Source=KENTS-WORK-PC\\CASS_SQLEXPRESS; Initial Catalog=NBFoodPantry;Integrated Security=true; MultipleActiveResultSets = True";
sqlConn = new SqlConnection(#strConnection);
try
{
sqlConn.Open();
}
catch (Exception ex)
{
string strMsg;
WriteErrorLog(strErrorLogFile, "ConnectToDatabase", ex.Message, false);
strMsg = "ConnectToDatabase: SQL Open failed. Please make sure that you database ";
strMsg += "instance and name are correct. Also make sure that the SQL engine is running.";
System.Windows.MessageBox.Show(strMsg);
}
}
catch (Exception ex)
{
string strMsg;
WriteErrorLog(strErrorLogFile, "ConnectToDatabase", ex.Message, false);
strMsg = " ConnectToDatabase: failed with error, " + ex.Message + ".";
System.Windows.MessageBox.Show(strMsg);
}
This is what application settings are designed to handle. Under the properties node in your project, open the settings. This has built in support for connection strings:
Then you can access the settings in your code by its name:
Properties.Settings.Default.ConnectionString
All of this is stored in your App.config, which you can modify on various machines to have different values.

SQL Server Compact edition 3.5 database acess is denied

I have developed a desktop application in C# with Microsoft SQL Server Compact Edition 3.5.
It works fine when I run .exe file from solution folder (bin\release or debug) but when I tried to deploy it by creating its setup it shows unhandled exception:
You don't have permission to access CustomersDB.sdf file.
Note there is no path error it is correct.
string lokasifile = Environment.CurrentDirectory + "\\CustomersDB.sdf";
string stringkoneksi = "Data Source = \"" + lokasifile + "\"";
SqlCeConnection koneksi = new SqlCeConnection(stringkoneksi);
koneksi.Open();
SecurityException
This is nothing but caller does not have the appropriate permission.
Environment.CurrentDirectory Property
try
{
//Call Path here you will get to what the exactly error is
}
catch (Exception ex)
{
if (ex is DirectoryNotFoundException|| ex is IOException|| ex is SecurityException)
{
//Your handling here
}
else
{
throw;
}
}

Connect C# to Mysql database

I want to connect to mysql server from C#. I found some code on the net but somewhere there is something wrong because i get
A first chance exception of type 'System.ArgumentException' occurred in System.Data.dll
error.
private void Initialise()
{
server = "dns to server";
database = "db_name";
uid = "root";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" +
uid + ";" + "PASSWORD=" + password + ";";
OR
connectionString = "Server=xxx.no-ip.org;Database=rdb;"+
"Uid=root;Pwd=wHt2%Zt;";
connection = new MySqlConnection(connectionString);
if (this.OpenConnection() == true)
Console.Out.Write("SUCCESS");
else
Console.Out.Write("ERROR");
}
private bool OpenConnection() {
try {
connection.Open();
return true;
}
catch (MySqlException ex){
switch (ex.Number) {
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
I don't get any message on the console. I added Mysql.Data as a reference to my project and i used using MySql.Data.MySqlClient;
I also tried connectig through gui but with no luck. Ideas ?
Edit 1 : with either connection string my program is still not working.
Edit 2 : OpenConnection method added.
Edit 3 : This is the error i get !
p.s.
http://www.connectionstrings.com/mysql
probably you need to change your approach...use a webconfig or app config to setup and read your connectionstrings from the config...
I would also recommend you to read this...
http://www.codeproject.com/Articles/12300/An-ASP-NET-Application-Using-a-MySQL-Database
UPDATE
Based on your updated findings...there can be two problems, first double check your connectionstring, Second is to check if the user "root" has the required permissions.
Look here: http://www.connectionstrings.com/mysql
Have all.
Server=myServerAddress;Port=1234;Database=myDataBase;Uid=myUsername;Pwd=myPassword;
I think the problem is your database server:
Server=xxx.no-ip.org
It seems your app doesn't find the server. Check firewall.
You can debug and set an interruption point and check which exception it's throwing, not just the number

Error while opening a connection to MS Access 2007 file: Cannot open the MS Office Access database engine workgroup information file

Cannot open the MS Office Access database engine workgroup information file - When I have code as posted.
What I am trying to do in my code is to create MS Access 2007 file and then set the user name and password to it from my program. What am I doing wrong here?
Error occurs here: objOleDbConnection.Open();
EDIT: I have made some changes, seems like it opens a connection but the command is incorrect.
Now problem is here:
objOleDbCommand.CommandText =
"ALTER USER " + storedAuth.UserName +
" PASSWORD [" + storedAuth.Password + "] []";
The entire code:
// Creating an object allowing me connecting to the database.
OleDbConnection objOleDbConnection = new OleDbConnection();
objOleDbConnection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=" + sfdNewFile.FileName + ";Persist Security Info=False";
// Creating command object.
OleDbCommand objOleDbCommand = new OleDbCommand();
objOleDbCommand.Connection = objOleDbConnection;
try
{
objOleDbConnection.Open();
objOleDbCommand.CommandText = "ALTER USER " +
storedAuth.UserName + " PASSWORD [" +
storedAuth.Password + "] []";
objOleDbCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
// Displaying any errors that
// might have occured.
MessageBox.Show("Error: " + ex.Message);
}
finally
{
objOleDbConnection.Close();
}
To change an Access DB password, you must it open in exclusive mode. Try adding this to your connection string ;Exclusive=1.
createMSFile.Create("Provider=Microsoft.ACE.OLEDB.12.0;Exclusive=1;Data Source=" +
sfdNewFile.FileName);
Well, the error you are getting suggests someone else is keeping the file open, which prevents the password change...
HelpNeeder, I think the problems you are experiencing should first be solved in your other question:
Error tells me I haven't close the connection, but haven't I?
Thanks!

Categories