Connection to .mdf database on local machine - c#

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;
}

Related

azure connection string c#

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.

Method fires an exception when trying to connect to remote SQL Server

I want to create a simple tool that connect to SQL Server then list all databases, and after user selects one of those databases, the tool will perform some SQL scripts on it.
Below is a method that should return a DataTable contains all my databases;
I send to it sqlServerIp as first parameter like 10.10.20.30 ip address not server name.
Also I didn't specify a SQL Server instance.
private DataTable GetSqlServerDatabases(String sqlServer, bool isWindowsAuth, String login, String password)
{
String connectionString;
DataTable databases;
if (isWindowsAuth)
{
connectionString = "Data Source=" + sqlServer + ",1433;Network Library=DBMSSOCN; Integrated Security=True;";
}
else
{
connectionString = "Data Source=" + sqlServer + ",1433;Network Library=DBMSSOCN;" + "User id=" + login + ";Password=" + password + ";";
}
try
{
using (var con = new SqlConnection(connectionString))
{
con.Open();
databases = con.GetSchema("Databases");
foreach (DataRow database in databases.Rows)
{
String databaseName = database.Field<String>("database_name");
short dbID = database.Field<short>("dbid");
DateTime creationDate = database.Field<DateTime>("create_date");
}
}
}
catch(Exception ex)
{
databases = null;
MessageBox.Show(ex.Message.ToString());
}
return databases;
}
When I try to call the method on more than one server I faced an exception:
Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.
or
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible.
I used connection string with Network Library=DBMSSOCN; after searching here on SO and web so I don't know what is the wrong with this method.
Remove Integrated Security parameter. This parameter is for trusted connections.
More samples on http://www.connectionstrings.com/sql-server

OleDb connection to Access 2013 database

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.

SQL query running as local user instead of user in connection string

I have a WPF application that accesses a SQL server using SqlConnection with a connection string.
private string connString =
"user id=*****;" +
"password=*****;" +
"server=1.1.1.1;" +
"Trusted_Connection = yes;" +
"database=****;" +
"connection timeout = 30";
private SqlConnection myConnection = new SqlConnection(connString);
The string contains the username and password for the account I want the program to use to access the database. This works as I would expect it to on my machine. Once I run it on another machine I get a an error:
"Login failed for user 'Domain\local user'"
I am sure that I am just missing some sort of setting or configuration.
Any help would be great
Trusted_Connection = yes tells SQL Server to use Integrated (Windows) Authentication. Your user name and password are ignored.

C# Mysql connection working only on localhost

I'm connecting to a mysql database in c#, and it all works well as long as I input the server address as "localhost" or its ip, but if I try a remote ip it fails with:
Error: 0 : Unable to connect to any of the specified MySQL hosts.
here's the code:
server = Properties.Settings.Default.DBHost;
port = Properties.Settings.Default.DBPort;
database = Properties.Settings.Default.DBName ;
uid = Properties.Settings.Default.DBUser;
password = Properties.Settings.Default.DBPassword ;
string connectionString;
connectionString = "SERVER=" + server + ";" + "PORT=" + port + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
[...]
if (this.OpenConnection() == true){
// exec db operations
}
else{
MessageBox.Show("Database Connection Error.");
}
Tested:
No firewall restrictions
Same error in different computers
Already tried on with different remote databases, all with set privileges and accessible from other sources
If its your mysql server then,
Check you port is open or not. (probably 3306)
Change your bind-address in your my.ini file (from 127.0.0.1 to 0.0.0.0)
Double check the user your trying to connect to server has necessary privileges
If its not your mysql server then,
Ask the provider whether they are supporting remote connections or not.
1st you have to check if your server is supporting remote MySQL database Connection then
You can try this MySQL Connection String Builder example, i'm working with all the time .. no errors :
_connectionStr = new MySqlConnectionStringBuilder
{
Server = "127.0.0.1",
Database = myDatabase,
UserID = myUserName,
Password = myPassword,
ConnectionTimeout=60,
Port = 3306,
AllowZeroDateTime = true
};
_con = new MySqlConnection(_connectionStr.ConnectionString);
try
{
_con.Open();
}
catch
{
MessageBox.Show("Error, help i can't get connected!");
}
Hope this works!
Maybe your MySQL Server is not configured to listen to any of your IP Interface.
Maybe it is just listening into your "localhost:3306"
Check it in your MySQL Server config file "bind-address".

Categories