Omortis
Omortis

Reputation: 1530

CS0246 error with OdbcConnection line in C#

Ive been chasing this CS0246 error for a couple hours and am not sure how to resolve it. Given this simple C# code:

using System;
// using Microsoft.Data.Odbc; 
using System.Data.Odbc; 

namespace dotnetdb
{
    class Program
    {
        static private void SelectRows(string[] args)
        {
            string passWord = "PWD=password";
            string uName    = "UID=username";
            string dbServer = "SERVER=server";
            string dbName   = "DATABASE=db";
            string driver   = "DRIVER={ODBC Driver 13 for SQL Server}"
            string connString = // assembled from above 

            string sql = // sql;

            OdbcConnection conn = new OdbcConnection(connString);

            conn.Open();

            OdbcCommand cmd = new OdbcCommand(sql, conn);

            // work with cmd

            Console.WriteLine("Didnt kick the bucket!");
        }
    }
}

The Microsoft stanza on line 2 yields a CS0234 error. The stanza on line 3 (from the Microsoft docs) gives me the CS0246:

Program.cs(20,13): error CS0246: The type or namespace name 'OdbcConnection' could not be found

I use this ODBC connection in go and python all the time but this is my first attempt at using it with C#. Also my first ever C# program. The code above is scraped almost directly from the MS docs - what am I missing? How do I get access to System.Data.Odbc?

Am I trying to run before I learn how to walk with C#?

Note that applications created with dotnet build [console|webapi] build and run just fine.

Thanks!

Upvotes: 3

Views: 3635

Answers (1)

Jimenemex
Jimenemex

Reputation: 3166

You need to add it as a reference. Refer to this question on how to add a reference in Visual Studio Code. I also noticed that your program doesn't have a Main() and that'll prevent it from compiling also.

Change this:

static private void SelectRows(string[] args)

to

static void Main(string[] args)

Or call it from Main() like this:

static void Main(string[] args)
{
    SelectRows(args);
}

private static void SelectRows(String[] args)
{
    ...
}

In general references are a piece of compiled code, mostly in .DLL format which you can include in your own project so you can use the methods/code that the reference provides.

For example,

Let's say I have MyMath.dll which was created by somebody and I want to use this method in it.

int Add(int a, int b) {
    return a + b;
}

I have to include that MyMath.dll that somebody else created in order to use that Add() method. So when I want to use it, I use something like this.

using MyMath; // MyMath.dll

static void Main(string[] args)
{
    MyMath calculator = new MyMath();
    int result = calculator.Add(1, 2);
}

If you don't know, Visual Studio has a free community version that's pretty powerful too.

Upvotes: 2

Related Questions