2014-12-05 8 views
1

C# 응용 프로그램에서 SQL 데이터베이스에 삽입하려고합니다.C#에서 SQL 데이터베이스에 삽입

나는 약간의 문서를 읽고, 내가 생각했던 것에서 생각해 냈다. 실제로 사용자가 자신의 데이터를 입력하고 제출 버튼을 누르면 잠시 멈추고 "SqlException"을 표시하고 연결할 수 없다는 것에 대해 언급합니다.

연결 문자열을 올바르게 사용했는지 확신 할 수 없어 도움을 요청하고 있습니다.

이 내가 연결 쿼리를 구축하기 위해 사용되는 방법은 다음과 같습니다

private void btn_Submit_Click(object sender, EventArgs e) 
{ 
    if (isValidData()) 
    { 
     //MessageBox.Show("Valid", "All Entries Were Valid!"); 

     //CONVERT FORM VALUES AND STORE IN VARIABLES TO SEND TO MYSQL QUERY 
     DateTime saleTime = saleDatePicker.Value; 
     Decimal price = Convert.ToDecimal(txt_Price.Text); 
     string customerName = txt_CustomerName.Text; 
     string customerPhone = txt_CustomerPhone.Text; 
     string description = rTxt_Description.Text; 

     //Build Query string 
     string query = "INSERT into SALES VALUES ('" + saleTime + "','" + 
      price + "','" + customerName + "','" + customerPhone + "','" + 
      description + "');"; 

     insertValues(query); 

    } 
} 
private void insertValues(string q) 
{ 
    SqlConnection sqlConnection1 = new SqlConnection("Server=host;Database=dbname;User Id=username;Password=password;"); 
    SqlCommand cmd = new SqlCommand(); 
    SqlDataReader reader; 

    cmd.CommandText = q; 
    cmd.CommandType = CommandType.Text; 
    cmd.Connection = sqlConnection1; 

    sqlConnection1.Open(); 

    reader = cmd.ExecuteReader(); 
    // Data is accessible through the DataReader object here. 

    sqlConnection1.Close(); 
} 

enter image description here

+0

인가? – Steve

+0

아니, 그게 내가 어디에 있는지 검열하는 것이었다. 호스트는 something.db.11420661.hostedresource.com – user2962806

+0

의 형태로 godaddy 서버입니다. 실제 예외가 필요하므로 게시하고 확인해 보겠습니다. –

답변

6

내가 연결 문자열에 대한 확실하지 않다,하지만 귀하의 질문은 다음 MySQL의 태그 것을보고 다른 클래스를 사용하여 MySql과 '대화'해야합니다. 지금 사용하고있는 것들은 Microsoft SQL Server 작업의 목적에 부합합니다.

당신은 MySQL의 대응에 SqlConnection, SqlCommandSqlDataReaderMySqlConnection, MySqlCommand, MySqlDataReader라는 것을 변경해야합니다. 이 클래스는 다운로드 한 후 MySql NET/Connector을 설치 한 다음 MySql.Data.Dll에 대한 참조를 설정하고 프로젝트에 using MySql.Data.MySqlClient;을 추가하십시오.

MySql에 대한 연결 문자열에 대해서도 규칙을 따르고 사용해야합니다 키워드는 다음과 같습니다. explained in this site

이것은 프로그램에 작업 가능성을 부여하기위한 기본 단계이지만 여기에는 큰 문제가 있습니다. 이것은 SQL 명령에서 문자열 연결이라고하며이 습관은 곧 Sql Injection vulnerability으로 연결됩니다.

당신은 이런 일에 코드를 변경해야

: '호스트'서버 (은 SQL Server가 설치되어있는 PC 이름)의 이름

private void btn_Submit_Click(object sender, EventArgs e) 
{ 
    if (isValidData()) 
    { 

     //CONVERT FORM VALUES AND STORE IN VARIABLES TO SEND TO MYSQL QUERY 
     DateTime saleTime = saleDatePicker.Value; 
     Decimal price = Convert.ToDecimal(txt_Price.Text); 
     string customerName = txt_CustomerName.Text; 
     string customerPhone = txt_CustomerPhone.Text; 
     string description = rTxt_Description.Text; 

     // Create the query using parameter placeholders, not the actual stringized values.... 
     string query = "INSERT into SALES VALUES (@stime, @price, @cname,@cphone,@cdesc)"; 

     // Create a list of parameters with the actual values with the placeholders names 
     // Pay attention to the Size value for string parameters, you need to change it 
     // accordingly to your fields size on the database table. 
     List<MySqlParameter> prms = new List<MySqlParameter>() 
     { 
      new MySqlParameter {ParameterName="@stime", MySqlDbType=MySqlDbType.DateTime, Value = saleTime }, 
      new MySqlParameter {ParameterName="@price", MySqlDbType=MySqlDbType.Decimal, Value = price }, 
      new MySqlParameter {ParameterName="@cname", MySqlDbType=MySqlDbType.VarChar, Value = customerName, Size = 150 }, 
      new MySqlParameter {ParameterName="@cphone", MySqlDbType=MySqlDbType.VarChar, Value = customerPhone , Size = 150 }, 
      new MySqlParameter {ParameterName="@desc", MySqlDbType=MySqlDbType.VarChar, Value = description , Size = 150 } 
     }; 

     // Pass query and parameters to the insertion method. 
     // get the return value. if it is more than zero you are ok.. 
     int result = insertValues(query, prms); 
     // if(result > 0) 
     // .... insertion ok .... 
    } 
} 

private int insertValues(string q, List<MySqlParameter> parameters) 
{ 
    using(MySqlConnection con = new MySqlConnection(....)) 
    using(MySqlCommand cmd = new MySqlCommand(q, con)) 
    { 
     con.Open(); 
     cmd.Parameters.AddRange(parameters.ToArray()); 
     int rowsInserted = cmd.ExecuteNonQuery(); 
     return rowsInserted; 
    } 
} 
+0

확인. 이제 이것이 올바른 방향입니다. 커넥터를 다운로드하여 설치했습니다. 어디에서 DLL을 참조 할 수 있습니까? – user2962806

+0

은 너겟과 함께 설치할 수 있습니다 https://www.nuget.org/packages?q=Tags%3A%22Connector%2FNET%22 –

+0

대단히 감사합니다. 이것은 확실히 문제 였고 이제는 내 행이 올바르게 삽입됩니다. 다시 한번 감사드립니다. – user2962806