美好的一天!插件到我的程序时遇到了一个小问题。看,代码没有错误,但我在尝试插入时遇到了OleDb异常。我项目的其他部分工作正常,但这里有一个小问题我似乎无法找到
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();
}
其他功能,如搜索和删除工作,但我在这里找不到问题
以下是例外情况:
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
答案 0 :(得分:0)
我建议您使用Parameter
来避免SQL注入,并将括号[]
放入[Password]
的查询中,因为它是如下所示的关键字:
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();
}
答案 1 :(得分:0)
Abdellah的答案可行,但在构建查询字符串时请注意SQL注入攻击。你应该像这样构建它:
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;