2016-03-25 12 views
-1

私はこれで初めてです。私は、datareader経由でsqlデータベースを読み込むc#コンソールプログラムを作成し、いずれかの行がクエリと一致する場合はステートメントを表示し、SQLの更新クエリでこれらの行を更新します。しかし、私はこのエラーを修正する方法を理解することはできません。ここに私のコードです。助けに感謝します。ありがとう。名前 "ABC ..."は現在のコンテキストに存在しません。 C#SQLコンソールプログラム

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Data.SqlClient; 

namespace emailsend 
{ 
    class Program 
    { 
     #region Connection String 
     static private SqlConnection connection = new SqlConnection("Data Source=server;Initial Catalog=dbTrainning;User ID=user;Password=123"); 
     #endregion   

     static void Main(string[] args) 
     { 
      #region SQL Select Unsent Query 
      string Sql = "SELECT * FROM People where Visits is Null;"; 
      SqlCommand cmd = new SqlCommand(Sql, connection); 
      #endregion 

      #region Open DB Connection 
      if (connection.State != ConnectionState.Open) 
      { 
       connection.Open(); 
      } 
      #endregion 
      SqlDataReader DR = cmd.ExecuteReader(); 

      #region Try Catch Block 
      try 
      {    
       while (DR.Read()) 
       { 
        #region Fetching DB data 
        DateTime TimeStamp = (DateTime)DR["ExceptionDate"]; 
        string VNumber = (string)DR["VisitNumber"]; 
        Console.Write("Total Visits = " +VNumber "\n"); 
        #endregion 
        DR.Close(); 
       } 

       cmd = new SqlCommand("UPDATE People SET Visits = '0' WHERE VisitNumber = '" + VNumber + "'", connection); //The name 'VNumber' does not exist in the current context 
       cmd.ExecuteNonQuery(); 
      } 
      catch (SqlException exception) 
      { 
       Console.Write(exception); 
      } 
      finally 
      { 
       connection.Close(); 
      } 
      #endregion 
     } 
    } 
} 
+0

あなたは{ 'の内部で宣言された変数にアクセスできるようにしたい場合は、'必要にこれらの変数へのアクセスを得るために}デバッガを使用しただけでなく、重要な用語 'SCOPE'を理解する場所ですループの外側の '変数'を宣言/初期化するか、あるいは '試みる'など... – MethodMan

答えて

0

あなたはwhileループでVNumberを作成し、それが外に見えないからです。それを試してください:

try 
{ 
    string VNumber = null;  //outside the loop 
    while (DR.Read()) 
    { 
     #region Fetching DB data 
     DateTime TimeStamp = (DateTime)DR["ExceptionDate"]; 
     VNumber = (string)DR["VisitNumber"]; 
     Console.Write("Total Visits = " +VNumber "\n"); 
     #endregion 
     DR.Close(); 
    } 

    cmd = new SqlCommand("UPDATE People SET Visits = '0' WHERE VisitNumber = '" + VNumber + "'", connection); //The name 'VNumber' does not exist in the current context 
    cmd.ExecuteNonQuery(); 
} 
+0

それは小さな問題を解決しました。私が参照していた変数がループ内で作成され、初期化されたことがわかりました。これはクラス/メソッドの始めに**グローバル変数**として初期化されているはずです。 –

関連する問題