使用vb.net INSERT INTO SELECT无法插入

时间:2017-01-18 09:25:22

标签: vb.net ms-access select insert

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Con.Open()
    Dim Str As String = "INSERT INTO db (ID,companyname,companyaddress,companycontact,contactperson,contactnumber,UserLogin,mDate) SELECT @ID,@companyname,@companyaddress,@companycontact,@contactperson,@contactnumber,@UserLogin,@mDate FROM db WHERE Userlogin = @Userlogin"

    Dim Cmd As New OleDbCommand
    With Cmd

        .CommandText = Str

        .Parameters.AddWithValue("@ID", f1.Text)
        .Parameters.AddWithValue("@companyname", f2.Text)
        .Parameters.AddWithValue("@companyaddress", f3.Text)
        .Parameters.AddWithValue("@companycontact", f4.Text)
        .Parameters.AddWithValue("@contactperson", f5.Text)
        .Parameters.AddWithValue("@contactnumber", f6.Text)
        .Parameters.AddWithValue("@UserLogin", f12.Text)
        .Parameters.AddWithValue("@mDate", DateTimePicker1.Text)
        .Connection = Con

        .ExecuteNonQuery()
    End With
    If Cmd.ExecuteNonQuery() Then
        Con.Close()
        MessageBox.Show("New Record is Added successfully.", "Record Saved")
        Call clear()

    Else

        MsgBox("Could Not Insert Record!!! ", "Already Entered")
        Return
    End If
End Sub

3 个答案:

答案 0 :(得分:1)

您必须传递日期

.Parameters.AddWithValue("@mDate", DateTimePicker1.Value)

答案 1 :(得分:0)

调用ExecuteNonQuery()方法时是否出现任何错误? 我检查了你的代码,我有两条评论:
(1)您在代码中调用ExecuteNonQuery()两次:
+ ------------------------ +
'第一次打电话 .ExecuteNonQuery()
以。结束 '二次致电 如果Cmd.ExecuteNonQuery()那么
+ ------------------------ +
你是故意两次打电话给方法吗? 2.确保在调用Cmd.ExecuteNonQuery()方法之前打开连接。

如果您仍然遇到问题,我在这里找到了一个相关的问题,其中包含一些有价值的信息: How can I Insert data into SQL Server using VBNet

我希望这有帮助!

答案 2 :(得分:-1)

我不解释为什么使用SELECT?我想你想这样做:

INSERT INTO db(ID,companyname,companyaddress,companycontact,contactperson,contactnumber,UserLogin,mDate)VALUES(@ ID,@ companyname,@ companyaddress,@ companycontact,@ contactperson,@ contactnumber,@ UserLogin,@ mDate)< / p>