2014-04-13 3 views
0

MySql 데이터베이스에서 작동해야하는 응용 프로그램을 만들고 있습니다. 이유를 알고 나는이 오류를 얻고있다, 나는 그나마 내 테이블 중 하나에서 열 "priemer"가있는 경우개체 참조가 개체의 인스턴스로 설정되지 않았습니다. - MySqlCommand

public void rtMean() 
    { 
     MySqlConnection conect = con.ConnectToMySQL(); 
     MySqlDataReader reader; 
     MySqlDataReader readerMean; 

     // OVERENIE, CI UZ STLPEC PRIEMER EXISTUJE 

     string query1 = "SELECT * FROM feture"; 
     MySqlCommand cmd1 = new MySqlCommand(query1, conect); 
     reader = cmd1.ExecuteReader(); 

     for (int j=0; j < reader.FieldCount; j++) 
     { 
      if (reader.GetName(j) == "priemer") 
      { 
       break; 
      } 
      else 
      { 
       reader.Close(); 
       cmd1.Cancel(); 
       string queryAlterTable = "ALTER TABLE feture ADD COLUMN priemer FLOAT NOT NULL"; 
       MySqlCommand cmd = new MySqlCommand(queryAlterTable, conect); //here I am getting the error 
       cmd.ExecuteScalar(); 
      } 
     } 

이 chceck해야

Object reference not set to an instance of an object 

가 여기 내 코드입니다. 예이면 끝나야하고, 없으면 내 테이블을 "priemer"라는 새 열로 변경해야합니다.

감사합니다.

편집 : STACK - TRACE : 내가 제대로 이해한다면 첫 번째 필드의 이름되지 않은 경우

at MySql.Data.MySqlClient.MySqlCommand.ExecuteScalar() 
    at WindowsFormsApplication1.ClusteringReady.rtMean() in c:\Users\Martin\Desktop\CLUSTER\WindowsFormsApplication1\ClusteringReady.cs:line 43 
    at WindowsFormsApplication1.Form1.clusterize_Click(Object sender, EventArgs e) in c:\Users\Martin\Desktop\CLUSTER\WindowsFormsApplication1\Form1.cs:line 130 
    at System.Windows.Forms.Control.OnClick(EventArgs e) 
    at System.Windows.Forms.Button.OnClick(EventArgs e) 
    at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) 
    at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) 
    at System.Windows.Forms.Control.WndProc(Message& m) 
    at System.Windows.Forms.ButtonBase.WndProc(Message& m) 
    at System.Windows.Forms.Button.WndProc(Message& m) 
    at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) 
    at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) 
    at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) 
    at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) 
    at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) 
    at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) 
    at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) 
    at System.Windows.Forms.Application.Run(Form mainForm) 
    at WindowsFormsApplication1.Program.Main() in c:\Users\Martin\Desktop\CLUSTER\WindowsFormsApplication1\Program.cs:line 19 
    at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) 
    at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) 
    at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 
    at System.Threading.ThreadHelper.ThreadStart_Context(Object state) 
    at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) 
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 
    at System.Threading.ThreadHelper.ThreadStart() 
+0

예외의 스택 추적은 무엇입니까? – adrianbanks

+0

@adrianbanks 제 편집을 확인해주세요. –

답변

1

확인 필요 여부를 확인하기 위해 더 나은 방법이있다 결과 집합의 첫 번째 셀에 CNT = 0이 생기면 ALTER TABLE 쿼리를 다른 현명한 방법으로 실행해야합니다. for 루프를 실행할 필요가 없습니다.

+0

이 오류가 발생합니다. SQL 구문에 오류가 있습니다. 올바른 문법이 'IF NOT EXISTS (SELECT priemer FROM feture)'근처에서 사용하도록 MySQL 서버 버전에 해당하는 매뉴얼을 확인하십시오. 1 행의 "ALTER TABLE feture ADD COLUMN pr" –

+0

@MartinNemeth, 제 편집을보십시오. – NeverHopeless

1

그래서, priemer 당신은 독자를 닫으려고 새 열을 만듭니다. 하지만 루프를 멈추지 않으므로 독자가 닫힌 상태에서 두 번째 루프를 실행합니다.

SELECT COUNT(*) as cnt FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'feture' 
AND COLUMN_NAME = 'premier' 

과 같은 경우

당신은이 쿼리를 실행할 수 있습니다, 테이블이 포함 여부 열이 아래의 설명에 따라

bool found = false; 
using(MySqlConnection cnn = new MySqlConnection(".....................")) 
{ 
    cnn.Open(); 
    DataTable dt = cnn.GetSchema("COLUMNS", new string[] {null,null,"feture", null}); 
    foreach(DataRow r in dt.Rows) 
    { 
     if(r["COLUMN_NAME"].ToString() == "priemer") 
     { 
      found = true; 
      break; 
     } 
    } 
    if(!found) 
    { 
     .. create your column here 
    } 
} 
+0

그래서 루프를 중단하지 않으면 중단 할 수 있습니까? col로 테이블 col을 검사하고 싶습니다. "priemer"라는 열을 발견하면 루프를 멈추게됩니다. –

+0

위의 예는 스키마 데이터 만 필요할 때 테이블의 모든 레코드를 검색하지 않도록합니다. GetSchema 메서드의 도움을 받아 독자가 반복하는 테이블을 변경하지 않아야합니다. 확실하지는 않지만 위험한 것으로 보입니다. 루프를 끝낸 후 플래그를 설정하고 테이블을 변경하십시오. – Steve

관련 문제