c# - 如何检测 MySql 查询是否成功并输出消息?

标签 c# mysql

我正在使用 C# 制作图书馆管理系统。例如,我有一个表格来添加一本书。输入所有详细信息并运行查询以将书籍添加到数据库后,我想知道如何检测查询是否成功并输出消息。

表单代码:

private void btnSubmit_Click(object sender, EventArgs e)
    {
        string isbn = txtISBN.Text;
        string title = txtbkTitle.Text;
        string author = txtbkAuthor.Text;
        string publisher = txtbkPublisher.Text;
        string imgPath = txtimgPath.Text;
        string catalog = txtCatalog.Text;


        book bc = new book(isbn, title, author, publisher, imgPath, catalog);
        utility = new DBUtlitiesBook();

        utility.Insert(bc);
    }

此代码获取用户条目的所有详细信息,将它们存储在变量中并将它们发送到具有插入查询的方法。

这是方法:

public override void Insert(object ob)
    {

        book bk = (book)ob;
        string isbn = bk.Isbn;
        string title = bk.Title;
        string author = bk.Author;
        string publisher = bk.Publisher;
        string localPath = bk.Imgpath;
        string catalogid = bk.CatalogID;



        MySqlConnection connection = new MySqlConnection(conn);
        MySqlCommand cmd;


        try
        {
            connection.Open();
            cmd = connection.CreateCommand();
            cmd.CommandText = "INSERT INTO BOOK(ISBN, title, author, publisher,imgPath, catalogID) VALUES ('" + isbn + "','" + title + "','" + author + "','" + publisher + "','" + localPath + "','" + catalogid + "')";
            cmd.ExecuteNonQuery();
        }

        catch (Exception)
        {
            throw;
        }
        finally
        {
            if (connection.State == System.Data.ConnectionState.Open)
            {
                connection.Close();

            }
        }
    }

(这个方法覆盖了父类中的另一个方法)

你能帮我解决我的问题吗?

谢谢

最佳答案

你可以使用下面提到的代码

try
        {
            connection.Open();
            cmd = connection.CreateCommand();
            cmd.CommandText = "INSERT INTO BOOK(ISBN, title, author, publisher,imgPath, catalogID) VALUES ('" + isbn + "','" + title + "','" + author + "','" + publisher + "','" + localPath + "','" + catalogid + "')";
            int a= cmd.ExecuteNonQuery();
             if(a>0)
               //updated.
             else
              //Not updated.
        }
catch (Exception)
        {
           //Not updated.
        }

关于c# - 如何检测 MySql 查询是否成功并输出消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24061615/

相关文章:

c# - RabbitMQ EventingBasicConsumer 丢失消息

c# - 弹出窗口为 View 中的每个窗口显示相同的结果

PHP MySQL - 插入数据时接收邮件

php - Laravel leftJoin 现在显示结果

c# - 仅选择职位为服务员的员工

c# - Linq to SQL - 从两个表返回记录详细信息

php - 自动检索表单值

mysql - 为什么我的更新查询对我的表格内容没有影响?

mysql - 根据 Mysql 中的单元格值将一行转换为多行

c# - 试图 int.parse 多数组字符串