1

이 코드의 문제점을 알려주십시오.Insert에 대한 ExecuteNonQuery()

표에 삽입하려면 DataAdapter을 사용해야합니까?

서버 탐색기에서 테스트했기 때문에 connectionString은 괜찮습니다.

Dim mydao As New Connection 
    Dim connectionString As String = mydao.GetConnectionString() 
    Dim connection As New SqlConnection(connectionString) 
    Dim cmd As New SqlCommand 

Public Function add(ByVal area As String, ByVal user As String) As Integer 

     cmd.CommandText = "INSERT into Area (Area, user) VALUES ('" + area + "','" + user + "')" 
     Try 
      connection.Open() 
      Dim cant As Integer = cmd.ExecuteNonQuery()'it throws exception here 
      connection.Close() 
      Return cant 
     Catch ex As Exception 
      Console.WriteLine(ex.Message) 
      Return 0 
     End Try 

    End Function 

은 위의 코드는 바로 뒤에 ExecuteNonQuery() 왜 안 들려요 그림을 실패합니다.

TARGET 필드 (SQL 서버 2008) :

AREA  varchar(100) NOT NULL , 
USER  varchar(100) NOT NULL 

내가받을 예외는 다음과 같습니다 Connection property has not initialized

+1

오류 메시지 수행 방법 너는받을거야? – Alex

+1

연결을 여는 중이지만 해당 연결에 명령의 연결 속성을 설정하지 않은 것으로 보입니다. – kwwallpe

+0

연결 속성이 초기화되지 않았습니다. – phalanx

답변

8

이 코드 몇 가지 문제가있다.

가장 중요한 것은 명령의 Connection 속성을 설정하지 않기 때문에 명령에 데이터베이스 연결 방법을 알 수 없기 때문입니다.

또한 강력하게 using을 활용하는 것이 좋습니다, 또한 parameterizing 쿼리 것입니다 : 당신이 필요하지 않는 한 마지막

는, 함수의 외부 연결 및 명령을 선언하지 않습니다. 필요할 때만 연결 및 명령을 유지해야합니다. 현재, 당신은 0 항상 반환됩니다

Public Function add(ByVal area As String, ByVal user As String) As Integer 

    Dim mydao As New Connection 

    Using connection As New SqlConnection(mydao.ConnectionString()) 

     Using command As New SqlCommand() 
      ' Set the connection 
      command.Connection = connection 

      ' Not necessary, but good practice 
      command.CommandType = CommandType.Text 

      ' Example query using parameters 
      command.CommandText = "INSERT into Area (Area, user) VALUES (@area, @user)" 

      ' Adding the parameters to the command 
      command.Parameters.AddWithValue("@area", area) 
      command.Parameters.AddWithValue("@user", user) 

      connection.Open() 

      Return command.ExecuteNonQuery() 

     End Using ' Dispose Command 

    End Using ' Dispose (and hence Close) Connection 

End Function 

참고 :

그래서 당신의 기능처럼 보이는 끝낼 것입니다. 위의 예제는 함수에서 반환 된 값을 확인하지 않고 단순히 예외를 throw합니다. 이렇게하면 호출자가 0을 오류 조건으로 이해해야하므로 호출자가 예외를 처리해야하는 경우 Try-Catch 블록의이 함수에 대한 호출을 간단하게 마무리합니다.

+0

대단히 감사합니다. – phalanx

관련 문제