Avatar of Skale
Skale
 asked on

How to create function that returns a single value and single row from MS Access Database in C#

Hello,

I would like to create a function and return a single value like an example;

public static string GetValueFromAccess(string uniqueID) {....}

As in example i'd like to get result "DF556-33446" when i set uniquID = 30075

I'm trying to edit this code to implement it but didn't succeeded.

        private void AccessReader_Click(object sender, RoutedEventArgs e)
        {
            string connetionString = null;
            OleDbConnection cnn;
            OleDbCommand cmd;
            string sql = null;

            connetionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Mode=Read;Data Source=E:\SampleData\ASampleDatabase.accdb";

            sql = "Select Count(*) from [Asset Items]";

            cnn = new OleDbConnection(connetionString);
            try
            {
                cnn.Open();
                MessageBox.Show("Connection Opened ");
                cmd = new OleDbCommand(sql, cnn);
                cmd.ExecuteNonQuery();
                cmd.Dispose();
                cnn.Close();
                MessageBox.Show(" ExecuteNonQuery in OleDbConnection executed !! :");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Can not open connection ! " + ex.ToString());
            }
        }

Open in new window


You can find sample database on attachment also.

AccessExample.pngASampleDatabase.accdb
DatabasesMicrosoft AccessC#SQL

Avatar of undefined
Last Comment
Skale

8/22/2022 - Mon
David Johnson, CD

SELECT [Asset Items].[Asset No]
FROM [Asset Items]
WHERE ((([Asset Items].[Serial No])="DF556-33446"));

Open in new window

ASampleDatabase-DWJ.accdb
ASKER CERTIFIED SOLUTION
Fernando Soto

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Skale

ASKER
Thank you for contributions :) Now i got the idea. Fernando it's worked! and David it's also useful to get reverse value for me :)
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck