I cant delete rows in a table
it doesn't come up with any error messages
con has been used on other statements and works just fine
textbox1 is read-only and gets input from a listbox filled with the values of the "Driver" column
and check() is just to refresh the listbox containing the values
con.Open()
Try
success = True
Dim cmd As New SqlCommand("DELETE FROM Driver WHERE Driver='" & TextBox1.Text & "';", con)
Catch ex As Exception
MsgBox(ex.Message)
success = False
End Try
If success Then
MsgBox("Success")
End If
con.Close()
check()
You never execute the command. Add a call to SqlCommand::ExecuteNonQuery
Dim cmd As New SqlCommand("DELETE FROM Driver WHERE Driver='" & TextBox1.Text & "';", con)
cmd.ExecuteNonQuery() ' added
That said you should not use string concatenation when adding values to your sql statement. Instead use Parameters which prevents sql injection attacks.
Dim cmd As New SqlCommand("DELETE FROM Driver WHERE Driver= #driver", con)
cmd.Parameters.Add("#driver", SqlDbType.VarChar).Value = TextBox1.Text ' add parameter
cmd.ExecuteNonQuery() ' added
Assumption
Driver is a column inside a table with the same name Driver. If this is not the case then you do not understand tables and columns or the DELETE statement which in its basic form is DELETE FROM [TABLE] WHERE [condition on one or more columns]
Related
i am begginer in visual basic and i want to insert text into cells in column in MS access but i doesn't find, how could i do that.
Here is code i tried:
Private Sub UpdateDataBase2()
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
datafile = "F:\Test Database\Database.accdb"
conString = provider & datafile
myConnection.ConnectionString = conString
myConnection.Open()
Dim str As String
str = "Insert into TABLA([LABELS]) Values (?)"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("LABELS", CType(TextBox1.Text, String)))
Select Case panelCount
Case 1
' TextBox1.Text = cmd.Add("LABELS").Rows(0).Item(1).ToString()
Case 2
' str = "Insert into TABLA([LABELS]) Values (?)"
'cmd.Parameters.Add(New OleDbParameter("LABELS", CType(TextBox1.Text, String)))
End Select
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
myConnection.Close()
End Sub
In this application, i made a dynamics panels and labels.(dynamics is for me generated in code)
panelcount is variable which saves to another MS acces database count of dynamics panels. I want to save text from labels to database systematically(it means: text from label 1 insert to cell 1.), but every code i tried was not function for me.
I know i have to use loop, but first i want to try if code works.
Sorry for my english.
Any solution?
Database objects like Connection and Command should be declared in the method where they are used so they can be disposed.
Use Using...End Using blocks to ensure that your database objects are closed and disposed even if there is an error.
Insert creates a new record. If you want to Update an existing record you will need the primary key value for the record you want to update.
Dim Str = Update TABLA Set [LABELS] = ? Where ID = ?
Then you will need a second parameter.
cmd.Parameters.Add("ID", OleDbType.Integer).Value = intID
You will need to declare and provide a value for intID.
Don't show a message box while a connection is open.
Private Sub OPCode()
Try
Dim Str = "Insert into TABLA([LABELS]) Values (?)"
Dim ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\Test Database\Database.accdb"
Using myConnection As New OleDbConnection(ConStr),
cmd As OleDbCommand = New OleDbCommand(Str, myConnection)
cmd.Parameters.Add("LABELS", OleDbType.VarChar).Value = TextBox1.Text
myConnection.Open()
cmd.ExecuteNonQuery()
End Using 'Closes and disposes the connection and disposes the command
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
For Each row As DataGridViewRow In selectedRows
Dim str As String
str = "DELETE from sheet1 WHERE Id = #Id"
Dim cmd As OracleCommand = New OracleCommand(str, con)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add(New OracleParameter("#Id", row.Cells("Id").Value))
Try
con.Open()
cmd.ExecuteNonQuery()
cmd.Dispose()
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next
I like to delete oracle table multiple records through vb.net DataGridView, ora 00936 missing expression error is come for below coding.. if im using AddWithValue instead of cmd.parameter.add then the error is AddWithValue is not a member of oracle.dataAccess.client.oracleparametercollection..
Please help me..
Create the connection and command outside the loop. The only thing that changes inside the loop is the value of the parameter. Open the connection once outside the loop.
CommandType.Text is the default value for .CommandType and doesn't need to explicitly stated.
Use a Using...End Using block to insure that your database objects are closed and disposed even if there is an error.
Notice the parameter name is preceded by a colon in the .CommandText. When the parameter name is provided to the Parameter constructor there is no colon. I have not tested this. This is info from https://learn.microsoft.com/en-us/dotnet/api/system.data.oracleclient.oraclecommand.parameters?view=netframework-4.8 Check the last paragraph in Remarks.
Private Sub OPCode(selectedRows As List(Of DataGridViewRow))
Using con As New OracleConnection("Your connection String"),
cmd As New OracleCommand("DELETE from sheet1 WHERE Id = :Id", con)
'This will bind parameters by name instead of the order they appear in the command text.
cmd.BindByName = True
cmd.Parameters.Add("Id", OracleDbType.Int32)
con.Open()
For Each row As DataGridViewRow In selectedRows
cmd.Parameters("Id").Value = row.Cells("Id").Value))
Try
cmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next
End Using
End Sub
Please help to get the primary key of the last insert record as the one which i have gives me duplicate rows in the database and return 0
Try
If Conn.State = ConnectionState.Open Then Conn.Close()
'insert the new customer data
Conn.Open()
cmd = New SqlCommand("insert into Quote values ('" & dateOFCreat & "','" & Emp & "','" & Customer_no & "' )", Conn)
Dim a As Integer = cmd.ExecuteNonQuery()
Dim results As Integer
Dim cmd_results As SqlCommand
'Get the last created Quote in the Database
cmd_results = New SqlCommand("Select ##Identity from Quote", Conn)
results = cmd.ExecuteScalar
TxtLastQuoteID.Text = results
If a = 0 Then
MsgBox("Error")
End If
Conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
You can make use of the batch commands supported by Sql Server. Just put together the two instructions and just use ExecuteScalar. However, before that, you need to fix ASAP your Sql Injection vulnerability. Do not concatenate strings to build an sql command, but use parameters.
Try
Using con as SqlConnection = new SqlConnection(....constringhere...)
Conn.Open()
Dim sqlText = "insert into Quote values (#dat,#emp,#cusno); SELECT SCOPE_IDENTITY()"
cmd = New SqlCommand(sqlText,Conn)
cmd.Parameters.Add("#dat", SqlDbType.NVarChar).Value = dateOFCreat
cmd.Parameters.Add("#end", SqlDbType.NVarChar).Value = emp
cmd.Parameters.Add("#cusno", SqlDbType.NVarChar).Value = Customer_no
Dim lastID As Integer = cmd.ExecuteScalar()
TxtLastQuoteID.Text = lastID.ToString()
Conn.Close()
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
Notice also that is a very bad thing to keep a global connection object. You don't need that because ADO.NET implements Connection Pooling that makes opening a connection a very fast operation. Instead keeping a connection around requires a lot of effort to work correctly around it
Finally you can look here to better understand the difference between SCOPE_IDENTITY and ##IDENTITY and why is usually better to use the first one.
I'm trying to make a library system. I have a listview and it contains items to be inserted into different tables, (b_borrow_tbl, for the books , d_borrow_tbl for the multimedia, and m_borrow_tbl for the module).
I'm using this code to insert items to b_borrow_tbl:
Dim myconnection As New SqlConnection("Data Source = .\SqlExpress;Initial Catalog = librarysystemdb; Integrated Security = True")
selecteduser = cmb_borrower.SelectedValue
myconnection.Open()
For xa = 0 To ListView1.Items.Count - 1
Dim mycommand As New SqlCommand("Insert into b_borrow_tbl (bid,user_id,dateborrowed,aid,status) values(#bid,#user,#dateborrowed,#admin ,'" & "Borrowed" & "')", myconnection)
mycommand.Parameters.AddWithValue("bid", ListView1.Items(xa).SubItems(5).Text)
mycommand.Parameters.AddWithValue("user", selecteduser)
mycommand.Parameters.AddWithValue("dateborrowed", datestring)
mycommand.Parameters.AddWithValue("admin", LoginPage.admin)
mycommand.ExecuteNonQuery()
myconnection.Close()
Next
MsgBox("Transaction Saved")
ListView1.Items.Clear()
myconnection.Close()
End Sub
Here's one possibility. Note that I can't give you exact code because I don't know the structure of your other tables...so, with that caveat...
Dim myconnection As New SqlConnection("Data Source = .\SqlExpress;Initial Catalog = librarysystemdb; Integrated Security = True")
selecteduser = cmb_borrower.SelectedValue
myconnection.Open()
For xa = 0 To ListView1.Items.Count - 1
Dim itemType as String
itemType = ListView1.Items(xa).Subitems(6).Text ' Not sure abt col #
if itemType="Books" Then
Dim mycommand As New SqlCommand("Insert into b_borrow_tbl (bid,user_id,dateborrowed,aid,status) values(#bid,#user,#dateborrowed,#admin ,'" & "Borrowed" & "')", myconnection)
mycommand.Parameters.AddWithValue("bid", ListView1.Items(xa).SubItems(5).Text)
mycommand.Parameters.AddWithValue("user", selecteduser)
mycommand.Parameters.AddWithValue("dateborrowed", datestring)
mycommand.Parameters.AddWithValue("admin", LoginPage.admin)
mycommand.ExecuteNonQuery()
End If
If itemType="Multimedia" Then
mycommand.SqlCommand="Insert into d_borrow_table( field1,field2,etc) values (#parm1,#parm2,...)
mycommand.Parameters.Clear()
mycommand.Parameters.AddWithValue("#param1",value)
' etc
mycommand.ExecuteNonQuery()
' Then repeat by changing command text for third table
' clearing/defining parameters, then executing the query
End If
myconnection.Close()
Next
MsgBox("Transaction Saved")
ListView1.Items.Clear()
myconnection.Close()
End Sub
All we're doing here is "resetting" the "mycommand" variable with a new INSERT statement, clearing the parameters, and redefining them for the second and third inserts. Note that the connection isn't closed until after all three inserts have fired. You'll obviously need to replace the "placeholders" of "field1,field2" and #param1,#param2 etc with the actual fields from your tables, but I think that should give you a push in the right direction.
This is my first attempt at writing a program that accesses a database from scratch, rather than simply modifying my company's existing programs. It's also my first time using VB.Net 2010, as our other programs are written in VB6 and VB.NET 2003. We're using SQL Server 2000 but should be upgrading to 2008 soon, if that's relevant.
I can successfully connect to the database and pull data via query and assign, for instance, the results to a combobox, such as here:
Private Sub PopulateCustomers()
Dim conn As New SqlConnection()
Dim SQLQuery As New SqlCommand
Dim daCustomers As New SqlDataAdapter
Dim dsCustomers As New DataSet
conn = GetConnect()
Try
SQLQuery = conn.CreateCommand
SQLQuery.CommandText = "SELECT Customer_Name, Customer_ID FROM Customer_Information ORDER BY Customer_Name"
daCustomers.SelectCommand = SQLQuery
daCustomers.Fill(dsCustomers, "Customer_Information")
With cboCustomer
.DataSource = dsCustomers.Tables("Customer_Information")
.DisplayMember = "Customer_Name"
.ValueMember = "Customer_ID"
.SelectedIndex = -1
End With
Catch ex As Exception
MsgBox("Error: " & ex.Source & ": " & ex.Message, MsgBoxStyle.OkOnly, "Connection Error !!")
End Try
conn.Close()
End Sub
I also have no problem executing a query that pulls a single field and assigns it to a variable using ExecuteScalar. What I haven't managed to figure out how to do (and can't seem to hit upon the right combination of search terms to find it elsewhere) is how to execute a query that will return a single row and then set various fields within that row to individual variables.
In case it's relevant, here is the GetConnect function referenced in the above code:
Public Function GetConnect()
conn = New SqlConnection("Data Source=<SERVERNAME>;Initial Catalog=<DBNAME>;User Id=" & Username & ";Password=" & Password & ";")
Return conn
End Function
How do I execute a query so as to assign each field of the returned row to individual variables?
You probably want to take a look at the SqlDataReader:
Using con As SqlConnection = GetConnect()
con.Open()
Using cmd As New SqlCommand("Stored Procedure Name", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("#param", SqlDbType.Int)
cmd.Parameters("#param").Value = id
' Use result to build up collection
Using dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.CloseConnection Or CommandBehavior.SingleResult Or CommandBehavior.SingleRow)
If (dr.Read()) Then
' dr then has indexed columns for each column returned for the row
End If
End Using
End Using
End Using
Like #Roland Shaw, I'd go down the datareader route but an other way.
would be to loop through
dsCustomers.Tables("Customer_Information").Rows
Don't forget to check to see if there are any rows in there.
Google VB.Net and DataRow for more info.