connect mysql database in websever with c# application - c#

i have a PHP website and MySQL database in same web sever. i wont to connect that MySQL database with c# application. my c# application in run another computer.
how can i connect that MySQL database ?

First make sure you have downloaded and installed the MySQL Connector/NET from the MySQL official website. In this article, I will use the Connector/NET version 6.1.
Then add MySql.Data namespace in Reference
Then you can use mysql in .net
now create a connection strin like this
class ConnectToMySql{
private MySqlConnection connection;
private void Initialize()
{
server = "localhost";
database = "connectcsharptomysql";
uid = "username";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
connection.Open();
}
}
Then
1 Create a MySQL command.
2 Assign a connection and a query to the command. This can be done using the constructor
3 using the Connection and the CommandText methods in the MySqlCommand class.
4 Create a MySqlDataReader object to read the selected records/data.
5 Execute the command.
6 Read the records and display them or store them in a list.
7 Close the data reader.
8 Close the connection.
I tooth this will help full for you . now you can start working on mysql in .NET
Best of luck

you firstly have to add mysql ref to your project:
plz right click on your project and go to the ref part in it
after that try to find mysl.conncetor and tick it
and refresh your project and firstly try to add using mysql.net.client
now you can use data base located in the mysql db from c# coding
be sure you have downloaded both mysql connector and installaton which is about 500 mb files.
class ConnectToMySql{
private MySqlConnection mscon;
private void Initialize()
{
server = "localhost";
database = "your own database name";
uid = " your username";
password = "your password";
string const;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
mscon= new MySqlConnection(const);
mscon.Open();
}
}

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.

SSIS generate Programmatically: Project connection manager don't appear in the project connection list

I create Package from c#,and this code use to work with SQL server 2016 but now with Sql server 2014 its giving me issues :
I am adding the package to the project this way :
proj.PackageItems.Remove("HSTG_" + hstg_table.tablename + ".dtsx");
proj.PackageItems.Add(p, "HSTG_" + hstg_table.tablename + ".dtsx");
In the list of connection of the project i can see 3 Connection manager,
but in the the package i see 0 connection and then of course when i try to access one of them this way p.Connections["META"] it throw me error saying the connection cannot be found.
local_variable2
Instead of reading an existing ispac,I create one programmatically and it does work. But i still don't understand why it doesn't work in the previous way.
/* Previous way of doing it which work for me on a previous project but not
working anymore
*/
Project proj = Project.OpenProject(fixed_settings.Default.PROJECT_ISPAC);
// New way by creating the project on the fly
//Test creation project
Project proj = Project.CreateProject();
ConnectionManagerItem connectionManagerItem_meta = proj.ConnectionManagerItems.Add("OLEDB", "META.conmgr");
connectionManagerItem_meta.ConnectionManager.Name = "META";
connectionManagerItem_meta.ConnectionManager.ConnectionString = "Data Source=" + fixed_settings.Default.server_meta + ";Initial Catalog=" + fixed_settings.Default.server_meta + ";Provider=SQLNCLI11.1;Integrated Security=SSPI;Auto Translate=False;";
ConnectionManagerItem connectionManagerItem_stg = proj.ConnectionManagerItems.Add("OLEDB", "STG.conmgr");
connectionManagerItem_stg.ConnectionManager.Name = "STG";
connectionManagerItem_stg.ConnectionManager.ConnectionString = "Data Source = " + fixed_settings.Default.server_stg + "; Initial Catalog = " + fixed_settings.Default.database_stg + "; Provider = SQLNCLI11.1; Integrated Security = SSPI; Auto Translate = False;";
ConnectionManagerItem connectionManagerItem_hstg = proj.ConnectionManagerItems.Add("OLEDB", "HSTG.conmgr");
connectionManagerItem_hstg.ConnectionManager.Name = "HSTG";
connectionManagerItem_hstg.ConnectionManager.ConnectionString = "Data Source=" + fixed_settings.Default.server_hstg + ";Initial Catalog=" + fixed_settings.Default.database_hstg + ";Provider=SQLNCLI11.1;Integrated Security=SSPI;Auto Translate=False;";

Unable to Format Message Error when connecting to DB

I am currently working on a function that connects to a database through a connection string that includes the parameter: "Provider=OleDB.Provider". When I ran the code I get the following error:
Unable to format message, ID: 0xc0010001: Class not registered
I have also made sure the file is located on the database and the name parameter I am passing matches the name of the Database, since I got this from the msdn webstie:
"The variable cannot be found. This occurs when an attempt is made to retrieve a variable from the Variables collection on a container during execution of the package, and the variable is not there. The variable name may have changed or the variable is not being created."
Some of the code I have for the connection is(error happens on conn.open):
using (OleDbConnection conn = new OleDbConnection("Provider=mrOleDB.Provider.2;Persist Security Info=False;User ID=\"\";Data Source=" + data_source + ";Location=\"Provider=SQLOLEDB.1;Persist Security Info=False;User ID=" + user + "; PWD=" + password + ";Initial Catalog='" + jobnumber + "';Data Source=" + oDatabase + ";OLE DB Services=-4\";Extended Properties=\"\";Initial Catalog=" + oroot + jobnumber + "\\" + jobnumber + ".mdd;Mode=ReadWrite;MR Init MDSC=\"\";MR Init MDSC Access=2;") {
//(Theres a little more on the connection string but its adding settings for the data collection similar to the last part: MR Init mdsc)
try{
conn.Open();
}
catch(exception er)
Console.Writelin(er.message)
}
Could you please help me understand this error, or what it means? I tried looking for some solutions but was not able to find a solution that is similar to my issue. Thank you for all your help!

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".

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