你好我创建了一个私有子,其中代码必须插入一个mysql命令....它确实如此,但最有趣的部分是记录从数据库中消失 它在那里,但是我停止了debbug并重新启动它不存在,甚至在数据库中也没有 为什么呢?
Private Sub gravarAtleta()
Dim sqlStatement = "insert into atl([nome],[morada],[sexo],[datan],[telf],[desporto]) "
sqlStatement &= "VALUES (@nome, @morada, @sexo, @datan, @telf, @desporto)"
Using xConn As New SqlConnection(myConnectionString)
Try
Dim xComm As New SqlCommand(sqlStatement, xConn)
With xComm
.CommandType = CommandType.Text
.Parameters.AddWithValue("@nome", txtNome.Text)
.Parameters.AddWithValue("@morada", txtMorada.Text)
.Parameters.AddWithValue("@sexo", ComboSexo.Text)
.Parameters.AddWithValue("@datan", CType(txtDataN.Text, DateTime).ToString("yyyy-MM-dd"))
.Parameters.AddWithValue("@telf", txtTelemovel.Text)
.Parameters.AddWithValue("@desporto", ComboBox1.Text)
End With
xConn.Open()
xComm.ExecuteNonQuery()
xComm.Dispose()
Label1.Content = "O atleta " + txtNome.Text + " foi registado!!!"
Catch ex As SqlException
MsgBox(ex.Message)
Label1.Content = "Falhou a ligação a base de dados!!!"
End Try
End Using
End Sub
答案 0 :(得分:1)
我修改了代码,看它是否有效
Private Sub gravarAtleta()
Dim sqlStatement = "INSERT INTO atl([nome],[morada],[sexo],[datan],[telf],[desporto]) "
sqlStatement &= "VALUES (@nome, @morada, @sexo, @datan, @telf, @desporto)"
Using xConn As New SqlConnection(myConnectionString)
Using xComm As New SqlCommand(sqlStatement, xConn)
With xComm
.CommandType = CommandType.Text
.Parameters.AddWithValue("@nome", txtNome.Text)
.Parameters.AddWithValue("@morada", txtMorada.Text)
.Parameters.AddWithValue("@sexo", ComboSexo.Text)
.Parameters.AddWithValue("@datan", CType(txtDataN.Text, DateTime).ToString("yyyy-MM-dd"))
.Parameters.AddWithValue("@telf", txtTelemovel.Text)
.Parameters.AddWithValue("@desporto", ComboBox1.Text)
End With
Try
xConn.Open
xComm.ExecuteNonQuery
Label1.Content = "O atleta " + txtNome.Text + " foi registado!!!"
Catch ex As SqlException
Msgbox (ex.Message)
Label1.Content = "Falhou a ligação a base de dados!!!"
Finally
xConn.Close
End Try
End Using
End Using
End Sub
答案 1 :(得分:0)
首先,您的命令创建应该使用using语句完成;这样你就不必拥有dispose语句,即使数据库生成和异常,也会处理该对象。例如:
Using xComm As New SqlCommand(sqlStatement, xConn)
With xComm
.CommandType = CommandType.Text
.Parameters.AddWithValue("@nome", txtNome.Text)
.Parameters.AddWithValue("@morada", txtMorada.Text)
.Parameters.AddWithValue("@sexo", ComboSexo.Text)
.Parameters.AddWithValue("@datan", CType(txtDataN.Text, DateTime).ToString("yyyy-MM-dd"))
.Parameters.AddWithValue("@telf", txtTelemovel.Text)
.Parameters.AddWithValue("@desporto", ComboBox1.Text)
xConn.Open()
.ExecuteNonQuery()
End With
End Using
其次,您是否可以在应用程序的部署中包含数据库?我甚至不确定使用MySQL是否可行,但是在我们将数据库副本(SQLCE,Access)作为解决方案中的内容包含在内并将其复制到构建的输出目录之前,我们遇到过类似的问题。
这会引起很大的混淆,因为在先前的调试周期中所做的更改会被新复制的数据库覆盖。