C#连接db2数据库的实现方法

通过OLE DB for DB2驱动
复制代码 代码如下:

string strSql = @"select phone_no from no_store where id<5";
            string strConn = "Provider=IBMDADB2;Data Source=数据库名;UID=用户名;PWD=密码;";
            using (OleDbConnection conn = new OleDbConnection(strConn))
            {
                OleDbCommand cmd = new OleDbCommand(strSql, conn);
                try
                {
                    conn.Open();
                    OleDbDataAdapter adp = new OleDbDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    adp.Fill(ds);
                    DataTable dt = ds.Tables[0];
                    if (dt != null)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            Console.WriteLine("电话" + i + ":" + dt.Rows[i][0].ToString());
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            Console.Read();

通过IBM提供的IBM.data.DB2.DLL
复制代码 代码如下:

string strSql = @"select phone_no from no_store where id<5";
            string strConn = "Database=数据库名;UID=用户名;PWD=密码;";
            using (DB2Connection conn = new DB2Connection(strConn))
            {
                DB2Command cmd = new DB2Command(strSql, conn);
                try
                {
                    conn.Open();
                    DB2DataAdapter adp = new DB2DataAdapter(cmd);
                    DataSet ds = new DataSet();
                    adp.Fill(ds);
                    DataTable dt = ds.Tables[0];
                    if (dt != null)
                    {
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            Console.WriteLine("电话" + i + ":" + dt.Rows[i][0].ToString());
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            Console.Read();

小结
(1)两种方式的数据库操作对象可以参考c#连接sqlserver的数据库对象。
(2)如果db2数据库在远程服务器,连接字符串中的数据库名、用户名、密码为db2编目到本地的数据库名、用户名、密码。
(3)使用IBM.Data.DB2,必须引用该程序集。

你可能感兴趣的:(C#连接db2数据库的实现方法)