I have a program that reads from and writes to an Access database. It works fine on my own computer but when I tried to download it on a new computer that has the new Office 2013 programs it said that the provider in connection string didn't work. Here's my connection string:
string filepath = #"C:\FamilyFoundations\ProvidentLiving\App\Data\"; // Hold the path to the file
string dbPath = filepath + "GoalsDB.accdb"; // Holds the name of our data base
// string to create our database
string db = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + dbPath + "; JET OLEDB:Engine Type=5";'
Does my string need to be changed or is there something I need to download on my friends computer? My first thought is that there is a new Microsoft.JET that I need to include, but please correct me if I'm wrong.
Related
I'm creating a C# application with a SQL Server .mdf database file. I need to install it on the user's computer, however I'm having trouble connecting to the database, the computer does not have SQL Server.
The system will only be on a local computer.
What would be the best option to connect to my .mdf database file?
Connecting to the database:
public Banco()
{
string Caminho = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + #"\AppData\Banco.mdf";
string sStringConexao = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=" + Caminho + ";Integrated Security=True";
_conexao = new SqlConnection(sStringConexao);
_comando = new SqlCommand();
_comando.Connection = _conexao;
}
I am trying to open connection with Azure SQL database. Tried creating usual connection = new MySqlConnection("Server=" + server + "Database=" + database + "Uid=" + uid + "Password=" + password); with every string variable ending with ; but yet it always fails to connect even if the data is correct. Tried to use given string for ADO.NET but then I am getting exception "keyword is not supported". I don't what else to actually.. Googled as much as possible but all solutions are quite the same and yet nothing works out for me :/
Firstly, azure databases don't use mysql. so using MySqlConnection() won't work.
instead use
SqlConnection connection = new SqlConnection(connectionstring);
Standard connection strings should be in the format
Server=tcp:[serverName].database.windows.net;Database=myDataBase;
User ID=[LoginForDb]#[serverName];Password=myPassword;Trusted_Connection=False;
Encrypt=True;
See https://www.connectionstrings.com/azure-sql-database/ for more options
var connectionString = #"Server=tcp:<dbname>.database.windows.net,1433;Initial Catalog=<databasename>;Persist Security Info=False;User ID=<userid>;Password=<password>;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;";
That's how I connect to my Azure SQL Database, works for me.
For MySQL In App you can use the fellowing code in c# to get the connection string:
static string getConnectionString()
{
#if DEBUG
string connectionString = "dbname=localdb;host=localhost:3306;user=root;pass=password;";
#else
string connectionString = Environment.GetEnvironmentVariable("MYSQLCONNSTR_localdb");
#endif
string[] options = connectionString.Split(";");
string database = options[0].Split("=")[1]; ;
string serverport = options[1].Split("=")[1];
string server = serverport.Split(":")[0];
string port = serverport.Split(":")[1];
string user = options[2].Split("=")[1];
string password = options[3].Split("=")[1]; ;
connectionString = $"server={server};port={port};database={database};user={user};password={password};";
return connectionString;
}
The standard .Net Framework provider format is:
Server=[serverName].database.windows.net;Database=myDataBase;
User ID=[LoginForDb]#[serverName];Password=myPassword;Trusted_Connection=False;
Encrypt=True;
Azure SQL Database is an SQL Server type database, not MySQL!
Have you followed Microsoft instructions?
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-connect-query-dotnet-visual-studio
You have to create server-level firewall rule on azure too, to be able to connect.
I have a problem that when i want to create database and specify its name it is created in the specified directory and in directory where the aplication is running. Why is that happening?
Code that creates database:
using System.Data.SQLite;
...
private static string AddDb(string dbName, string dbPassword)
{
try
{
//default paths
string startupPath = Environment.CurrentDirectory;
string dataBasePath = startupPath + "\\DB\\" + dbName;
//creating the dbfile
SQLiteConnection.CreateFile(dataBasePath);
//Opening connection
SQLiteConnection dbConnString;
dbConnString = new SQLiteConnection("Data Source =" + dbName + ";Version=3;");
dbConnString.Open();
dbConnString.ChangePassword(dbPassword);
dbConnString.Close();
return dataBasePath;
}
catch
{
MessageBox.Show("Failed to create database", "DB Creator");
return "";
}
}
The problem seems to be that you use different paths in CreateFile and your connection string.
If you look at your code below you'll notice that in one case you use a full path to create the file (databaseBasePath), while in the other case you only use the database file name in your connection string (dbName). Without an absolute path, this may be a different folder!
string dataBasePath = startupPath + "\\DB\\" + dbName;
SQLiteConnection.CreateFile(dataBasePath);
SQLiteConnection dbConnString;
dbConnString = new SQLiteConnection("Data Source =" + dbName + ";Version=3;");
It seems like Open then creates the file if it can't find it.
A word on the paths:
You're not allowed to write the Program Files folder, so using the current folder for the database file is really a bad idea.
The use of Environment.CurrentDirectory is also a bad idea. Depending on how you start your application, this may or may not be the folder that you think it is (see my comments to the other answers and this).
Never assume that \ is actually the path separator. Use Path.Combine instead.
I suggest that you use Environment.GetFolderPath to get a location that's shared among all users (if the database content should be shared) or private to the current user (if all users should have their own database) and create the database there:
string baseFolder = Environment.GetFolderPath(<wherever it should be>);
string dataBasePath = Path.Combine(baseFolder, "DB", dbName);
SQLiteConnection.CreateFile(dataBasePath);
SQLiteConnection dbConnString = new SQLiteConnection(String.Format("Data Source = {0};Version=3;", dataBasePath);
The Environment.CurrentDirectory contains the directory that the application starts from by default. You can set this property. See the MSDN article Environment.CurrentDirectory Property
How i get full path of database(.mdb) in c# which is connected by ODBC connection ?
Desire output:-
String path="path of ms access file";
Is there any method or function available in c# to get db location ?
This seems to work for me:
using (OdbcConnection con = new OdbcConnection(myConnectionString))
{
con.Open();
String path = con.Database;
Console.WriteLine(path);
It doesn't just parse the connection string, because when myConnectionString is DSN=db1; (a System DSN), path still contains
C:\Users\Public\Database1.accdb
I have this connection string :
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\Release\DB.accdb"); // Database Connection
I want my program to connect to the database without the "..\Release\" in the string.
What I mean is, that i want the program to look for the database in the program's folder, without specifying the folder's name (whatever the folder's name is).
How is that done?
You should add your DB to the project (Add -> Existing Item...) and set Build Action to Content and Copy to Output Directory to Copy always:
After that you can using following connection string:
string cs = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=test.mdb;Persist Security Info=False;";
Following code, will find database file in program folder or sub-folder:
string programPath = System.IO.Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName;
var dbPath = System.IO.Directory.GetFiles(programPath, "*.accdb", SearchOption.AllDirectories).FirstOrDefault();
string cs = null;
if (!string.IsNullOrEmpty(dbPath))
{
cs = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;", dbPath);
}
Perhaps you could use something like
String strAppDir = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
String strFullPathToMyFile = System.IO.Path.Combine(strAppDir, "DB.accdb");
ref:
How to: Get the Application Directory