我正在尝试在" IF THEN"中更新sql db。声明,但我得到了:
ExecuteNonQuery:尚未初始化Connection属性。
当我运行我的代码时。
Private m_cn As New SqlConnection
If oldcost <> newcost Then
'Dim myconnect As New SqlClient.SqlConnection
m_cn.ConnectionString = "Data Source=localhost;Initial Catalog=tires;Integrated Security=True"
m_cn.Open()
Dim mycommand As SqlClient.SqlCommand = New SqlClient.SqlCommand()
'm_cn.Open()
mycommand.CommandText = "INSERT INTO tire_price_changes (change_date, old_cost, old_retail,new_cost,new_retail,tire_id) VALUES (@change_date, @Nold_cost, @old_retail, @new_cost, @new_retail, @tire_id)"
Try
mycommand.Parameters.Add("@change_date", SqlDbType.Date).Value = tiredate
mycommand.Parameters.Add("@old_cost", SqlDbType.NVarChar).Value = oldcost
mycommand.Parameters.Add("@old_retail", SqlDbType.VarChar).Value = oldretail
mycommand.Parameters.Add("@new_cost", SqlDbType.VarChar).Value = newcost
mycommand.Parameters.Add("@new_retail", SqlDbType.NVarChar).Value = newretail
mycommand.Parameters.Add("@tire_id", SqlDbType.NVarChar).Value = m_introwposition
mycommand.ExecuteNonQuery()
MsgBox("Success")
Catch ex As System.Data.SqlClient.SqlException
MsgBox(ex.Message)
End Try
End If
答案 0 :(得分:1)
它不会以这种方式初始化。手动设置myCommand.Connection
属性或使用CreateCommand:
myCommand = m_cn.CreateCommand();
答案 1 :(得分:0)
您没有连接命令和连接。
在执行前尝试此操作:
mycommand.Connection = m_cn;
您也可以要求连接对象为您创建命令对象,在这种情况下,它将自行设置:
Dim mycommand As SqlClient.SqlCommand = Connection.CreateCommand()
此外,请记住在完成这些对象后调用Dispose
。