chequer-io / JDBC.NET

It is a wrapper that allows you to use JDBC drivers in ADO.NET
MIT License
33 stars 11 forks source link

Sample for using JDBC.NET with Dapper #24

Closed kellerd closed 1 year ago

kellerd commented 1 year ago

Curious if you would have a sample of how to use JDBC.NET with say something like Dapper.

Currently running into trouble when binding parameters using their sample.

public class Dog
        {
            public int Age { get; set; }
            public string Id { get; set; }
        }

var dog = connection.Query<Dog>("select Age = @Age, Id = @Id", new { Age = 7, Id = "Mr. Dog" });

Would give the error: The given key was not present in the dictionary. at JDBC.NET.Data.JdbcParameterCollection.Contains(String parameterName) at Dapper.DbString.AddParameter(IDbCommand command, String name) in //Dapper/DbString.cs:line 65 at ParamInfo9e274bac-0a53-4256-bf31-c91b703ba22c(IDbCommand, Object) at Dapper.CommandDefinition.SetupCommand(IDbConnection cnn, Action`2 paramReader) in //Dapper/CommandDefinition.cs:line 128 at Dapper.SqlMapper.QueryImpl[T](IDbConnection cnn, CommandDefinition command, Type effectiveType)+MoveNext() in //Dapper/SqlMapper.cs:line 1091 at System.Collections.Generic.List1..ctor(IEnumerable1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source) at Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable1 commandTimeout, Nullable`1 commandType) in //Dapper/SqlMapper.cs:line 734

tcables commented 1 year ago

JDBC does not support named parameters.

https://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html

It accepts prepared statements with positional arguments.

Use: var part = connection.Query<Part>("SELECT * FROM Parts WHERE CODE = ? and DESC = ?", new { Code = 7, Desc = "blue" });

NB: Argument names dont matter. you can var part = connection.Query<Part>("SELECT * FROM Parts WHERE CODE = ? and DESC = ?", new { foo = 7, bar = "blue" });

I just tested that, and it works.

kellerd commented 1 year ago

Perfect, thanks!

Just an FYI for others coming in. Dapper seemingly has issues if the variable names match the anonymous class names. CODE and Code would work, but CODE and CODE wouldn't.