2016-08-19 32 views
0
Imports System.Data.Sql 
Imports System.Data.SqlClient 

Public Class Main 
    Dim c As New SqlCommand 
    Dim connection As String = "Server=DESKTOP-7MC233A\SQLJOSE;database=AttendanceLog;user id=sa;password=pogi1234;" 

    Private Sub Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load 
     Timer1.Enabled = True 

     Dim dtmNow As DateTime = System.DateTime.Now 

     If dtmNow.Hour > 0 And dtmNow.Hour < 11 Then 
      Label2.Text = "Good morning" 

     ElseIf dtmNow.Hour > 12 And dtmNow.Hour < 18 Then 
      Label2.Text = "Good afternoon" 

     ElseIf dtmNow.Hour > 19 And dtmNow.Hour < 23 Then 
      Label2.Text = "Good evening " 
     Else 

     End If 
    End Sub 

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick 
     lblDate.Text = Date.Now.ToString("MMM dd,yyyy") 
     lblTime.Text = Date.Now.ToString("hh:mm:ss") 
    End Sub 

    Private Sub Label1_Click(sender As Object, e As EventArgs) Handles lblDate.Click 

    End Sub 

    Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbNames.SelectedIndexChanged 



    End Sub 

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
     Using con As New SqlConnection(connection) 
      Try 
       If con.State = ConnectionState.Closed Then 
        con.Open() 
       End If 

       With c 
        .Connection = con 
        .CommandText = "Insert into TimeIn values(@Name,@TimeIn,@Date)" 
        .CommandType = CommandType.Text 

        .Parameters.AddWithValue("@Name", cmbNames.Text) 
        .Parameters.AddWithValue("@TimeIn", lblTime.Text) 
        .Parameters.AddWithValue("@Date", lblDate.Text) 

        .ExecuteNonQuery() 

       End With 
       Dim dtmNow As DateTime = System.DateTime.Now 

       If dtmNow.Hour > 9 Then 
        MsgBox("You are late!!!", MsgBoxStyle.Critical) 
       ElseIf dtmNow.Hour < 9 Then 

        MsgBox("You are on time!", MsgBoxStyle.Information) 

       End If 



      Catch ex As Exception 
       MsgBox("From: " & ex.Message) 
      End Try 
      con.Dispose() 

     End Using 

    End Sub 
End Class 

這是我的代碼,我很遺憾接下來要做的事情。先謝謝您的幫助。使用MS SQL作爲我的數據庫處理VB.net程序。然後,當我試圖向我的表格中插入另一個值時彈出此錯誤

+0

哪裏是實際的錯誤?它在哪裏升起? –

+1

什麼是錯誤?你的代碼中的哪一行會彈出?你有沒有試過用突破點來運行它? –

+0

錯誤是「變量名稱@Name」已被聲明變量名稱在查詢批處理或存儲過程中必須是唯一的,並且當我想向我的數據庫中添加另一個值時引發。 – josiemeister

回答

0

每次創建一個新的sqlcommand。每次您創建一個新的連接的方式都是一樣的。

您遇到的問題是您在第二遍時再次添加@name。

Using con As New SqlConnection(connection) 
    Using cmd as New SqlCommand(...) 

    .... 

    End Using 
End Using 
1

只需在使用它後處理sqlCommand。
你可以使用:

Using c As New SqlCommand("commandtext", connection") 

或者你也可以..

With c 
'after the execution 
.Parameters.Clear() 
.Dispose 
End With 
+0

It works!Thanks很多! – josiemeister

+0

如果此答案幫助您解決問題,請標記爲已回答 – kiLLua

相關問題