|
| 1 | +(odbc-csharp)= |
| 2 | + |
| 3 | +# ODBC with C# |
| 4 | + |
| 5 | +:::{rubric} About |
| 6 | +::: |
| 7 | + |
| 8 | +Use the ODBC .NET Data Provider to access data from your C Sharp ADO\.NET |
| 9 | +applications. The [.NET Framework Data Provider for ODBC] is available |
| 10 | +through the [System.Data.Odbc] namespace. |
| 11 | + |
| 12 | +:::{rubric} Install |
| 13 | +::: |
| 14 | + |
| 15 | +:::{include} /connect/odbc/install-dropdown.md |
| 16 | +::: |
| 17 | + |
| 18 | +:::{rubric} Synopsis |
| 19 | +::: |
| 20 | + |
| 21 | +`example.csproj` |
| 22 | +```xml |
| 23 | +<Project Sdk="Microsoft.NET.Sdk"> |
| 24 | + |
| 25 | + <PropertyGroup> |
| 26 | + <OutputType>Exe</OutputType> |
| 27 | + <TargetFramework>net$(NETCoreAppMaximumVersion)</TargetFramework> |
| 28 | + <GenerateProgramFile>false</GenerateProgramFile> |
| 29 | + </PropertyGroup> |
| 30 | + |
| 31 | + <ItemGroup> |
| 32 | + <PackageReference Include="System.Data.Odbc" Version="9.*" /> |
| 33 | + </ItemGroup> |
| 34 | + |
| 35 | +</Project> |
| 36 | +``` |
| 37 | +`example.cs` |
| 38 | +```c# |
| 39 | +using System; |
| 40 | +using System.Data.Odbc; |
| 41 | + |
| 42 | +// Connect to database |
| 43 | +string connection_string = "Driver={PostgreSQL Unicode};Server=localhost;Port=5432;Uid=crate;Pwd=crate;MaxVarcharSize=1073741824"; |
| 44 | +using (OdbcConnection connection = new OdbcConnection(connection_string)) |
| 45 | +{ |
| 46 | + connection.Open(); |
| 47 | + |
| 48 | + // Invoke query |
| 49 | + using (OdbcCommand command = new OdbcCommand("SELECT mountain, height FROM sys.summits ORDER BY height DESC LIMIT 5", connection)) |
| 50 | + using (OdbcDataReader reader = command.ExecuteReader()) |
| 51 | + { |
| 52 | + // Display results |
| 53 | + while (reader.Read()) |
| 54 | + Console.WriteLine($"{reader.GetString(0)}: {reader.GetInt32(1)}"); |
| 55 | + } |
| 56 | +} |
| 57 | +``` |
| 58 | + |
| 59 | +:::{rubric} Example |
| 60 | +::: |
| 61 | + |
| 62 | +Create the files `example.csproj` and `example.cs` including the synopsis code shared above. |
| 63 | + |
| 64 | +:::{include} ../_cratedb.md |
| 65 | +::: |
| 66 | +Invoke program. |
| 67 | +```shell |
| 68 | +dotnet run |
| 69 | +``` |
| 70 | + |
| 71 | +:::{rubric} CrateDB Cloud |
| 72 | +::: |
| 73 | + |
| 74 | +For connecting to CrateDB Cloud, use the `Sslmode=require` parameter, |
| 75 | +and replace username, password, and hostname with values matching |
| 76 | +your environment. |
| 77 | +```csharp |
| 78 | +string connection_string = "Driver={PostgreSQL Unicode};Server=testcluster.cratedb.net;Port=5432;Sslmode=require;Uid=admin;Pwd=password"; |
| 79 | +``` |
| 80 | + |
| 81 | + |
| 82 | +[.NET Framework Data Provider for ODBC]: https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/data-providers#net-framework-data-provider-for-odbc |
| 83 | +[System.Data.Odbc]: https://learn.microsoft.com/en-us/dotnet/api/system.data.odbc |
0 commit comments