如何使用从datagridview检索到的ID将数据保存到数据库?

时间:2018-12-08 13:21:17

标签: c# mysql xampp

我想使用从datagridview检索到的ID将一些数据插入mysql数据库。我是编程新手。有人可以帮帮我吗?谢谢

enter image description here

1 个答案:

答案 0 :(得分:0)

首先,您需要下载并安装

MySQL ADO.Net connector

这是C#应用程序的官方ado.net连接器。一旦安装完毕,便可以使用ado.net支持的数据访问方法来保存数据。

基本步骤

  • 首先创建与my sql数据库的连接。
  • 然后创建一个包含插入命令的命令对象。
  • 然后提供包含所谓ID的对象并完成命令对象
  • 然后对数据库执行命令。

示例代码

这是稍后将使用的类变量

private MySqlConnection connection; // this MySqlConnection class comes with the connector
private string server;
private string database;
private string uid;
private string password;

此初始化方法将使用配置数据配置连接

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

希望这会有所帮助