How to update a MS Access database in vb.net - vb.net

Hi I'm having trouble with updating one of my tables using vb.net when i click on the button to update the data base it give me the error "System.Data.OleDb.OleDbException: No value given for one or more required parameters."
here is the code
Protected Sub Button6_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button6.Click
Dim aConnection As New OleDbConnection
Dim aCommand As New OleDbCommand
Dim SQLQuery, aConnectionString As String
Dim Text As String = TextBox1.Text
Dim aDataAdapter As New OleDbDataAdapter
Dim aDataReader As New DataSet
SQLQuery = "Update Review Set report='Yes' Where Text='" & Text & "'"
aConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Server.MapPath("App_Data/BookReviewWebsite.accdb")
aConnection = New OleDbConnection(aConnectionString)
aConnection.Open()
aCommand = New OleDbCommand(SQLQuery, aConnection)
aCommand.ExecuteNonQuery()
Label15.Text = "Review has been reported"
aConnection.Close()
End Sub

Review, Report and Text. Here you have two fields and a table name, you should check if your database effectively contains a table named Review and if, in this table, there are two field named report and Text.
If your really have this table and these fields, then you need to enclose the word TEXT with square brackets because the word TEXT is a reserved keyword in Access 2007.
Last, but not least of your problems is the query string itself. Concatenating strings in that way could be a source of errors. If you have a single quote in your 'Text' variable then the results could be impredictable and range from Syntax error to Sql Injection
SQLQuery = "Update Review Set report='Yes' Where [Text]=?"
aCommand = New OleDbCommand(SQLQuery, aConnection)
aCommand.Parameter.AddWithValue("#p1", Text)
aCommand.ExecuteNonQuery()

Related

how to get datatable if textbox matches your data in database

how can I possibly populate my table if like textbox.text matches from my data inside database.
I'm stuck here, not sure where I did go wrong
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Dim dbcommand As String
dbcommand = "SELECT * FROM aws_rdp where csn_user like " & txtCSNUser.Text & ""
adt = New OleDbDataAdapter(dbcommand, dbconn)
datatable = New DataTable
adt.Fill(datatable)
DataGridView1.DataSource = datatable
End Sub
Try putting ' before and after the quotation marks surrounding the textbox text. If you're trying to find that text within the text stored in the database you will also need wildcards (%) surrounding it too. Try:
dbcommand = "SELECT * FROM aws_rdp where csn_user like '%" & txtCSNUser.Text & "%'"
Also, as others have stated, look into using parameters in your SQL code as it will help prevent things like SQL injection and is always good practice
Found the answer to my problem by using this code. Anyways, thanks for your time replying on my query, will surely take note of your advises for my future references
Dim dbcommand As String = "SELECT * FROM aws_rdp where csn_user like '%" & txtCSNUser.Text & "%'"
Dim command As New OleDbCommand(dbcommand, dbconn)
Dim adapter As New OleDbDataAdapter(command)
Dim datatable As New DataTable
adapter.Fill(datatable)
DataGridView1.DataSource = datatable
DataGridView1.Columns(0).HeaderText = "ID"
DataGridView1.Columns(1).HeaderText = "IP Address"
DataGridView1.Columns(2).HeaderText = "Username"
DataGridView1.Columns(3).HeaderText = "Password"

Add datagrid columns to database?

I'm trying to add a users selected row to the database
I want the CarID, CarBrand, And CarModel to enter
When the user selected that row they click a button to add it to the database
I seem to be getting errors and I'm not sure why
Here is my code
Private Sub Btn_addtorental_Click(sender As Object, e As EventArgs) Handles Btn_addtorental.Click
If datcarsearchresults.SelectedRows.Count = 1 Then
Dim SelectedCarID As Integer = datcarsearchresults.SelectedRows(0).Tag
Dim SelectedCarBrand As String = datcarsearchresults.SelectedColumns(1)
Dim SelectedCarModel As String = datcarsearchresults.SelectedColumns(2)
PublicCarID = SelectedCarID
If DbConnect() Then
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Insert into Tbl_Rental (CarID,CarBrand,CarModel) " & "Values (#CarID,#CarBrand,#CarModel)"
.Parameters.AddWithValue("#CarID", SelectedCarID)
.Parameters.AddWithValue("#CarBrand", SelectedCarBrand)
.Parameters.AddWithValue("#CarModel", SelectedCarModel)
.ExecuteNonQuery()
It says it cannot be converted to string??
Any help would be appreciated thanks
Where is it erroring? I'm guessing when you try to get the value from the column. The SelectedColumns(1) doesn't bring back a string but brings back a DataGridViewColumnCollection. Take a look at this link with more answers. vb.net how to get cell value from datagridview.

Select from multiple tables without getting Parameter error

I am currently trying to code a database project for a musicians record log. I have been struggling to join 3 tables together in a single search of the database and I am getting this error:
No value given for one or more required parameters.
I have been searching online for why this is but cannot find anything which quite fixes my code. I have tried copying almost word for word other syntax but still get this error. Any help would be much appreciated, my database is as follows:
Program(ProgramID(PK), LengthOfProgram, UserName, NameOfProgram)
ProgramList(PieceListID(PK), PieceID(FK), ProgramID(FK))
Repertoire(PieceID(PK), NameOfPiece, Composer)
Those are the fields needed from repertoire.
Here is my code for when the the program is selected from the list box.
Public dtbConnecter As New OleDbConnection
Dim fileLocator As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source = " + Application.StartupPath + "\Musician Record Log.accdb"
Private Sub lstPro_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstPro.SelectedIndexChanged
Dim programID As String
Dim programIDLength As Integer
Dim selectedString As String = lstPro.GetItemText(lstPro.SelectedItem)
programIDLength = selectedString.IndexOf(":")
programID = selectedString.Substring(0, programIDLength)
MsgBox(programID)
Dim SQL As String = "Select Program.ProgramName, Program.ProgramLength, Repertoire.NameOfPiece, Repertoire.Composer From ((ProgramList INNER JOIN Repertoire ON ProgramList.PieceID = Repertoire.PieceID) INNER JOIN Program ON ProgramList.ProgramID = Program.ProgramID) WHERE (Program.ProgramID = #Param1)"
Dim da As New OleDbDataAdapter
Dim dtbTable As New DataTable
Dim ds As New DataSet
Dim dtbCommand As New OleDbCommand
dtbCommand.Parameters.Add("#Param1", OleDbType.VarChar).Value = programID
dtbCommand.Connection = dtbConnecter
dtbCommand.CommandType = CommandType.Text
dtbCommand.CommandText = SQL
da.SelectCommand = dtbCommand
da.Fill(dtbTable)
'Here i would then use the table's information to update my form, however first i'm trying to get this to work.
da.Dispose()
da = Nothing
End Sub
I also import System.Data, System.Data.OleDb and System.Drawing.Imaging at the top.
It was just a stupid mistake, the names of the fields in the database are NameOfProgram and LengthOfProgram but in the SQL query I used ProgramName and ProgramLength, thanks for all the help in ensuring the SQL query was correct and I did need to correct the data type but the main problem was the wrong identifier.

Trying to delete a record from my access database in visual basic studio 2010

Private Function CreatePlayerAdapter(ByVal playerDBconnection As OleDbConnection) As OleDbDataAdapter
// Initiating instances for the function
Dim dataAdapter As OleDbDataAdapter = New OleDbDataAdapter()
Dim myCommand As OleDbCommand
Dim parameter As OleDbParameter
// establishing the string to tell where to delete record from and how to find the record i want.
// PlayerIDTextBox.Text is a text on a form that is populated from the database after selecting a list of name (this works correctly) // connection is already open and is directed to correct place
Dim sql As String = "DELETE * FROM Players WHERE ID ='" & CInt(PlayerIDTextBox.Text) & "'"
myCommand = New OleDbCommand(sql, playerDBconnection)
parameter = myCommand.Parameters.Add("ID", OleDbType.Char, 3, "ID")
parameter.SourceVersion = DataRowVersion.Original
dataAdapter.DeleteCommand = myCommand
Return dataAdapter
End Function
// i call this function after executing a button click.
//ListPlayerComboBox.Text is populated with the names and needs it a name to fill PlayerIDTextBox.Text(works correctly)
Private Sub RemovePlayerButton_Click(sender As System.Object, e As System.EventArgs) Handles RemovePlayerButton.Click
If ListPlayerComboBox.Text = " " Then
MsgBox("Please Select a Player.")
Else
Me.CreatePlayerAdapter(playerDBConnection)
End If
End Sub
// no errors occur. However, nothing is done in the database. help please?
Notes:
1)Never leave your OleDbConnection Open. Only allow it to be opened when you actually need it. This will save you from a lot of headaches later on. The reasons why can be found on following stackoverflow question.
2) There is no reason to return an OleDbDataAdapter if you don't intend on using it.
3) Use your parameters correctly : see below example2
4) Keep in mind that there are some restricted keywords in Access. Luckely for you ID isn't one. The restrictedKeywords can be found here: Keywords
I'm probably missing some further points here. Anyone should be free to add em.
Why not adjust your Function CreatePlayerAdapter to the following:
1) Without parameters
Private Sub CreatePlayerAdapter(ByVal playerDBconnection As OleDbConnection)
Dim myCommand As OleDbCommand
Dim sql As String = "DELETE * FROM Players WHERE ID =" & CInt(PlayerIDTextBox.Text)
myCommand = New OleDbCommand(sql, playerDBconnection)
playerDBconnection.Open()
myCommand.ExecuteNonQuery()
playerDBconnection.Close()
End Sub
2) With parameters
Private Sub CreatePlayerAdapter(ByVal playerDBconnection As OleDbConnection)
Dim myCommand As OleDbCommand
Dim sql As String = "DELETE * FROM Players WHERE ID = #playerId"
myCommand = New OleDbCommand(sql, playerDBconnection)
Dim param As New OleDb.OleDbParameter(#playerId", CInt(PlayerIDTextBox.Text))
myCommand.Add(param)
playerDBconnection.Open()
myCommand.ExecuteNonQuery()
playerDBconnection.Close()
End Sub
The method ExecuteNonQuery executes the query passed to the command on the specified OleDbConnection and returns the number of rows affected. More info Here

How do I add htmltablecell data to database after I click submit

I created an htmltable in .aspx.vb, because I have a lot of rows that come from database and they depend on the querystring. that part is fine. But when someone makes a change in one of the cells how do I save data back to database?
Code -
Dim tr As New HtmlTableRow
Dim td As New HtmlTableCell
td = New HtmlTableCell
Dim txtbox1 As New TextBox
txtbox1.ID = "price_" & rd("id")
txtbox1.Text = rd("price")
td.Controls.Add(txtbox1)
tr.Cells.Add(td)
tb1.Rows.Add(tr)
Now when someone changes the price in the textbox, how do I save it in database?
This is code for submit button -
Protected Sub submit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles submit.Click
Dim sqlcnn As SqlConnection = Nothing, sqlstr As String = "", sqlcmd As SqlCommand
sqlstr = "UPDATE ???"
sqlcmd = New SqlCommand(sqlstr, sqlcnn)
sqlcmd.ExecuteScalar()
End Sub
Please answer in detail.
I would suggest using the built in grid controls. Here is a walkthrough Walkthrough: Editing and Inserting Data in Web Pages with the DetailsView Web Server Control
. It might be better to start with Walkthrough: Basic Data Access in Web Pages.
If you choose to move forward with HTML then here is one way to do it based on what you provided. You can add an update button and try this code in that event:
'Create an update Command with the apropriate paramaters'
Dim sql = ("UPDATE SO_Prices SET Price = #Price WHERE ID = #ID")
Dim Cmd As New SqlCommand(sql, connection)
Cmd.Parameters.Add("#Price", SqlDbType.SmallMoney)
Cmd.Parameters.Add("#ID", SqlDbType.Int)
connection.Open()
'Loop through the fields returned'
For Each Key As String In Request.Form.Keys
'Make sure you only process fields you want'
If Key.StartsWith("price") Then
'Pull the ID out of the field name by splitting on the underscore'
' then choosing the second item in the array'
Dim ID As String = Key.Split("_")(1)
'Update the paramaters for the update query'
Cmd.Parameters("#ID").Value = ID
Cmd.Parameters("#Price").Value = Request.Form(Key)
'Run the SQL to update the record'
Cmd.ExecuteNonQuery()
End If
Next
connection.Close()
Let me know if you need any additional assitance. If not, please mark this as the correct answer.