ran*_*ish 14 vb.net sql-server
我是新手,vb.net我需要使用vb.net在表中插入数据,请任何人帮助
我试过这个
在这里我尝试了示例代码
我得到了这个例外,Column name or number of supplied values does not match table definition.
谢谢你
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim strName As String = txtName.Text
Dim strId As String = txtID.Text
Dim strPhone As String = txtPhone.Text
Dim strBranch As String = cmboxBranch.SelectedItem.ToString()
Dim strCourse As String = cmbboxCourse.SelectedItem.ToString()
Dim dblFee As Double = Double.Parse(txtFee.Text)
Dim strCommand As String = "insert into student values('" & strName & "','" & strId & "','" & strPhone & "','" & strBranch & "','" & strCourse & "'," & dblFee & ")"
Dim command As SqlCommand = New SqlCommand(strCommand, connection)
command.CommandType = CommandType.Text
'' MsgBox(strCommand)
connection.Open()
If (command.ExecuteNonQuery().Equals(1)) Then
MsgBox("Information stored in database")
Else
MsgBox("Not stored in database")
End If
End Sub
Run Code Online (Sandbox Code Playgroud)
Joh*_*Woo 19
这意味着语句VALUES中子句中指定的值的数量INSERT不等于表中的总列数.如果您只尝试在选定列上插入,则必须指定列名.
另一个,因为您正在使用ADO.Net,始终参数化您的查询以避免SQL Injection.你现在正在做的是你正在击败使用sqlCommand.
前
Dim query as String = String.Empty
query &= "INSERT INTO student (colName, colID, colPhone, "
query &= " colBranch, colCourse, coldblFee) "
query &= "VALUES (@colName,@colID, @colPhone, @colBranch,@colCourse, @coldblFee)"
Using conn as New SqlConnection("connectionStringHere")
Using comm As New SqlCommand()
With comm
.Connection = conn
.CommandType = CommandType.Text
.CommandText = query
.Parameters.AddWithValue("@colName", strName)
.Parameters.AddWithValue("@colID", strId)
.Parameters.AddWithValue("@colPhone", strPhone)
.Parameters.AddWithValue("@colBranch", strBranch)
.Parameters.AddWithValue("@colCourse", strCourse)
.Parameters.AddWithValue("@coldblFee", dblFee)
End With
Try
conn.open()
comm.ExecuteNonQuery()
Catch(ex as SqlException)
MessageBox.Show(ex.Message.ToString(), "Error Message")
End Try
End Using
End USing
Run Code Online (Sandbox Code Playgroud)
PS:请将查询中指定的列名更改为表中的原始列.
| 归档时间: |
|
| 查看次数: |
112481 次 |
| 最近记录: |