P粉8212313192023-08-17 13:01:58
To connect to a MySQL database hosted on a remote server from your C# standalone application, you can use the MySQL Connector/NET library. This library provides the tools needed to establish connections and perform various database operations. Here's how you can do it:
1- Install MySQL Connector/NET: If you have not installed the MySQL Connector/NET package, please install it in your C# project. You can install it through the NuGet package manager. Search for "MySql.Data" and install the official MySQL Connector/NET package.
2- Connection string: You need to build a connection string with the details needed to connect to the MySQL database. Since you mentioned that your IP is dynamic and needs to be added to the whitelist each time, you may need to adjust the connection string each time. Here is a basic example of a connection string:
string server = "your-server-ip"; string database = "your-database-name"; string uid = "your-username"; string password = "your-password"; string connectionString = $"Server={server};Database={database};Uid={uid};Pwd={password};";
3- Perform database operations: After preparing the connection string, you can use the MySQL Connector/NET library to perform database operations such as INSERT, UPDATE, DELETE, etc. The following is an example of performing an INSERT operation:
using MySql.Data.MySqlClient; // ... using (MySqlConnection connection = new MySqlConnection(connectionString)) { connection.Open(); string query = "INSERT INTO your_table (column1, column2) VALUES (@val1, @val2)"; using (MySqlCommand command = new MySqlCommand(query, connection)) { command.Parameters.AddWithValue("@val1", value1); command.Parameters.AddWithValue("@val2", value2); command.ExecuteNonQuery(); } }
Similarly, you can modify queries for UPDATE and DELETE operations.
Remember that for security reasons it is best to use parameterized queries (as shown above) to prevent SQL injection attacks.
Regarding the dynamic IP issue, if your IP address changes frequently and needs to be added to the whitelist every time, you may consider setting up a VPN or using a Dynamic DNS (DDNS) service to obtain the same IP address as your dynamic IP. The corresponding consistent host name. This gives you a more stable connection point and simplifies whitelist setup. Additionally, you may also wish to discuss with your hosting provider whether there are more secure and manageable remote connection options, such as setting up an SSH tunnel or using a virtual private network.