
[英]c#, .net, delegate, asynchronous callback. What am I doing wrong here?
[英]What am I doing wrong with this C# .NET WinForms application?
我正在尝试编辑Access DB_。 由于某种原因,我无法插入任何内容。 我相信我的代码是正确的。 连接字符串是正确的(尽管出于安全考虑,我为这篇文章添加了一个假冒的字符串)。 最后,我没有获得像在函数末尾那样的MessageBox
。 也不向Access DB添加任何内容。
有什么可能的原因吗?
namespace TestBuild
{
public partial class Form1 : Form
{
OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users...\Documents\TestDB.accdb");
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into table1 values('"+textBox1.Text+"','"+textBox2.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("record inserted successfully");
}
}
}
建议-请考虑如下重构您的代码,并在MSVS调试器中一次一行地逐步执行代码:
string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users...\Documents\TestDB.accdb";
private void Button1_Click(object sender, EventArgs e)
{
string sql = "insert into table1 values('" + textBox1.Text + "','" + textBox2.Text + "')";
OleDbCommand cmd= new OleDbCommand(sql);
using (OleDbConnection con = new OleDbConnection(connString)) {
cmd.Connection = conn;
try
{
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("record inserted successfully");
}
catch (Exception ex)
{
MessageBox.Show("ERROR" + ex.Message);
}
}
}
PS:
如果要使用准备好的语句,则可以将代码更改为以下形式:
string sql = "insert into table1 values(@param1, @param2)";
...
cmd.Parameters.AddWithValue("@param1", textBox1.Text);
cmd.Parameters.AddWithValue("@param1", textBox2.Text);
con.Open();
cmd.Prepare();
cmd.ExecuteNonQuery();
您可以在此处阅读有关缓解SQL注入的技术和准则的更多信息:
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
这是另一篇好文章:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.