[英]Cannot implicitly convert type 'System.Data.SqlClient.SqlDataReader' to 'System.Data.OracleClient.OracleDataReader' in C#
[英]C# - Cannot implicitly convert type 'IBM.Data.DB2.iSeries.iDB2DataReader' to 'System.Data.SqlClient.SqlDataReader'
我正在一個Ranorex項目中工作,但這不是Ranorex的特定問題。 我需要打開與AS400 DB2數據庫的連接,然后對它運行SQL查詢。
我有成功打開連接並返回SQL查詢結果的代碼。
iDB2Connection cn = new iDB2Connection("Data Source=as400_DB;User ID=CLIENT;Password=CLIENT;Default Collection=XXXXXX;Naming=System");
cn.Open();
iDB2Command cmd = new iDB2Command("select count(*) from ABC_table where xxxx = 'WC' AND xxxx = 'L302328'", cn);
int count = Convert.ToInt32(cmd.ExecuteScalar());
Report.Log(ReportLevel.Info, "count", count.ToString());
cn.Close();
在代碼中,第二種方法調用了第一種方法來打開連接,然后允許第二種方法運行SQL命令,但是出現以下錯誤:
無法將類型'IBM.Data.DB2.iSeries.iDB2DataReader'隱式轉換為'System.Data.SqlClient.SqlDataReader'
在第一個方法中的“返回新的iDB2Connection(cn.ToString())”點處。
public static class sQlHelper
{
private static SqlConnection sQlConnect()
{
iDB2Connection cn = new iDB2Connection("Data Source=as400_DB;User ID=CLIENT;Password=CLIENT;Default Collection=XXXXXX;Naming=System");
return new iDB2Connection(cn.ToString());
}
public static void validateResult()
{
var myConnection = sQlConnect();
myConnection.Open();
string sqlStatementForCheckHeaders = "select count(*) from ABC_table where xxxx = 'WC' AND xxxx = 'L302328'";
int count = Convert.ToInt32(cmd.ExecuteScalar());
SqlDataReader myReader = null;
iDB2Command myCommand = new iDB2Command(sqlStatementForCheckHeaders, myConnection);
myReader = myCommand.ExecuteReader();
while(myReader.Read())
{
Console.WriteLine(myReader["Column1"].ToString());
Console.WriteLine(myReader["Column2"].ToString());
}
myConnection.Close();
}
}
我無法鍛煉如何解決問題,也無法找到有關錯誤本身的任何信息。 我很感謝人們可以提供的任何支持/建議。
您在該代碼中有兩個缺陷。 我認為您正在將System.Data.SqlClient
命名空間與IBM.Data.DB2.iSeries
混淆。
首先,您的sQlConnect
方法被聲明為返回SqlConnection
,但返回一個iDB2Connection
。 修正簽名:
private static iDB2Connection sQlConnect() // returns a IDB2Connection!
{
return new iDB2Connection("Data Source=as400_DB;User ID=CLIENT;Password=CLIENT;Default Collection=XXXXXX;Naming=System");
}
第二條錯誤消息是由myReader
的錯誤聲明引起的。 由於myCommand
是一個iDB2Command
(而不是 SqlCommand
),因此其ExecuteReader()
方法返回一個IBM.Data.DB2.iSeries.iDB2DataReader
,而不是SqlDataReader
。
因此,您只需要更改myReader
的聲明即可:
iDB2Command myCommand = new iDB2Command(sqlStatementForCheckHeaders, myConnection);
// use the correct type (or var)
iDB2DataReader myReader = myCommand.ExecuteReader();
while(myReader.Read()) { ... }
首先 ,更新您的方法定義以返回iDB2Connection
而不是SQLConnection
private static iDB2Connection sQlConnect()
{
return new iDB2Connection("Data Source=as400_DB;User ID=CLIENT;Password=CLIENT;Default Collection=XXXXXX;Naming=System");
}
其次
cmd.ExecuteScalar();
無法轉換為iDB2DataReader
您正嘗試返回單個值而不是datareader,因此請使用類似
int hasRecords = (int)cmd.ExecuteScalar();
我似乎無法將這兩個答復都標記為正確答案,但是RenéVogt和Ehsan Ullah Nazir的帖子都為我的問題提供了解決方案。 感謝你們倆。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.