使用连接的MySQL数据库编辑DataGridView时出错。试图保存时出现错误

发布于 2025-02-02 00:01:03 字数 4329 浏览 5 评论 0 原文

在尝试编辑DataGridView时,出现错误“ CommandText属性尚未正确初始化。”。我读到需要其他一些存储过程,作为输入参数,它以用户的名字,姓氏和pathonymic和电话号码为单位,并返回他的ID,如果是这样,如何在MySQL链接上实现它:< a href =“ https://metanit.com/sharp/adonet/2.11.php” rel =“ nofollow noreferrer”> https://metanit.com/sharp/adonet/adonet/2.11.php , https://metanit.com/sharp/adonet/3.5.5.php 程序代码:

    using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SD = System.Data;

namespace DBredaction
{
    public partial class Form1 : Form
    {
            DataSet ds;
            MySqlDataAdapter adapter;
            MySqlCommandBuilder commandBuilder;
            string connectionString = "Server=localhost;Database=catalog;Uid=root;pwd=;charset=utf8;";
            string sql = "SELECT * FROM employee";
            public Form1()
        {
            InitializeComponent();

            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGridView1.AllowUserToAddRows = false;

            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();
                adapter = new MySqlDataAdapter(sql, connection);

                ds = new DataSet();
                adapter.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0];
                // делаем недоступным столбец id для изменения
                dataGridView1.Columns["Id"].ReadOnly = true;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        //public MySqlConnection mycon;
        //public MySqlCommand mycom;
        //public string connect = "Server=localhost;Database=catalog;Uid=root;pwd=;charset=utf8;";
        //public SD.DataSet ds;
        //public MySqlCommand mycon2;otchestvo

        private void button1_Click(object sender, EventArgs e)
        {
            try { 
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();
                adapter = new MySqlDataAdapter(sql, connection);
                commandBuilder = new MySqlCommandBuilder(adapter);
                adapter.InsertCommand = new MySqlCommand("", connection);
                adapter.InsertCommand.CommandType = CommandType.StoredProcedure;
                adapter.InsertCommand.Parameters.Add(new MySqlParameter("@imia",    MySqlDbType.VarChar, 50, "Имя"));
                adapter.InsertCommand.Parameters.Add(new MySqlParameter("@familia", MySqlDbType.VarChar, 50, "Фамилия"));
                adapter.InsertCommand.Parameters.Add(new MySqlParameter("@otchestvo", MySqlDbType.VarChar, 50, "Отчество"));
                adapter.InsertCommand.Parameters.Add(new MySqlParameter("@telephon", MySqlDbType.VarChar, 11, "Телефон"));
                

                MySqlParameter parameter = adapter.InsertCommand.Parameters.Add("@id", MySqlDbType.Int16, 0, "Id");
                parameter.Direction = ParameterDirection.Output;

                adapter.Update(ds);
            }
        }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    MessageBox.Show("DB CONNECT");
                    connection.Close();
                }
            }
            catch
            {
                MessageBox.Show("Connection lost");
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dataGridView1.SelectedRows)
            {
                dataGridView1.Rows.Remove(row);
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            DataRow row = ds.Tables[0].NewRow(); 
            ds.Tables[0].Rows.Add(row);
        }
    }
    }

When trying to edit the datagridview, an error appears "The CommandText property has not been properly initialized.". I read that some other stored procedure is needed, which as input parameters it takes the first name, last name and patronymic and phone number of the user and returns his id, if so, how to implement it on mysql link to the source: https://metanit.com/sharp/adonet/2.11.php , https://metanit.com/sharp/adonet/3.5.php
Program code:

    using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SD = System.Data;

namespace DBredaction
{
    public partial class Form1 : Form
    {
            DataSet ds;
            MySqlDataAdapter adapter;
            MySqlCommandBuilder commandBuilder;
            string connectionString = "Server=localhost;Database=catalog;Uid=root;pwd=;charset=utf8;";
            string sql = "SELECT * FROM employee";
            public Form1()
        {
            InitializeComponent();

            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGridView1.AllowUserToAddRows = false;

            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();
                adapter = new MySqlDataAdapter(sql, connection);

                ds = new DataSet();
                adapter.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0];
                // делаем недоступным столбец id для изменения
                dataGridView1.Columns["Id"].ReadOnly = true;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        //public MySqlConnection mycon;
        //public MySqlCommand mycom;
        //public string connect = "Server=localhost;Database=catalog;Uid=root;pwd=;charset=utf8;";
        //public SD.DataSet ds;
        //public MySqlCommand mycon2;otchestvo

        private void button1_Click(object sender, EventArgs e)
        {
            try { 
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                connection.Open();
                adapter = new MySqlDataAdapter(sql, connection);
                commandBuilder = new MySqlCommandBuilder(adapter);
                adapter.InsertCommand = new MySqlCommand("", connection);
                adapter.InsertCommand.CommandType = CommandType.StoredProcedure;
                adapter.InsertCommand.Parameters.Add(new MySqlParameter("@imia",    MySqlDbType.VarChar, 50, "Имя"));
                adapter.InsertCommand.Parameters.Add(new MySqlParameter("@familia", MySqlDbType.VarChar, 50, "Фамилия"));
                adapter.InsertCommand.Parameters.Add(new MySqlParameter("@otchestvo", MySqlDbType.VarChar, 50, "Отчество"));
                adapter.InsertCommand.Parameters.Add(new MySqlParameter("@telephon", MySqlDbType.VarChar, 11, "Телефон"));
                

                MySqlParameter parameter = adapter.InsertCommand.Parameters.Add("@id", MySqlDbType.Int16, 0, "Id");
                parameter.Direction = ParameterDirection.Output;

                adapter.Update(ds);
            }
        }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    MessageBox.Show("DB CONNECT");
                    connection.Close();
                }
            }
            catch
            {
                MessageBox.Show("Connection lost");
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in dataGridView1.SelectedRows)
            {
                dataGridView1.Rows.Remove(row);
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            DataRow row = ds.Tables[0].NewRow(); 
            ds.Tables[0].Rows.Add(row);
        }
    }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

丢了幸福的猪 2025-02-09 00:01:03

它不太好。如果您将命令构建器分配给适配器,则不会自己设置xxxcommand dml属性;命令构建器通过查看SelectCommand,制定表格架并编写查询来做到这一点。

我将在专用存储库类中的类级别的适配器,其中选择,connstr和命令构建器设置:

//in the constructor of the repo class
_myDataAdapter = new MySqlDataAdapter("SELECT here", "connstr here");
_commandBuilder = new MySqlCommandBuilder(_myDataAdapter);

填充代码运行:

//in a GetData method of the repo class

DatTable dt = new DataTable();
_myDataAdapter.Fill(dt);
return dt;

可以触发相关的I/U/D命令:

//in a SaveChanges(DataTable) method of the repo class
_myDataAdapter.Update(dt);

请参阅有关CB的更多背景信息;他们的示例代码基于一个完整的程序化“填充,更改,保存”工作流程,因此所有方法都是一种方法,但是您的工作流程基本上是由需要进行网格更改的用户中断的,因此将其分解。

如果您想以一种方法进行操作,可以制作适配器,制作命令构建器,然后通过在命令构建器上调用相关的getxxx在适配器上设置I/U/D命令,

请注意,命令构建器没有使用存储程序;您已经阅读的有关需要制作一个存储过程来更新/插入数据的东西并不是将数据保存到DB的唯一方法,如果您创建了一个Sproc并希望使用它,请忘记命令构建器;您必须自己进行命令设置

It doesn't work quite like that; if you're assigning a command builder to an adapter you don't then also set the XxxCommand DML properties yourself; the command builder does that from looking at the SelectCommand, working out the table schema and writing the queries.

I'd have the adapter at class level in a dedicated repository class, where the select, connstr and command builder are set:

//in the constructor of the repo class
_myDataAdapter = new MySqlDataAdapter("SELECT here", "connstr here");
_commandBuilder = new MySqlCommandBuilder(_myDataAdapter);

the fill code runs:

//in a GetData method of the repo class

DatTable dt = new DataTable();
_myDataAdapter.Fill(dt);
return dt;

and the relevant I/U/D commands can be triggered:

//in a SaveChanges(DataTable) method of the repo class
_myDataAdapter.Update(dt);

See https://www.devart.com/dotconnect/mysql/docs/Devart.Data.MySql~Devart.Data.MySql.MySqlCommandBuilder.html for more background info on the CB; their example code is based on a complete programmatic "fill, change, save" workflow so it's all in one method, but your workflow is essentially interrupted by the user needing to do the changes in the grid, hence breaking it up.

If you want to do it in one method, you can make your adapter, make your command builder and then set the I/U/D commands on the adapter by calling the relevant GetXxx on the command builder

Note that the command builder doesn't use stored procedures; that thing you've read about needing to make a stored procedure to update/insert data isn't the only way to save data to a db, and if you have created a sproc and are hoping to use it, forget a command builder; you'll have to do the command setup yourself

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文