2013-11-14 4 views
1

나는 내 mysql 데이터베이스의 열 평균을 계산하고 변수에 저장하려고하므로 정규 분포에 대한 분산을 찾는 등의 추가 계산에 사용할 수 있습니다. 어떻게하면 코드를 실행할 때 오류가 표시되지 않지만 데이터베이스를 읽지는 않습니다. 코드에 체크 포인트를 추가하여 코드가 얼마나 진행되는지 확인했습니다. 프로그램이 나에게 체크 포인트 2 이전에 "데이터베이스를 선택하지 않았습니다."라는 예외 메시지를 보여줍니다. 어떤 도움을 주시면 감사하겠습니다.Windows 용 mysql 데이터베이스에서 열의 평균 계산 양식 응용 프로그램

decimal proteinAvg; 

     string myConnection = "datasource=localhost;port=3306;username=root;password=root" 
     string Query = "SELECT AVG(Protein) AS proteinAvg FROM nutritioncalculator"; 
     MySqlConnection myConn = new MySqlConnection(myConnection); 
     MySqlCommand cmdDatabase = new MySqlCommand(Query, myConn); 
     MySqlDataReader myReader; 


try 
{ 
    myConn.Open(); 
    //checkpoint1 
    MessageBox.Show("connected"); 
    myReader = cmdDatabase.ExecuteReader(); 
    //Checkpoint2 

    MessageBox.Show("connected"); 
    while (myReader.Read()) 
    { 
     //checkpoint3 
     MessageBox.Show("connected"); 
     proteinAvg = (decimal) myReader["proteinAvg"]; 
     MessageBox.Show("Your protein intake should be around" + proteinAvg); 
    } 
+0

귀하의 [연결 문자열 (http://dev.mysql.com/doc/refman/5.0/en/connector-net-programming-connecting-connection-string.html) 잘못된 것입니다. – Brian

답변

1

ConnectionString 개체에 데이터베이스 이름을 지정하지 않았습니다.

string myConnection = "datasource=localhost;Database=mydatabase;port=3306;username=root;password=root"; 

]을 참조 MySQL Connection String

+0

'MySql'에서 그들은'Initial Catalog'를 사용하지 않고'Database'를 사용합니다. – Brian

+0

고맙습니다. 지금은 잘 작동합니다. –

+0

@ 브라이언 : 고마워요. –

0

코드 문제 몇 가지가 여기에있다이 링크를, 그리고 내 대답을 강조합니다

이보십시오.

decimal proteinAvg; 
// MySql uses 'database' and not 'Initial Catalog' like Sql does. 
string myConnection = string myConnection = "datasource=localhost;Database=mydatabase;port=3306;username=root;password=root"; // MySql uses 'database' to define the DB name. 
string Query = "SELECT AVG(Protein) AS proteinAvg FROM nutritioncalculator"; 

// Wrap your connection and command objects in 'using' blocks. 
// Both implement IDisposable and will be managed by GC once 
// they fall out-of-scope. 
using (MySqlConnection myConn = new MySqlConnection(myConnection)) 
{ 
    using (MySqlCommand cmdDatabase = new MySqlCommand(Query, myConn)) 
    { 
     MySqlDataReader myReader; 
     try 
     { 
     myConn.Open(); 
     //checkpoint1 
     MessageBox.Show("connected"); 
     myReader = cmdDatabase.ExecuteReader(); 
     //Checkpoint2 

     MessageBox.Show("connected"); 
     while (myReader.Read()) 
     { 
      //Checkpoint3 
      MessageBox.Show("connected"); 
      proteinAvg = (decimal) myReader["proteinAvg"]; 
      MessageBox.Show("Your protein intake should be around" + proteinAvg); 
     } 
     } 
    } 
} 
+0

@Brain - try catch 블록에서 사용할 때 cmdDatabase와 myReader 둘 다 scoup에서 벗어납니다. –

+0

@YashPatel - 예, 맞습니다. 내 대답을 편집하고'try/catch'를 움직 이도록하겠습니다. – Brian

관련 문제