Jump to content

Recommended Posts

Posted (edited)
	  Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\ClubeVideo.accdb"
		Dim OLDB As String = "INSERT INTO Filmes ([NomeFilme],[TituloOriginal],[CodigoFornecedor],[Genero],[Realizador],[Actores],[Pais],[Ano],[ClasseEtaria]) VALUES (@NomeFilme,@TituloOriginal,@CodigoFornecedor,@Genero,@Realizador,@Actores,@Pais,@Ano,@ClasseEtaria)"
		' Inicia uma ligação à bse de dados
		Using connection As New OleDbConnection(connString)
			' Define o comando e os parâmetros
			Dim command1 As New OleDbCommand(OLDB, connection)
			' command1.Parameters.Add("@IDFilme", OleDbType.VarChar).Value = TextBox1.Text
			command1.Parameters.Add("@NomeFilme", OleDbType.VarChar).Value = TextBox2.Text
			command1.Parameters.Add("@TituloOriginal", OleDbType.VarChar).Value = TextBox3.Text
			command1.Parameters.Add("@CodigoFornecedor", OleDbType.Integer).Value = TextBox4.Text
			command1.Parameters.Add("@Genero", OleDbType.VarChar).Value = TextBox5.Text
			command1.Parameters.Add("@Realizador", OleDbType.VarChar).Value = TextBox6.Text
			command1.Parameters.Add("@Actores", OleDbType.VarChar).Value = TextBox7.Text
			command1.Parameters.Add("@Pais", OleDbType.VarChar).Value = TextBox9.Text
			command1.Parameters.Add("@Ano", OleDbType.Integer).Value = TextBox10.Text
			command1.Parameters.Add("@ClasseEtaria", OleDbType.VarChar).Value = TextBox11.Text
			' command1.Parameters.Add("@foto", OleDbType.VarChar).Value = PictureBox1.ImageLocation
			' Abre a ligação e insere o registo
			connection.Open()
			Dim xx As String = command1.ExecuteNonQuery()
			If xx < 1 Then
				MessageBox.Show("Erro ao inserir", My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Error)
			Else
				MessageBox.Show("Registo inserido com sucesso!", My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Information)

			End If
			connection.Close()
			command1 = Nothing
		End Using
	End If

Então ao fazer este insert ele mostra me todos os dados na hora menos o ID pois por estar em autoincrement eu não o inseri.. Ele só o volta a mostrar aquando o fecho do programa ... Alguma solução?

Edited by Caça
GeSHi
Posted

Isto depende um pouco do banco de dados que você utiliza, pois não é uma função padrão SQL, mas é possível sim, veja alguns exemplos abaixo, o primeiro funciona com Access especificamente, o que parece ser o caso. Os outros são de SQLServer, mas podem funcionar, não testei.

http://stackoverflow.com/questions/9417897/last-inserted-id-of-msaccess-database

http://www.fryan0911.com/2009/03/vb-net-get-identity-field-value-from.html

http://stackoverflow.com/questions/4425153/vb-net-sql-last-inserted-id

Fernando Lage Bastos - MCP/MCTS/MCPD

Posted (edited)

Viva, o facto de estar em autoincrement não tem problemas tens é mal estuturado no insert.

a assim e altera tambem na tua bd

command1.Parameters.Add("@IDFilme", OleDbType.Int).Value = TextBox1.Text

o id tem que ser int e não varchar.

Edited by Blackvelvet
Posted

Pois mas por isso é que eu tinha essa linha de codigo comentada porque ja andei a testar e tudo mais mas o erro que me dá é sempre o mesmo..

Dim xx As String = command1.ExecuteNonQuery()

Não foi possível converter o valor do parâmetro de String para Int32.

Posted (edited)

O ExecuteNonQuery devolve valores do tipo Int32, e não string como está aqui

Dim xx As String = command1.ExecuteNonQuery()

e aqui estás comparando uma string com o valor numérico:

If xx < 1 Then

Edited by petvetbr

Fernando Lage Bastos - MCP/MCTS/MCPD

Posted (edited)

tenta assim, então:

Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\ClubeVideo.accdb"
Dim OLDB As String = "INSERT INTO Filmes ([NomeFilme],[TituloOriginal],[CodigoFornecedor],[Genero],[Realizador],[Actores],[Pais],[Ano],[ClasseEtaria]) VALUES (@NomeFilme,@TituloOriginal,@CodigoFornecedor,@Genero,@Realizador,@Actores,@Pais,@Ano,@ClasseEtaria)"
' Inicia uma ligação à bse de dados
					Using connection As New OleDbConnection(connString)
' Define o comando e os parâmetros
Dim command1 As New OleDbCommand(OLDB, connection)
command1.Parameters.Add("@IDFilme", OleDbType.INT).Value = TextBox1.Text
command1.Parameters.Add("@NomeFilme", OleDbType.VarChar).Value = TextBox2.Text
command1.Parameters.Add("@TituloOriginal", OleDbType.VarChar).Value = TextBox3.Text
command1.Parameters.Add("@CodigoFornecedor", OleDbType.Integer).Value = TextBox4.Text
command1.Parameters.Add("@Genero", OleDbType.VarChar).Value = TextBox5.Text
command1.Parameters.Add("@Realizador", OleDbType.VarChar).Value = TextBox6.Text
command1.Parameters.Add("@Actores", OleDbType.VarChar).Value = TextBox7.Text
command1.Parameters.Add("@Pais", OleDbType.VarChar).Value = TextBox9.Text
command1.Parameters.Add("@Ano", OleDbType.Integer).Value = TextBox10.Text
command1.Parameters.Add("@ClasseEtaria", OleDbType.VarChar).Value = TextBox11.Text
' command1.Parameters.Add("@foto", OleDbType.VarChar).Value = PictureBox1.ImageLocation
' Abre a ligação e insere o registo
connection.Open()
Dim xx As Integer = command1.ExecuteNonQuery()
If xx < 1 Then
 MessageBox.Show("Erro ao inserir", My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
 MessageBox.Show("Registo inserido com sucesso!", My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Information)
   End If
  connection.Close()
 command1 = Nothing
End Using
End If
Edited by Blackvelvet
Posted

Blackvet creio que aquele INT referes te a um Integer... Pois INT não funciona..

Obtenho o mesmo erro na mesma linha Dim xx As Integer = command1.ExecuteNonQuery()

Não foi possível converter o valor do parâmetro de String para Int32.

Posted (edited)
		Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\ClubeVideo.accdb"
		Dim OLDB As String = "INSERT INTO Filmes ([NomeFilme],[TituloOriginal],[CodigoFornecedor],[Genero],[Realizador],[Actores],[Pais],[Ano],[ClasseEtaria]) VALUES (@NomeFilme,@TituloOriginal,@CodigoFornecedor,@Genero,@Realizador,@Actores,@Pais,@Ano,@ClasseEtaria)"
		' Inicia uma ligação à bse de dados
		Using connection As New OleDbConnection(connString)
			' Define o comando e os parâmetros
			Dim command1 As New OleDbCommand(OLDB, connection)
			command1.Parameters.Add("@IDFilme", OleDbType.Integer).Value = TextBox1.Text
			command1.Parameters.Add("@NomeFilme", OleDbType.VarChar).Value = TextBox2.Text
			command1.Parameters.Add("@TituloOriginal", OleDbType.VarChar).Value = TextBox3.Text
			command1.Parameters.Add("@CodigoFornecedor", OleDbType.Integer).Value = TextBox4.Text
			command1.Parameters.Add("@Genero", OleDbType.VarChar).Value = TextBox5.Text
			command1.Parameters.Add("@Realizador", OleDbType.VarChar).Value = TextBox6.Text
			command1.Parameters.Add("@Actores", OleDbType.VarChar).Value = TextBox7.Text
			command1.Parameters.Add("@Pais", OleDbType.VarChar).Value = TextBox9.Text
			command1.Parameters.Add("@Ano", OleDbType.Integer).Value = TextBox10.Text
			command1.Parameters.Add("@ClasseEtaria", OleDbType.VarChar).Value = TextBox11.Text
			' command1.Parameters.Add("@foto", OleDbType.VarChar).Value = PictureBox1.ImageLocation
			' Abre a ligação e insere o registo
			connection.Open()
			Dim xx As Integer = command1.ExecuteNonQuery()
			If xx <> 1 Then
				MessageBox.Show("Erro ao inserir", My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Error)
			Else
				MessageBox.Show("Registo inserido com sucesso!", My.Application.Info.Title, MessageBoxButtons.OK, MessageBoxIcon.Information)
			End If
			connection.Close()
			command1 = Nothing
		End Using
	End If

Se calhar não estão a entender onde eu estou a tentar chegar.. passo a explicar... sem esta linha de codigocommand1.Parameters.Add("@IDFilme", OleDbType.Integer).Value = TextBox1.Text ele insere normalmente a questão é que ao inserir não me mostra o ID na textbox só fechando e reabrindo o programa novamente é que ele me apresente o ID na textbox... e eu pretendia contornar essa situação nem que fosse uma forma de voltar a fazer o load ao programa sem o fechar..

Edited by Mica
Posted

então, funciona assim...

logo após a inserção, você faz uma consulta, usando ExecuteQuery ou ExecuteScalar com o seguinte comando:

SELECT @@IDENTITY

com isto consegue obter o ID do registro que acabou de ser inserido que é devolvido desta consulta.

Fernando Lage Bastos - MCP/MCTS/MCPD

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.