2017-10-18 7 views
0

Visual Basic을 처음 사용했습니다. 내 미니 프로젝트에 대한 Visual Basic 2010 프로젝트를 개발 중입니다. 시각적 기본 형식으로 삽입 된 데이터를 ms 액세스 2007에서 만든 데이터베이스에 저장하고 싶습니다. 다음 코드를 입력했으나 값을 입력 할 때마다 양식 및 보도 자료 제출 메시지 상자에서 "오버플로"예외가 발생합니다. 나는 그 이유를 알 수 없었다. 제발 도와주세요. 어떤 변수 문제를 일으키는 좁히기Visual Basic 2010에서 ms 액세스 데이터베이스에 연결하는 동안 오버플로 예외를 수정하는 방법

Imports System.Data.OleDb 

Public Class dn_register 
    Dim provider As String 
    Dim dataFile As String 
    Dim connString As String 
    Dim myConnection As OleDbConnection = New OleDbConnection 

    Private Sub dn_sub_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dn_sub.Click 

     provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" 
     dataFile = "F:\MyDatabase\MyProjectDatabase.accdb" 
     connString = provider & dataFile 
     myConnection.Close() 
     myConnection.ConnectionString = connString 
     myConnection.Open() 
     Dim str As String 
     str = "Insert into Dnr_tbl([Dname],[Age],[Bloodgroup],[Location],[Contact],[Email]) Values(?,?,?,?,?,?)" 
     Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection) 
     cmd.Parameters.Add(New OleDbParameter("Dname", CType(TextBox1.Text, String))) 
     cmd.Parameters.Add(New OleDbParameter("Age", CType(TextBox2.Text, Integer))) 
     cmd.Parameters.Add(New OleDbParameter("Bloodgroup", CType(TextBox3.Text, String))) 
     cmd.Parameters.Add(New OleDbParameter("Location", CType(TextBox4.Text, String))) 
     cmd.Parameters.Add(New OleDbParameter("Contact", CType(TextBox5.Text, String))) 
     cmd.Parameters.Add(New OleDbParameter("Email", CType(TextBox6.Text, String))) 

     Try 
      cmd.ExecuteNonQuery() 
      cmd.Dispose() 
      myConnection.Close() 
      TextBox1.Clear() 
      TextBox2.Clear() 
      TextBox3.Clear() 
      TextBox4.Clear() 
      TextBox5.Clear() 
      TextBox6.Clear() 


     Catch ex As Exception 
      MsgBox(ex.Message) 

     End Try 

    End Sub 

End Class 

And here is the snapshot of my error message

+0

: 여기

당신이 내 첫 번째 제안을하는 경우, 다음 # 2가 불필요 구현 제안 2-5의 예입니다 https://social.msdn.microsoft.com/Forums/vstudio/ko-US/853aec35-5b19-4126-b142-44dae2ad0a47/oledbexception-overflow? forum = vbgeneral 삽입 쿼리가 잘못되었을 수 있습니다. – Jaxi

+0

테이블 구조를 보지 않고도 쿼리 매개 변수가 잘못되었는지 알기가 어렵습니다. 'Age' 컬럼은 'Byte' 데이터 타입을 사용하기 때문에 cmd.Parameters.Add (New OleDbParameter ("Age", CType (TextBox2.Text, Integer)))'는 가장 의심스러운 부분입니다. –

+0

기증자의 나이를 저장하는 것은 좋지 않습니다. 나는 그들의 DOB를 보관할 것입니다. 문자열의 길이가 올바른지 확인하십시오. 또한 VB.NET의 정수는 4 바이트이지만 Access에서는 2 바이트입니다. .NET에서'Int16'을 사용할 수도 있습니다. – Paul

답변

-1

먼저 시도 :

다음 코드이다. 모든 매개 변수를 주석으로 처리하고 문제점을 찾을 때까지 (매개 변수 수와 일치하도록 필요에 따라 SQL 문 조정) 또는 유력한 용의자를 선택하고 주석 처리를하고 매개 변수를 주석으로 처리하고 SQL 문을 계속 조정할 수 있습니다 작동 할 때까지. 테스트 된 열에 null을 허용하려면 Access에서 테이블을 임시적으로 조정해야 할 수도 있습니다. 정수 값은 가능성이있는 후보로 보이며 거기에서 시작할 것입니다.

문제 매개 변수를 찾으면 VB.NET과 Access간에 데이터 유형이 충돌하거나 불일치하는 것이 분명하거나 어떤 VB 캐스트가 작동하는지 찾기 위해 조금만 실험해야 할 수도 있습니다. 귀하의 예제에서 가장 가능성이 큰 후보는 문자열 길이 문제이며 테이블 정의 및 텍스트 상자 입력 길이 제한을 살펴보면 매우 분명합니다.

0

내 생각이 라인은 예외가 발생된다는 점이다 :

cmd.Parameters.Add(New OleDbParameter("Age", CType(TextBox2.Text, Integer)))

내 첫번째 제안 같은 NumericUpDown 제어으로 숫자 입력을 처리하기위한 적절한 제어를 사용하는 것이다.

두 번째 제안 (TextBox를 계속 사용하는 경우)은 Integer.TryParse을 사용하여 String 값을 정수로 명시 적으로 변환하는 것입니다.

제 3의 제안은 String 값 (textBox [n] .Text)에서 CType을 사용하여 문자열로 변환하는 것을 중지하는 것이므로 불필요합니다.

나의 네 번째 제안은 전달 된 값의 데이터 유형을 사용하기 때문에 대신 Parameter.AddWithValue을 사용하는 것입니다.

마지막 다섯 번째 제안은 using 문에서 iDisposable을 구현하는 개체를 래핑하거나 적어도 명시 적으로 처리하는 것입니다. 여기에서

'Declare an age variable that is an Integer 
Dim age As Integer 

'Convert the String to an Integer 
If Integer.TryParse(TextBox2.Text, age) Then 
    'Declare the connection object 
    Dim con As OleDbConnection 

    'Database operations should always be wrapped in Try/Catch 
    Try 
    'Set the connection object to a new instance 
    con = New OleDbConnection(connString) 

    'Create a new instance of the command object 
    Using cmd As OleDbCommand = New OleDbCommand("INSERT INTO [Dnr_tbl] ([Dname], [Age], [Bloodgroup], [Location], [Contact], [Email]) VALUES (@name, @age, @bloodgroup, @location, @contact, @email)", con) 
     'Parameterize the query 
     With cmd.Parameters 
     .AddWithValue("@name", TextBox1.Text) 
     .AddWithValue("@age", age) 
     .AddWithValue("@bloodgroup", TextBox3.Text) 
     .AddWithValue("@location", TextBox4.Text) 
     .AddWithValue("@contact", TextBox5.Text) 
     .AddWithValue("@email", TextBox6.Text) 
     End With 

     'Open the connection 
     con.Open() 

     'Execute the query 
     cmd.ExecuteNonQuery() 

     'Close the connection 
     con.Close() 

     'Clear the controls 
     TextBox1.Clear() : TextBox2.Clear() : TextBox3.Clear() : TextBox4.Clear() : TextBox5.Clear() : TextBox6.Clear() 
    End Using 
    Catch ex As Exception 
    MessageBox.Show(ex.ToString()) 
    Finally 
    'Check if the connection object was initialized 
    If con IsNot Nothing Then 
     If con.State = ConnectionState.Open Then 
     'Close the connection if it was left open(exception thrown) 
     con.Close() 
     End If 

     'Dispose of the connection object 
     con.Dispose() 
    End If 
    End Try 
Else 
    MessageBox.Show("Invalid age input.") 
End If