Advertisement
napland

ODBC to DB2 Connection and Query Example

Jul 24th, 2016
482
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.24 KB | None | 0 0
  1. using UnityEngine;
  2. using System;
  3. using System.Text;
  4. //C:\Program Files\IBM\SQLLIB\BIN may need to be in environment path.
  5. using System.Data.Odbc;
  6. public class DB2Service : MonoBehaviour
  7. {
  8.     void Start()
  9.     {
  10.         Test();
  11.     }
  12.  
  13.         void Test()
  14.     {      
  15.         // Set up a connection string. The format is pretty specific, just change the YOUR...HERE to real values.
  16.         string connectionStringODBC =
  17.             "Driver={IBM DB2 ODBC DRIVER};Database=YOURDATABASENAMEHERE;Hostname=localhost;Port=50000;Protocol=TCPIP;Uid=YOURUSERNAMEHERE;Pwd=YOURPASSWORDHERE;";
  18.         // Make the connection and open it
  19.         OdbcConnection odbcCon = new OdbcConnection(connectionStringODBC);
  20.         odbcCon.Open();
  21.  
  22.         // Try out a simple command/query - make sure to change SOMEREALTABLENAME to your table's name
  23.         OdbcCommand command = new OdbcCommand("SELECT COUNT(*) FROM SOMEREALTABLENAME", odbcCon);
  24.         int count = Convert.ToInt32(command.ExecuteScalar());
  25.         Debug.Log("count: " + count);
  26.  
  27.         // Try a full select query
  28.         OdbcCommand command2 = new OdbcCommand("SELECT * FROM SOMEREALTABLENAME", odbcCon);
  29.         StringBuilder sb = new StringBuilder();
  30.         using (OdbcDataReader reader = command2.ExecuteReader())
  31.         {
  32.             // Add the column names to the string builder
  33.             for (int i = 0; i < reader.FieldCount; i++)
  34.             {
  35.                 sb.Append(reader.GetName(i));
  36.                 if (i < reader.FieldCount - 1)
  37.                     sb.Append(",");
  38.             }
  39.  
  40.             sb.AppendLine();
  41.  
  42.             // Step through the query's results and add those to the string builder.
  43.             while (reader.Read())
  44.             {
  45.                 // Separate each column with a comma
  46.                 for (int i = 0; i < reader.FieldCount; i++)
  47.                 {
  48.                     sb.Append(reader.GetString(i).Trim());
  49.                     if (i < reader.FieldCount - 1)
  50.                         sb.Append(",");
  51.                 }
  52.                 sb.AppendLine();
  53.  
  54.             }
  55.  
  56.             // Output the results to the console
  57.             Debug.Log(sb.ToString());
  58.         }
  59.  
  60.         // Close up that connection!
  61.         odbcCon.Close();
  62.     }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement