Connect a Java database via C# .Net

I am currently working on a software project that involves connecting to a Java database (Apache Derby) via a .Net C# application.  I googled a lot and nothing helps. Finally, I decided to find my own one, and managed to get it up running. Here is my solution to share:

Tools we need:

using java.lang;
using java.sql;
using System;
using org.apache.derby.jdbc;

namespace DerbyDB
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();

                DriverManager.registerDriver(new EmbeddedDriver());
                var derbyDBConnection = DriverManager.getConnection("jdbc:derby:C:/DerbyDB");
                if (derbyDBConnection != null)
                {
                    Statement st = derbyDBConnection.createStatement();
                    ResultSet rs = st.executeQuery("select * from eventlog");
                    while (rs.next())
                    {
                        Console.WriteLine(rs.getInt("ID"));
                        Console.WriteLine(rs.getTime("EVENT_DATE"));
                        Console.WriteLine(rs.getString("EVENT_MESSAGE"));
                    }
                    st.close();
                    derbyDBConnection.close();
                }
            }
            catch (java.lang.Exception e)
            {
                Console.WriteLine(e);
            }
        }
    }
}

6 thoughts on “Connect a Java database via C# .Net”

  1. Hi nick.

    I’m trying your solution but I run into a problem.
    I get un error on using org.apache.derby.jdbc.

    Am I missing some references?

    Could you help?

    1. It seems you didn’t reference the DLLs correctly, and .Net application couldn’t find the assembly.
      When you use IKVM, it will generate a bunch of DLLs.

          1. Thanks for your trouble.

            I’ve tested it (error on DriverManager.getConnection(“jdbc:derby:C:/TempRH_DB”)):
            java.sql.SQLException: No suitable driver found for jdbc:derby:C:/TempRH_DB

            Any ideas?

          2. I think it’s your derby database version. Which version are you using?
            The demo I created is using 10.13.1.1.

            If you use different version, you may need to re-generate all the DLLs by yourself.

Leave a Reply

Your email address will not be published.