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. 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.
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. You should use Parameters
property to supply parameters to query.
Also, MySqlConnection
also is IDisposable
so make sure you correctly dispose of this object as well .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.