Good day all! I'm having a minor issue with the insert to my program. See, the code has no errors but I'm having an OleDb exception when trying to insert. The other parts of my project work fine but there is a tiny issue here that I can't seem to find
public void Insert()
{
//myDb = new OleDbConnection(conn + dbFile);
myDb.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM Employee", myDb);
//
OleDbCommand cmd = new OleDbCommand("INSERT INTO Employee(Username, Password, email, phone) VALUES ('" + insUn + "','" + insPass + "','" + insNm + "','" + insNmr + "')", myDb);
adapter.InsertCommand = cmd;
adapter.InsertCommand.ExecuteNonQuery();
DataSet ds = new DataSet();
adapter.Fill(ds, "Employee");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Employee";
myDb.Close();
}
The other functions such as the search and delete work but I can't find the problem here
These are the exceptions:
try
{
if (textBox2.Text != "")
{
insUn = textBox2.Text;
insNmr = textBox4.Text;
insPass = textBox3.Text;
insNm = textBox5.Text;
}
Insert();
}
catch (OleDbException ex)
{
MessageBox.Show("Error, please try again", "Exception", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
}
catch (FormatException ex)
{
MessageBox.Show("One or more fields have not been entered. Please check and re-enter", "Missing fields", MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
enter code here
I advice you to use the Parameter
to avoid SQL injections , and put the brackets []
in query for [Password]
because it's a keyword like below :
public void Insert()
{
//myDb = new OleDbConnection(conn + dbFile);
myDb.Open();
OleDbCommand cmd = new OleDbCommand("INSERT INTO Employee(Username, [Password], email, phone) VALUES (@Username, @Password, @email, @phone)", myDb);
cmd.Parameters.AddWithValue("@Username", insUn);
cmd.Parameters.AddWithValue("@Password", insPass);
cmd.Parameters.AddWithValue("@email", insNm);
cmd.Parameters.AddWithValue("@phone", insNmr);
cmd.ExecuteNonQuery();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM Employee", myDb);
DataSet ds = new DataSet();
adapter.Fill(ds, "Employee");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Employee";
myDb.Close();
}
Abdellah's answer will work, but be aware for SQL Injection attacks when building your query string. You should build it like this:
OleDbCommand cmd = new OleDbCommand("INSERT INTO Employee(Username, Password, email, phone) VALUES (@p1, @p2, @p3, @p4)", myDb);
int maxSize = 50;
cmd.Paramters.Add("@p1", SqlDbType.VarChar, maxSize).Value = insUn;
cmd.Parameters.Add("@p2", SqlDbType.VarChar, maxSize).Value = insPass;
cmd.Parameters.Add("@p3", SqlDbType.VarChar, maxSize).Value = insNm;
cmd.Parameters.Add("@p4", SqlDbType.VarChar, maxSize).Value = insNmr;
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.