【发布时间】:2019-05-10 00:16:16
【问题描述】:
【问题讨论】:
【问题讨论】:
首先你需要下载并安装
MySQL ADO.Net connector
它是用于 C# 应用程序的官方 ado.net 连接器。安装后,您可以使用 ado.net 标准数据访问方法来保存数据。
这是后面会用到的类变量
private MySqlConnection connection; // this MySqlConnection class comes with the connector
private string server;
private string database;
private string uid;
private string password;
这将Initialize方法将配置与配置数据的连接
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);
}
此方法将打开与数据库的连接。您也应该编写一个 C Lose 方法。因为最好在使用后始终关闭连接
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based
//on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
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;
}
}
这将向数据库中插入一条记录。查询将包含针对数据库运行的 T-SQL 查询
public void Insert()
{
string query = "INSERT INTO tableinfo (name, age) VALUES('John Smith', '33')";
//open connection
if (this.OpenConnection() == true)
{
//create command and assign the query and connection from the constructor
MySqlCommand cmd = new MySqlCommand(query, connection);
//Execute command
cmd.ExecuteNonQuery();
//close connection
this.CloseConnection();
}
}
希望这会有所帮助
【讨论】: