如何像存储过程一样在C#中执行Access查询

时间:2019-01-10 07:38:37

标签: c# oledb ms-access-2013 oledbcommand

我正在尝试使用参数执行MS Access查询,并且始终出现错误,需要再添加1个参数。 这是我的查询

#include<stdio.h>

void swap(int *a,int *b){
    int temp=*a;
    *a=*b;
    *b=temp;
}

int partition(int a[],int p,int r){
    int temp, i,x;
    x=a[r];
    i=p-1;
    for(int j=p;j<=r;j++){
        if(a[j]<x){
            i++;
            swap(&a[i],&a[j]);
        }
    }
    i++;
    swap(&a[i],&a[r]);;
    return i;
}

void qsort(int a[],int p,int r){
    int q;
    if(p<r){
        q=partition(a,p,r);
        qsort(a,p,q-1);
        qsort(a,q+1,r);
    }
}

int binarySearch(int arr[], int n, int key){ 
    int left = 0, right = n; 
    int mid; 
    while (left < right){ 
        mid = left + (right-left)/2; 
        if (arr[mid] == key){ 
            while (arr[mid+1] == key && mid+1<n) 
                 mid++; 
            break; 
        }else if (arr[mid] > key) 
            right = mid; 
        else
            left = mid + 1; 
    } 
    while (arr[mid] > key) 
        mid--; 
    return mid + 1; 
} 

int main(){
    int a, b;
    scanf("%d %d",&a, &b);
    int data[a],d;
    for(int i=0;i<a;i++){
        scanf("%d", &data[i]);
    }   
    qsort(c, 0, a-1);
    for(int i=0;i<b;i++){
        scanf("%d", &d);
        printf("%d\n", binarySearch(c, a, d));
    }
    return 0;
}

调用查询的方法:

PARAMETERS RendszamParam Text ( 255 );
SELECT *
FROM Auto
WHERE Rendszam=[RendszamParam];

RendszamAlapjan 中,如果我将参数(注释行)加倍,它可以正常工作,但是如果没有它,我将收到一条错误消息,要求再添加一个参数,我无法弄清楚为什么

1 个答案:

答案 0 :(得分:0)

我想通了。

在查询中,我们不必指定参数,只需在查询中使用@sing,Accsess 2013将自动识别出这是一个变量(参数),如下所示:

SELECT *
FROM Auto
WHERE Rendszam=[@RendszamParam];

调用方法如下:

public Auto RendszamAlapjan (string rendszam)
      {
         Auto auto = null;

         using (OleDbConnection connection = new OleDbConnection(KapcsolatAdatai.KapcsolatiString))
         {
            OleDbCommand command = connection.CreateCommand();

            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "AtoRendszamAlapjan";
            command.Parameters.Add("@RendszamParam", OleDbType.VarChar).Value = rendszam;

            connection.Open();

            using (OleDbDataReader reader = command.ExecuteReader())
            {
               while (reader.Read())
               {
                  auto = MapEntiy(reader);
               }
            }
         }

         return auto;
      }

希望有人帮助了。