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);
            }
        }
    }
}

4 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.

Leave a Reply

Your email address will not be published. Required fields are marked *