快捷搜索:

C#怎样连接DB2数据库?

【IT168 技术文章】

项目中遇到的。net(C#) 连接DB2问题,解决了,和大家分享一下。

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Data.Odbc;

using System.Data.SqlClient;

using System.Data;

namespace DB2Import

{

class Program

{

static void Main(string[] args)

{

OdbcConnection DB2Connection = new OdbcConnection("Dsn=DataSourceName;uid=UserName;pwd=mismidas");//创建DB2的数据源连接

//这里是用数据源连接的

//DataSourceName 数据源名称

//UserName 用户名

//pwd 用户口令

//OdbcCommand

SqlConnection conSql = new SqlConnection("Data Source=oadatabase\\userdb2005;Initial Catalog=GongChengGuanLi;Persist Security Info=True;User ID=sqlUserName;Password=SqlPassword");//Sql2005的数据库连接

DB2Connection.Open();//打开DB2的数据源连接

SqlDataAdapter ZDAdapter = new SqlDataAdapter(new SqlCommand("Select * from SCD_GXDY_XGJL", conSql));

SqlCommandBuilder myCommandBuilder = new SqlCommandBuilder(ZDAdapter);

DataSet ZDDataSet = new DataSet();

ZDAdapter.Fill(ZDDataSet, "SCD_GXDY_XGJL");

for (int i = 0; i < ZDDataSet.Tables["SCD_GXDY_XGJL"].Rows.Count; i++)

{

Console.WriteLine("importing "+i+" .....");

DataRow row = ZDDataSet.Tables["SCD_GXDY_XGJL"].Rows[i];

int KHDM = 0;

try

{

KHDM = int.Parse("" + row["KHDM"]);

}

catch (Exception paresException)

{

KHDM = 0;

}

//KHDM

if ("" + row["KHDM"] != "" && KHDM!=0)

{

OdbcCommand cmdSelect = new OdbcCommand("Select CCUST,CNME,CTYPE,CLOC,CMDPFX from V6tstF.RCM where CCUST=" +KHDM+ "", DB2Connection);

OdbcDataReader odbcReader= cmdSelect.ExecuteReader();

if (odbcReader.Read())//从DB2中读取数据

{

row["CNME"] = ""+odbcReader["CNME"];

row["CTYPE"] = "" + odbcReader["CTYPE"];

row["CLOC"] = "" + odbcReader["CLOC"];

row["CMDPFX"] = "" + odbcReader["CMDPFX"];

}

odbcReader.Close();

}

}

Console.WriteLine("Updating ....");

ZDAdapter.Update(ZDDataSet, "SCD_GXDY_XGJL");

Console.WriteLine("Commplete!");

Console.WriteLine("Press any Key to Exit!");

Console.Read();

}

}

}

但可能有朋友要问了,DB2的数据源是怎么建立的,安装IBM DB2 RUN-Time Client.

然后运行“從屬站架構輔助程式”来添加数据源。(剩下就是下一步了啊)
 

您可能还会对下面的文章感兴趣: