How to connect Sybase DB using C#
I needed to write a very short C# program to access a Sybase ASE database and extract some information.
First had to download the appropriate version of ASE. It contains a directory called \archives\odbc. There is a setup.exe. Just run it.
Now there a new driver available:
There is no need to add a data source to access ASE from an ODBC connection using C#. Just went there to check whether the driver was properly installed.
Then just create a program connecting to ASE using the following connection string:
Driver={Adaptive Server Enterprise};server=THE_HOSTNAME;port=2055;db=THE_DB_NAME;uid=sa;pwd=THE_SA_PASSWORD;
If you omit the db=… part, you’ll just land in the master database.
With this connection, you can then execute statements.
Here a sample code:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Odbc; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { String errorMsg; OdbcConnection con = Connect("sa", "sa.pwd", "2055", "192.168.190.200", "mydb", out errorMsg); Console.WriteLine(errorMsg); if (con != null) { Console.WriteLine("In database {0}", con.Database); OdbcCommand command = con.CreateCommand(); command.CommandText = "SELECT name FROM sysobjects WHERE type='U' ORDER BY name"; OdbcDataReader reader = command.ExecuteReader(); int fCount = reader.FieldCount; for (int i = 0; i < fCount; i++) { String fName = reader.GetName(i); Console.Write(fName + ":"); } Console.WriteLine(); while (reader.Read()) { for (int i = 0; i < fCount; i++) { String col = reader.GetValue(i).ToString(); Console.Write(col + ":"); } Console.WriteLine(); } reader.Close(); command.Dispose(); Close(con); Console.WriteLine("Press any key too continue..."); Console.ReadLine(); } } private static OdbcConnection Connect(String strUserName, String strPassword, String strPort, String strHostName, String dbName, out String strErrorMsg) { OdbcConnection con = null; strErrorMsg = String.Empty; try { String conString = "Driver={Adaptive Server Enterprise};server=" + strHostName + ";" + "port=" + strPort + ";db=" + dbName + ";uid=" + strUserName + ";pwd=" + strPassword + ";"; con = new OdbcConnection(conString); con.Open(); } catch (Exception exp) { con = null; strErrorMsg = exp.ToString(); } return con; } private static void Close(OdbcConnection con) { con.Close(); } } }
That was really easy ! Not that it’d have been more difficult with Java or PHP, but I’d have expected to waste ours making mistakes and trying to debug it…