Working with Access database via OleDbReader

StewartBW 285 Reputation points
2024-04-01T16:00:49.7066667+00:00

Hey all

I have no problem when all my access mdb are string!

I'm using Access database engine 2010 to connect to mdb.

The problem occurs when I have Boolean / Integer / Date fields:

New OleDbCommand("INSERT INTO tableblah (strfield, intfield, boolfield, datefield) VALUES ('" + strTextBoxX.Text + "' , '" + numIntegerInput.Value.ToString + "' , '" + boolCheckBoxX.Checked.ToString + "' , '" + DateTimePicker.Value.ToString + "')", MyConnection)

Seems that Yes/No field cannot get True/False? What should I pass in my command string?

About integer and date field how should I format it?

Thanks

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,268 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,574 questions
Access Development
Access Development
Access: A family of Microsoft relational database management systems designed for ease of use.Development: The process of researching, productizing, and refining new or existing technologies.
822 questions
{count} votes

3 answers

Sort by: Most helpful
  1. P a u l 10,406 Reputation points
    2024-04-01T17:59:01.3066667+00:00

    Have you seen this post? It seems to be related to your query:

    https://stackoverflow.com/questions/16856582/c-sharp-update-a-boolean-value-in-an-access-database#answer-19137696

    If you pass through the parameters via cmd.Parameters.Add() then it'll convert the values for you. Their example is C# but the API should be the same.

    0 comments No comments

  2. Jiale Xue - MSFT 32,076 Reputation points Microsoft Vendor
    2024-04-02T09:19:29.99+00:00

    Hi @StewartBW , Welcome to Microsoft Q&A,

    When dealing with different data types in your Access database (such as Boolean, Integer, and Date fields), it's important to properly format the values in your SQL command string to ensure they are correctly interpreted by the database engine. Here's how you can adjust your command string:

    1. Boolean (Yes/No) Field:
      • Access databases typically represent Boolean fields with Yes/No values.
      • You should use -1 for True and 0 for False when inserting Boolean values into Yes/No fields.
    2. Integer Field:
      • Integer fields don't require any special formatting in the command string. You can simply pass the integer value.
    3. Date Field:
      • Date fields should be formatted in a way that Access recognizes. The format #yyyy-MM-dd# is commonly used in SQL commands for dates in Access databases.

    Here's how you can adjust your command string to handle different data types:

    
    string commandString = "INSERT INTO tableblah (strfield, intfield, boolfield, datefield) VALUES ('" 
    
                            + strTextBoxX.Text + "' , " 
    
                            + numIntegerInput.Value.ToString() + " , " 
    
                            + (boolCheckBoxX.Checked ? "-1" : "0") + " , #" 
    
                            + DateTimePicker.Value.ToString("yyyy-MM-dd") + "#)";
    
    OleDbCommand command = new OleDbCommand(commandString, MyConnection);
    
    

    This should ensure that the command string correctly handles different data types when inserting records into the Access database. As Paul mentioned, use parameterized queries to handle potential SQL injection vulnerabilities instead of concatenating values directly into SQL command strings.

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  3. Karen Payne MVP 35,036 Reputation points
    2024-04-02T16:23:57.94+00:00

    Hello and welcome!

    I would recommend using Dapper for this which you add to your project as an NuGet package here.

    I put together a console project to show how to add a new record and read all records in this project. The same will work in a Windows Forms project.

    To try this in your project

    • If not using .NET Core, you will need to make some adjustments like the queries will need to be one liners.
    • Replace ConnectionString() with your connection string, in this project the connection string is in appsettings.json
    • Replace the class Person with a class which represents your data.

    Class which represents a row in the table

    public class Person
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public DateTime BirthDate { get; set; }
        public bool Active { get; set; }
        public int SomeNumber { get; set; }
    }
    

    Code which first adds a new record followed by reading all records and dumping the records using another NuGet package (you do not need this part).

    using System.Data;
    using System.Data.OleDb;
    using Dapper;
    using DapperForAccessDatabaseMdb.Classes;
    #pragma warning disable CA1416
    
    namespace DapperForAccessDatabaseMdb;
    
    internal partial class Program
    {
        private static IDbConnection _cn;
    
        private static void Main()
        {
            _cn = new OleDbConnection(ConnectionString());
    
            Person person = new()
            {
                FirstName = "John",
                LastName = "Doe",
                BirthDate = new(1980, 1, 1),
                Active = true,
                SomeNumber = 123
            };
    
            Add(person);
    
            var people = GetAll();
    
            AnsiConsole.MarkupLine(ObjectDumper.Dump(people));
            Console.ReadLine();
        }
    
        public static void Add(Person person)
        {
            const string statement =
                """
                INSERT INTO Person
                (
                    FirstName,LastName,BirthDate,Active,SomeNumber
                )
                VALUES
                (
                    @FirstName,@LastName,@BirthDate,@Active,@SomeNumber
                )
                """;
            _cn.Execute(statement, new
            {
                person.FirstName, 
                person.LastName, 
                person.BirthDate, 
                person.Active,
                person.SomeNumber
            });
        }
    
        public static List<Person> GetAll()
            => _cn.Query<Person>("SELECT * FROM Person").ToList();
    }
    

    Note there no need to open and close the connection, Dapper does this for you.

    A1

    0 comments No comments