繁体   English   中英

在 MySQL 数据库上插入数据 c# .NET

[英]Insert data on MySQL Database c# .NET

我想在用户单击按钮时将数据输入我的数据库。 问题应该用这段代码解决:

MySqlCommand com = connection.CreateCommand();
com.CommandText = ("INSERT INTO users (username, password) VALUES ('" + txt_usrn.Text + "', '" + txt_pssw.Text+ "')");

但我注意到(从我的 phpmyadmin 面板)点击按钮不会插入任何内容。 老实说,我不知道为什么,你知道为什么吗? 我把我的完整代码留给你:

namespace sharetru
{
    public partial class Form1 : Form
    {
        [DllImport("Gdi32.dll", EntryPoint = "CreateRoundRectRgn")]
        private static extern IntPtr CreateRoundRectRgn(

            int nLeft,
            int nTop,
            int nRight,
            int nBottom,
            int nWidthEllipse,
            int nHeightEllipse

            );

        public Form1()
        {
            InitializeComponent();         
        }

        //mysql
        MySqlConnection connection;
        
        
        Point lastpoint;

        private void Form1_Load(object sender, EventArgs e)
        {
            btn_accedi.Region = Region.FromHrgn(CreateRoundRectRgn(0, 0, btn_accedi.Width, btn_accedi.Height, 7, 7));
            btn_accedi.BackColor = Color.FromArgb(0, 149, 246);
         
            this.BackColor = Color.FromArgb(250, 250, 250);
            try
            {
                connection = new MySqlConnection("Server=sql7.freemysqlhosting.net; Port=3306; Database=sql7389377; Uid=sql7389377; Pwd=*********; ");
                connection.Open();
                if (connection.State == ConnectionState.Open)
                {
                    label1.Text = "Connected";
                    label1.ForeColor = Color.Green;
                }
                else
                {
                    label1.Text = "Not Connected";
                    label1.ForeColor = Color.Red;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

           
        }
                                              
        private void btn_accedi_Click(object sender, EventArgs e)
        {
            MySqlCommand com = connection.CreateCommand();
            com.CommandText = ("INSERT INTO users (username, password) VALUES ('" + txt_usrn.Text + "', '" + txt_pssw.Text+ "')");
            lbl_fkeerr.Visible = true;
        }
    }
}

您忘记执行查询。 您还忘记了MySqlCommandIDisposable ,因此您应该使用using块。

请参阅更正后的代码:

private void btn_accedi_Click(object sender, EventArgs e)
{
    using(MySqlCommand com = connection.CreateCommand())
    {
        com.CommandText = ("INSERT INTO users (username, password) VALUES ('" + txt_usrn.Text + "', '" + txt_pssw.Text+ "')");
        com.ExecuteNonQuery();
        lbl_fkeerr.Visible = true;
    }
}

进一步说明

由于字符串连接,该代码容易受到 SQL 注入攻击。 您应该使用Parameters属性来提供要查询的参数。

此外, MySqlConnection也是IDisposable ,因此请确保您也正确处理了此 object

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM