我怎么能在MySQL数据库中插入数据? [英] How I can Insert Data in the MySQL Database?

查看:135
本文介绍了我怎么能在MySQL数据库中插入数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET应用程序和MySQL数据库。我想要写一个类插入,删除,并显示在数据库中的数据。我有一个连接到数据库,但我不能在数据库中插入数据。

I have a ASP.NET Application and a MySQL Database. I want write a Class to insert,delete and show the Data from the database. I have a Connection to the Database but I can't insert data in the database.

我的班级插入方式:

 public string CreateEntry(string Connectionstring,string mitarbeiter)
        {
            connection = new MySqlConnection(Connectionstring);

            try
            {
                MySqlCommand command = connection.CreateCommand();

                command.CommandText = "INSERT INTO tb_mitarbeiter (Vorname) VALUES ('tom')";

                connection.Open();

                return "Mitarbeiter wurde angelegt";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                connection.Close();
            }
        }

ConnectionString中是正确的。我没有得到一个错误,但没有数据在数据库中。

The Connectionstring is right. I don't get a error but there is no data in the database.

我的表名:tb_mitarbeiter
列:ID和Vorname

My tablename: tb_mitarbeiter columns: ID and Vorname

推荐答案

您应该简单地执行命令

....
MySqlCommand command = connection.CreateCommand();
command.CommandText = "INSERT INTO tb_mitarbeiter (Vorname) VALUES ('tom')";
connection.Open();
command.ExecuteNonQuery();
....

我想, mitarbeiter 是要在数据库中设置的实际价值。结果
如果是这样的话记得要使用参数来插入/更新数据。

I suppose that mitarbeiter is the real value that should be set in the database.
If this is the case remember to use parameters to insert/update your data

MySqlCommand command = connection.CreateCommand();
command.CommandText = "INSERT INTO tb_mitarbeiter (Vorname) VALUES (?name)";
command.Parameters.AddWithValue("?name", mitarbeiter);
connection.Open();
command.ExecuteNonQuery();

这篇关于我怎么能在MySQL数据库中插入数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆