2017-10-13 1 views
0

안녕하세요 저는이 포럼에 새입니다. 그 첫 번째 게시물 그래서 만약 내가 뭔가 잘못했다 ... 나는 아래 코드가 있습니다. 나는 쿼리의 모든 매개 변수에 대한 오류를Visual Studio 오류 : 문자열에서 날짜 및/또는 시간을 변환 할 때 변환하지 못했습니다.

"conversion failed when converting date and/or time from character string. visual studio"

public void pay_fighter(string FighterID, string PaymentDay, string PaymentAmount, string PaymentDescr) 
    { 
     if (FighterID.Length != 0) 
     { 
      if (conn.State.ToString() == "Closed") 
      { 
       conn.Open(); 
      } 
      SqlCommand newCmd = conn.CreateCommand(); 
      newCmd.Connection = conn; 
      newCmd.CommandType = CommandType.Text; 
      newCmd.Parameters.AddWithValue("PaymentAmount", PaymentAmount); 
      newCmd.Parameters.AddWithValue("PaymentDescr", PaymentDescr); 
      newCmd.CommandText = "INSERT INTO PaymentInfo VALUES('" + FighterID + "','" + PaymentDay + "',@PaymentAmount, @PaymentDescr)"; 
      newCmd.ExecuteNonQuery(); 
     } 
    } 
+2

SQL-Server 또는 MySQL입니까? 태그 스팸을 피하십시오. – Alex

+0

'PaymentInfo' 테이블에 열의 데이터 유형을 게시하십시오. –

+0

아. 문자열 형 코드. VB.Net과 SQL Server에는 datetime 데이터를 저장하기 위해 설계된 * 데이터 형식 *이 있으며이 데이터 형식을 전혀 사용하지 않는다는 것을 알고 있습니까? 왜 모든 입력 매개 변수는'string'입니까? –

답변

1

를 사용하여 올바른 유형과 SqlParameters를 수신하고 있습니다.

public void pay_fighter(
    string fighterID, 
    DateTime paymentDay, 
    decimal paymentAmount, 
    string paymentDescr) 
{ 
    if (String.IsNullOrEmpty(fighterId)) 
    { 
     return; 
    } 

    var query = 
     @"INSERT INTO PaymentInfo VALUES (
      @FighterId, 
      @PaymentDay, 
      @PaymentAmount, 
      @PaymentDescr)"; 
    var parameters = new[] 
    { 
     new SqlParameter 
     { 
      ParameterName = "@FigtherId", 
      SqlDbType = SqlDbType.Int, // use correct type for column 
      Value = fighterId 
     }, 
     new SqlParameter 
     { 
      ParameterName = "@PaymentDay", 
      SqlDbType = SqlDbType.DateTime, // use correct date type defined in column 
      Value = paymentDay 
     }, 
     new SqlParameter 
     { 
      ParameterName = "@PaymentAmount", 
      SqlDbType = SqlDbType.Decimal, // use correct type for column 
      Value = paymentAmount 
     }, 
     new SqlParameter 
     { 
      ParameterName = "@PaymentDescr", 
      SqlDbType = SqlDbType.VarChar, // use correct type for column 
      Size = 100, // use size defined for column 
      Value = paymentDescr 
     } 
    }; 

    using (var connection = new SqlConnection(connectionString)) 
    using (var command = new SqlCommand(query, connection)) 
    { 
     command.Parameters.AddRange(parameters); 

     connection.Open(); 
     command.ExecuteNonQuery(); 
    } 
} 

쿼리에 대해 새 SqlConnection 인스턴스를 만드는 것이 더 안전합니다. ADO.NET은 실제/실제 연결을 처리하고 필요할 경우 이미 생성 된 재사용을 처리합니다.

관련 문제