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

rjee0c15  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(229)

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

bq9c1y66

bq9c1y661#

首先你需要下载和安装

MySQL ADO.Net connector

它是c应用程序的官方ado.net连接器。一旦你安装,你可以使用ado.net标准数据访问方法来保存数据。

基本步骤

首先创建到mysql数据库的连接。
然后创建一个包含insert命令的command对象。
然后提供包含所谓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();
    }
}

希望这会有帮助

相关问题