簡體   English   中英

System.Data.dll中發生了System.Data.OleDb.OleDbException”

[英]System.Data.OleDb.OleDbException' occurred in System.Data.dll

我應該能夠在文本框中輸入郵政編碼,因此程序運行時,應該在另一個文本框中輸入具有匹配郵政編碼的街道名稱。

但是,我收到此錯誤,但我無法真正解決。 錯誤出現在此行:

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和數據庫的經驗。

您錯誤地構造了查詢字符串

"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類構造實際的字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM