[英]Insert data on MySQL Database c# .NET
I would like to enter data into my database when a user clicks the button.我想在用户单击按钮时将数据输入我的数据库。 The problem should be solved with this code:问题应该用这段代码解决:
MySqlCommand com = connection.CreateCommand();
com.CommandText = ("INSERT INTO users (username, password) VALUES ('" + txt_usrn.Text + "', '" + txt_pssw.Text+ "')");
But I'm noticing (from my phpmyadmin panel) that clicking on the button doesn't insert anything.但我注意到(从我的 phpmyadmin 面板)点击按钮不会插入任何内容。 I honestly don't know why, do you know why?老实说,我不知道为什么,你知道为什么吗? I leave you my complete code:我把我的完整代码留给你:
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;
}
}
}
You forgot to execute the query.您忘记执行查询。 Also you forgot that MySqlCommand
is IDisposable
, so you should use using
block.您还忘记了MySqlCommand
是IDisposable
,因此您应该使用using
块。
See corrected code:请参阅更正后的代码:
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;
}
}
Further remarks进一步说明
The code is vulnerable to SQL injection attack - due to string concatenation.由于字符串连接,该代码容易受到 SQL 注入攻击。 You should use Parameters
property to supply parameters to query.您应该使用Parameters
属性来提供要查询的参数。
Also, MySqlConnection
also is IDisposable
so make sure you correctly dispose of this object as well .此外, MySqlConnection
也是IDisposable
,因此请确保您也正确处理了此 object 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.