2012-02-12 2 views
0

좋아요. 기본적으로 PhpMyAdmin에서 MySQL 테이블을 만들었습니다. 로컬 호스트, 사용자 이름 루트 및 암호 없음.Visual C# Express 2008과의 MySQL 연결

Visual Express 2008의 C#을 기반으로하는 Windows 응용 프로그램에서 작업하고 있습니다. 다음과 같은 코드를 사용하여 MySQL에서 데이터를 저장 /로드 할 수 있습니다 (이 링크로 이동하려면/tuts를 따라 가야합니다. 그러나 이것이 이론적으로 MySQL @ phpmyadmin에 어떻게 연결될 수 있는지 모르겠다. 나는 PhpmyAdmin 데이터베이스와 참조에서 다운로드하거나 스크립트 또는 뭔가 플러그인으로 추가 할 파일이 필요 없다는 것을 의미합니까? Tottaly lost ..) :

 String connString = "SERVER = localhost; DATABASE = request; User ID = root; ID =; UserName =; Date =; Type =; Rules =;"; 
     MySqlConnection mcon = new MySqlConnection(connString); 
     String command = "SELECT * FROM requesttcw"; 
     MySqlCommand cmd = new MySqlCommand(command, mcon); 
     MySqlDataReader reader; 

     try 
     { 
      mcon.Open(); 
      cmd.ExecuteNonQuery(); 
      reader = cmd.ExecuteReader(); 
      cmd.CommandType = System.Data.CommandType.Text; 
      while (reader.Read() != false) 
      { 
       Console.WriteLine(reader["ID"]); 
       Console.WriteLine(reader["ClanName"]); 
       Console.WriteLine(reader["Date"]); 
       Console.WriteLine(reader["Type"]); 
       Console.WriteLine(reader["Rules"]); 

      } 

      Console.ReadLine(); 

     } 
     catch (Exception) 
     { 
      MessageBox.Show("ERROR: There was an error trying to connect to the DB!"); 
      return; 
     } 
     cmd.CommandText = "INSERT INTO requesttcw (ClanName, Date, Type, Rules) VALUES ('" + textBox1.Text + "', '" + textBox2.Text + "', '" + textBox3.Text + "', '" + richTextBox1.Text + "' LIMIT 1)"; 

     try 
     { 
      cmd.ExecuteNonQuery(); 
      MessageBox.Show("You're Request Has Been Posted!"); 
     } 
     catch (Exception ex) 
     { 
      string message = ("ERROR: There was an error submitting your form!" + ex + ""); 
      DialogResult result = MessageBox.Show(message, "ERROR", MessageBoxButtons.RetryCancel, MessageBoxIcon.Question); 

      switch (result) 
      { 
       case DialogResult.Retry: 
        Application.Restart(); 
        break; 
       case DialogResult.Cancel: 
        this.Close(); 
        break; 
      } 
     } 

실행할 때 내 데이터를 입력하고 단추를 클릭하면 온라인에이 오류가 표시됩니다 (MySqlConnection mcon = new MySqlConnection (connString);).* 키워드가 지원되지 않습니다. 매개 변수 이름 : id *

완벽하게 MySQL에 연결하는 방법을 알려주십시오. 또한 MySQL Connector를 다운로드하고 mysql.data.dll 파일을 참조했습니다. 그래서 그 부분은

답변

3

는 다음 연결 문자열을 시도 ... 너무 수행됩니다

string connString = "Server=localhost;Database=request;Uid=root;Pwd=;"; 

또한 코드를 청소 시도에 그들을 배치하여 제대로 같은 SQL 연결 및 명령 등의 IDispoable 자원을 폐기하고 있는지 확인 using 문. 또한이 준비된 문을 사용하거나 (눈 깜짝 할 사이에) 코드가 SQL 주입 공격에 취약하고 데이터베이스가 매우 빠르게 파괴 할 수 있는지 확인하십시오

예외 처리에 관한 지금까지로
string connString = "Server=localhost;Database=request;Uid=root;Pwd=;"; 

using (MySqlConnection mcon = new MySqlConnection(connString)) 
using (MySqlCommand cmd = mcon.CreateCommand()) 
{ 
    mcon.Open(); 
    cmd.CommandText = "SELECT * FROM requesttcw"; 
    using (MySqlDataReader reader = cmd.ExecuteReader()) 
    { 
     while (reader.Read()) 
     { 
      Console.WriteLine(reader["ID"]); 
      Console.WriteLine(reader["ClanName"]); 
      Console.WriteLine(reader["Date"]); 
      Console.WriteLine(reader["Type"]); 
      Console.WriteLine(reader["Rules"]); 
     } 
    } 
} 

using (MySqlConnection mcon = new MySqlConnection(connString)) 
using (MySqlCommand cmd = mcon.CreateCommand()) 
{ 
    mcon.Open(); 
    cmd.CommandText = "INSERT INTO requesttcw (ClanName, Date, Type, Rules) VALUES (@ClanName, @Date, @Type, @Rules)"; 
    cmd.Parameters.AddWithValue("@ClanName", textBox1.Text); 

    // Warning if the Date column in your database is of type DateTime 
    // you need to parse the value first, like this: 
    // cmd.Parameters.AddWithValue("@Date", Date.Parse(textBox2.Text)); 
    cmd.Parameters.AddWithValue("@Date", textBox2.Text); 
    cmd.Parameters.AddWithValue("@Type", textBox3.Text); 
    cmd.Parameters.AddWithValue("@Rules", richTextBox1.Text); 

    cmd.ExecuteNonQuery(); 
} 

, 필자는 예제에서 생략했지만 try/catch 블록에 using 문을 넣을 수 있습니다.

+0

대런 디미트로프 감사합니다! 그게 다 고쳐! !!!!! 나는 이것을 알아 내려고 노력하는 하루처럼 보냈지 만, 당신은 그저 나를 도왔습니다 !! : D – DamageDz

+0

@DamageDz, 좋아요, 제가 도울 수있어서 기쁩니다. 이 게시물이 도움이 되었다면 [대답으로 표시] (http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)를 고려해 보시기 바랍니다. 그것. –

+0

@vucetica, ADO.NET은 연결 풀을 관리합니다. 따라서 두 번째'using' 블록 **은 데이터베이스에 새로운 연결 **을 열지 않습니다. [연결 풀] (http://dev.mysql.com/doc/refman/5.0/en/connector-net-programming-connection-pooling.html)에서 기존 연결을 그립니다. using 문의 끝에서 연결은 닫히지 않지만 재사용하기 위해 연결 풀로 리턴됩니다. 두 번째 발언에 관한 한, 나는 나의 신청서에있는 우려를 분리하는 것을 선호한다. 두 사람은 일반적으로 나중에 완전히 재사용 할 수있는 완전히 별개의 두 가지 방법으로 이동합니다. –

0

connString 변수에 ID =; (User ID = root 이후) 변수가 있습니다.

0

연결 문자열은 응용 프로그램과 MySQL 서버 간의 연결을 지정합니다. 연결 문자열에 실수를했기 때문에 오류가 발생했습니다. 다음 내용이 귀하의 필요를 더 잘 충족시킬 것이라고 생각합니다.

Server=localhost;Database=request;Uid=myUsername;Pwd=myPassword;