在System.Data.dll中发生System.Data.OleDb.OleDbException

时间:2014-06-02 15:09:27

标签: c# sql database ms-access oledb

我应该能够在文本框中输入邮政编码,所以当程序运行时,它应该将街道名称和匹配的邮政编码放在另一个文本框中。

然而,我收到此错误并且我无法解决问题。错误出现在这一行:

leesAdres = Adres.ExecuteReader();

整个代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication12
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void btnZoek_Click(object sender, EventArgs e)
        {
            OleDbConnection con = new OleDbConnection();
            OleDbCommand Adres = new OleDbCommand("Select `street` from `postcode` where `postcode` LIKE txtPostcode.Text", con);
            OleDbDataReader readAdres;
            con.ConnectionString = "provider=Microsoft.Ace.OLEDB.12.0; data Source = C:\\Users\\name\\Documents\\school\\Adodotnet\\postcode.accdb";

            con.Open();
            readAdres = Adres.ExecuteReader();

            while (leesAdres.Read())
            {
                txtStreet.Text = leesAdres.GetValue(0).ToString();
            }
        }
    }
}

我怀疑它可能是我的SQL命令,但我不确定,我没有使用SQL和数据库的经验。

1 个答案:

答案 0 :(得分:3)

你在

行中误解了你的查询字符串
"Select `street` from `postcode` where `postcode` LIKE txtPostcode.Text", con

应该是

"Select `street` from `postcode` where `postcode` LIKE '%" + txtPostcode.Text+ "%'" , con

为了使代码更健壮并防止SQL注入,您可以构建

形式
SqlCommand cmd = new SqlCommand("Select `street` from `postcode` where `postcode` LIKE @P1" , conn);
cmd.Parameters.Add(P1);
cmd.Parameters["P1"].Value = txtTagNumber.Text;

还要研究使用stringbuilder类来构造实际的字符串。