vb.net msaccess update, may i ask whats wrong, why it does not update my data base? - vb.net

I don't know what seems to be the problem,
can anyone help?
I already installed all necessary thing to run the program.
Public Sub main1_Click(sender As Object, e As EventArgs) Handles main1.Click
scorestanding.Text = standingscore
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "Database\user.mdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "UPDATE login set[scorestand] = '" & scorestanding.Text & "' Where [username] = '" & Label1.Text & "'"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
Try
cmd.CommandText = "UPDATE login set[scorestand] = '" & scorestanding.Text & "' Where [username] = '" & Label1.Text
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Me.Close()
main.Show()
End Sub
str = "UPDATE login set[scorestand] = '" & scorestanding.Text & "' Where [username] = '" & Label1.Text & "'"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
Try
cmd.CommandText = "UPDATE login set[scorestand] = '" & scorestanding.Text & "' Where [username] = '" & Label1.Text
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Me.Close()
main.Show()
End Sub
It does nt have any eror but it also does nothing.

Related

Need to close program to see datagrid changes after making a search query and update the results

I execute the search query and after that i want to update the results but datagridview doesnt update, need to close and reopen to see the results.
Can anyone help? dont know if the problem is in the update button or the search
Update button
Call cn()
Dim teste As String
teste = "UPDATE CARROS SET processo = '" & processo & "', estado = '" & estado & "', tecnico = '" & tecnico & "', data = #" & data & "# , localizacao = '" & localizacao & "', [Pedido/PI] = '" & pedido & "'
WHERE Código = " & codigo
updatee = New OleDb.OleDbCommand(teste, connection)
updatee.ExecuteNonQuery()
MessageBox.Show("Actualizado com sucesso")
connection.Close()
CARROSTableAdapter1.Fill(STOCKDataSet1.CARROS)
SEARCH Button
Dim locali As String
Call cn()
'Se não tem valor Erro
If pesqtxt.Text = "" Then
MsgBox("Introduz um Valor")
Else
locali = pesqtxt.Text
'Codigo SQL
sql = "Select *
FROM CARROS
WHERE (processo LIKE '%" & locali & "%') OR
(estado LIKE '%" & locali & "%') OR
(data Like '%" & locali & "%') OR
(localizacao Like '%" & locali & "%') OR
(tecnico Like '%" & locali & "%')"
oledbAdapter = New OleDbDataAdapter(sql, connection)
oledbAdapter.Fill(ds)
CARROSDataGridView.DataSource = ds.Tables(0)
CARROSTableAdapter1.Update(STOCKDataSet1.CARROS)
CARROSTableAdapter1.Fill(STOCKDataSet1.CARROS)
connection.Close()
As far as the Search code goes, you cannot find out if a String is "Like" as Date.
Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error. Keep you database objects local and open connections as late as possible anc close as soon as possible.
Private Sub UpdateDatabse()
Using cn As New OleDbConnection("Your connection string")
Using cmd As New OleDbCommand("UPDATE CARROS SET processo = #processo, estado = #estado, tecnico = #tecnico, data = #data , localizacao = #localizacao, [Pedido/PI] = #pedido WHERE Código = #codigo", cn)
With cmd.Parameters
.Add("#processo", OleDbType.VarChar, 50).Value = processo
.Add("#estado", OleDbType.VarChar, 50).Value = estado
.Add("#tecnico", OleDbType.VarChar, 50).Value = tecnico
.Add("#data", OleDbType.Date).Value = CDate(Data)
.Add("#localizacao", OleDbType.VarChar, 50).Value = localizacao
.Add("#peido", OleDbType.VarChar).Value = pedido
.Add("#codigo", OleDbType.Integer).Value = codigo
End With
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
MessageBox.Show("Actualizado com sucesso")
CARROSTableAdapter1.Fill(STOCKDataSet1.CARROS) 'No way for me to check this
End Sub
Private Sub Search(locali As String)
Dim dt As New DataTable
Using cn As New OleDbConnection("Your connection string")
Using cmd As New OleDbCommand("Select *
FROM CARROS
WHERE (processo LIKE #processo) OR
(estado LIKE #estado) OR
(localizacao Like #localizacao) OR
(tecnico Like #tecnico);", cn)
With cmd.Parameters
.Add("#processo", OleDbType.VarChar).Value = "%" & locali & "%"
.Add("#estado", OleDbType.VarChar).Value = "%" & locali & "%"
.Add("#localizacao", OleDbType.VarChar).Value = "%" & locali & "%"
.Add("#tecnico", OleDbType.VarChar).Value = "%" & locali & "%"
End With
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
If dt.Rows.Count > 0 Then
CARROSDataGridView.DataSource = Nothing
CARROSDataGridView.DataSource = dt
Else
MessageBox.Show("No matching records found")
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Se não tem valor Erro
If pesqtxt.Text = "" Then
MsgBox("Introduz um Valor")
Return
End If
Search(pesqtxt.Text)
End Sub
Try the Refresh option on the grid after you have loaded the updated data.
CARROSDataGridView.DataSource = ds.Tables(0)
CARROSTableAdapter1.Update(STOCKDataSet1.CARROS)
CARROSTableAdapter1.Fill(STOCKDataSet1.CARROS)
CARROSDataGridView.Refresh

VB.NET:Updating record in Ms Access

I am creating an employee timing sheet in which they have to insert their timings through pressing timein and timeout buttons. For timein I am creating a new record in database, for that person, and for timeout I am using UPDATING command to update that existing record. Here is my code:
Dim cb As New OleDb.OleDbCommandBuilder(ssda)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
con.ConnectionString = dbProvider & dbSource
con.Open()
Dim str As String
str = "UPDATE emp_timing SET emp_timing.emp_timeout = '" & OnlyTime & "' WHERE (((emp_timing.emp_code)='" & TextBox1.Text & "') AND ((emp_timing.day)=" & Now.ToString("MM/dd/yyyy") & "))"
Dim cmd As OleDbCommand = New OleDbCommand(str, con)
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
con.Close()
MsgBox("Data added")
TextBox1.Clear()
TextBox2.Clear()
TextBox1.Focus()
ComboBox1.SelectedIndex = -1
Catch ex As Exception
MsgBox(ex.Message)
End Try
My code is working fine but the problem is that it is not updating records in database.
Datatype for fields in Access:
emp_code = Number, emp_timeout = Text, day = Date/Time.
As usual this is caused by your code not using the Parameters collection to pass values to the database engine. This is not really understood until you hit a conversion problem as always happens with dates
str = "UPDATE emp_timing SET emp_timeout = #p1 " & _
"WHERE emp_code = #p2 AND day = #p3"
Using con = new OleDbConnection( dbProvider & dbSource)
Using cmd = New OleDbCommand(str, con)
con.Open()
cmd.Parameters.Add("#p1", OleDbType.VarWChar).Value = OnlyTime
cmd.Parameters.Add("#p2", OleDbType.Integer).Value = Convert.ToInt32(TextBox1.Text)
cmd.Parameters.Add("#p3", OleDbType.Date).Value = new DateTime(Now.Year, Now.Month, Now.Day)
Try
Dim rowsAdded = cmd.ExecuteNonQuery()
if rowsAdded > 0 Then
MsgBox("Data added")
TextBox1.Clear()
TextBox2.Clear()
TextBox1.Focus()
ComboBox1.SelectedIndex = -1
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
End Using

Connection is not closed (vb)

Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogin.Click
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Jen\Documents\Jade\vb\database.accdb")
txtAdmin.Text = "Admin"
Dim strsql As New OleDbCommand("select * from Account where Username ='" & txtUsername.Text & "' AND [Password] ='" & txtPassword.Text & "' AND AccountType = '" & txtAdmin.Text & "'", conn)
Dim strsql2 As New OleDbCommand("select * from Account where Username ='" & txtUsername.Text & "' AND [Password] ='" & txtPassword.Text & "' AND AccountType = '" & txtStudent.Text & "'", conn)
Dim uu As New OleDbParameter("UserName", txtUsername.Text)
Dim pp As New OleDbParameter("Password", txtPassword.Text)
strsql.Connection.Open()
strsql2.Connection.Open()
Dim reader As OleDbDataReader
reader = strsql.ExecuteReader
Dim reader2 As OleDbDataReader
reader2 = strsql2.ExecuteReader
If reader.HasRows Then
strsql.Connection.Close()
MsgBox(" Welcome Admin!", vbInformation)
frmIndex.Show()
desktopFade.Close()
ElseIf reader2.HasRows Then
strsql2.Connection.Close()
MsgBox(" Welcome Student!", vbInformation)
frmReg.Show()
desktopFade.Close()
ElseIf txtUsername.Text = "" And txtPassword.Text = "" Then
MsgBox("Don't leave the fields blank", vbCritical)
txtUsername.Focus()
Else
MsgBox("Your Username or Password is invalid", MsgBoxStyle.Critical)
Me.txtUsername.Text = ""
Me.txtPassword.Text = ""
Me.txtUsername.Focus()
strsql.Connection.Close()
strsql2.Connection.Close()
End If
The error here is the strsql2.connection.open() <--- it says that the connection is not close. still open.
I edited your question because you tagged it VBA and this is VB.NET
You have several problems with your code.
You should add Error trapping with Try Catch and also your connection is not always closed
To only fix the actual issue, test if the connection is open before trying to open it
If strsql2.Connection.State = ConnectionState.Open Then
Console.WriteLine("COnnection already open, closing it")
strsql2.Connection.Close()
End If
strsql2.Connection.Open()

Error in updating MS Access database with Visual Basic 2010

This code is not working. An error message pops up saying:
Syntax Error (missing operator) in query exprssion SubName = Gussing Game.
Here is my code please help. I need this code to update the Microsoft Access Database.
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
Dim Str As String
Con.Open()
Str = "update vb set AssignDate="
Str += """" & txtADate.Text & """"
Str += "where SubName = "
Str += txtAName.Text.Trim()
Cmd = New OleDbCommand(Str, Con)
Cmd.ExecuteNonQuery()
Con.Close()
Con.Open()
Str = "update vb set DueDate="
Str += """" & txtDDate.Text & """"
Str += "where SubName = "
Str += txtAName.Text.Trim()
Cmd = New OleDbCommand(Str, Con)
Cmd.ExecuteNonQuery()
Con.Close()
Con.Open()
Str = "update vb set Weight="
Str += """" & txtWeight.Text & """"
Str += "where SubName = "
Str += txtAName.Text.Trim()
Cmd = New OleDbCommand(Str, Con)
Cmd.ExecuteNonQuery()
Con.Close()
Con.Open()
Str = "update vb set Reference="
Str += """" & txtReference.Text & """"
Str += "where SubName = "
Str += txtAName.Text.Trim()
Cmd = New OleDbCommand(Str, Con)
Cmd.ExecuteNonQuery()
Con.Close()
Con.Open()
Str = "update vb set Comment="
Str += """" & txtComment.Text & """"
Str += " where SubName ="
Str += txtAName.Text.Trim()
Cmd = New OleDbCommand(Str, Con)
Cmd.ExecuteNonQuery()
Con.Close()
Con.Open()
Str = "update vb set Statues="
Str += """" & txtStatues.Text & """"
Str += " where SubName ="
Str += txtAName.Text.Trim()
Cmd = New OleDbCommand(Str, Con)
Cmd.ExecuteNonQuery()
Con.Close()
Dst.Clear()
Dad = New OleDbDataAdapter("SELECT * FROM vb ORDER BY SubName", Con)
Dad.Fill(Dst, "assignment")
MessageBox.Show("Record Updated!", "Caution", MessageBoxButtons.OK, MessageBoxIcon.Error)
Catch ex As Exception
MsgBox(ex.Message & "," & ex.Source)
End Try
Con.Close()
End Sub
You didn't quote the string scalar you compare SubName with:
Str = "update vb set AssignDate="
Str += """" & txtADate.Text & """"
Str += "where SubName = "
Str += txtAName.Text.Trim() ' should be """"&txtAName.Text.Trim()&""""
I'll skip over what an extremely bad way of querying this is.

Retrieving/adding data from/to a stored procedure

Alright so I have this webpage that I have to create and it has 3 pages and a master page. Now basically all of it is working, except the fact that I can't seem to get data coming into the webpage when requested via a retrieve button, nor will it update or add data to the SQL table. Now in my queries page when I put Select * From Customer it brings back the data in the table so that part works. From what I have to work with in the pdf's provided, they want me to use
TextBox1.Text = table.Rows(0).Field<string>("TextBox1")
TextBox1.DataBind()
To retrieve the data from the sql, now it comes up with an error saying Overload resolution failed because no accessible 'Field' accepts this number of arguments.
So here is my Customer page
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Data.DataRowCollection
Public Class Customer
Inherits System.Web.UI.Page
Dim conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("dbConnection1").ConnectionString)
Shadows adapter As SqlDataAdapter = New SqlDataAdapter()
// Tells me to use Shadows because variable adapter conflicts with property 'adapter'
Dim table As DataTable = New DataTable()
Dim command As SqlCommand = New SqlCommand()
Protected Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Try
conn = New SqlConnection(ConfigurationManager.ConnectionStrings("dbConnection1").ConnectionString)
Dim command As SqlCommand = New SqlCommand()
command.Connection = conn
command.CommandType = CommandType.Text
command.CommandText = "INSERT INTO Acme_Customer VALUES(" & txtCustID.Text & ",'" & txtFirstname.Text & "', '" & txtSurname.Text & "', " & txtGender.Text & ", " + txtAge.Text & ", " & txtAddress1.Text & ", " & txtAddress2.Text & ", " & txtCity.Text & ", " + txtPhone.Text & ", " + txtMobile.Text & ", " & txtEmail.Text & ")"
command.Connection.Open()
adapter.InsertCommand = command
adapter.InsertCommand.ExecuteNonQuery()
command.Connection.Close()
Clear()
lblMessage.Text = "You have been successfully added into our records"
Catch ex As Exception
lblMessage.Text = "Something has gone wrong with adding you to our records, please double check everything as we want you to become a member."
End Try
End Sub
Protected Sub btnRetrieve_Click(sender As Object, e As EventArgs) Handles btnRetrieve.Click
Try
command.Connection = conn
command.CommandType = CommandType.StoredProcedure
command.CommandText = "GetCustomer"
command.Connection.Open()
Dim param As SqlParameter = New SqlParameter()
param.ParameterName = "#ID"
param.SqlDbType = SqlDbType.Int
param.Direction = ParameterDirection.Input
param.Value = txtCustID.Text
command.Parameters.Add(param)
adapter.SelectCommand = command
adapter.Fill(table)
txtFirstname.Text = table.Rows(0).Field<string>("Firstname")
txtFirstname.DataBind()
txtSurname.Text = table.Rows(0).Field<string>("Surname")
txtSurname.DataBind()
txtGender.Text = table.Rows(0).Field<String>("Gender")
txtGender.DataBind()
txtAge.Text = table.Rows(0).Field<Integer>("Age")
txtAge.DataBind()
txtAddress1.Text = table.Rows(0).Field<String>("Address1")
txtAddress1.DataBind()
txtAddress2.Text = table.Rows(0).Field<String>("Address2")
txtAddress2.DataBind()
txtCity.Text = table.Rows(0).Field<String>("City")
txtCity.DataBind()
txtPhone.Text = table.Rows(0).Field<Integer>("Phone Number")
txtPhone.DataBind()
txtMobile.Text = table.Rows(0).Field<Integer>("Mobile Number")
txtMobile.DataBind()
txtEmail.Text = table.Rows(0).Field<String>("Email")
txtEmail.DataBind()
Catch ex As Exception
lblMessage.Text = "The ID you have entered doesn't exist."
End Try
End Sub
So I'm just wondering what I've written wrong or if I should be using other code instead of what I have here, I know I should be using C# but I just got the hang of vb so, hopefully I can just start using C# after this project.
Protected Sub btnRetrieve_Click(sender As Object, e As EventArgs) Handles btnRetrieve.Click
Try
command.Connection = conn
command.CommandType = CommandType.StoredProcedure
command.CommandText = "GetCustomer"
command.Connection.Open()
Dim param As SqlParameter = New SqlParameter()
param.ParameterName = "#ID"
param.SqlDbType = SqlDbType.Int
param.Direction = ParameterDirection.Input
param.Value = txtCustID.Text
command.Parameters.Add(param)
adapter.SelectCommand = command
adapter.Fill(table)
dim objDV as dataview = table.defaultview
txtFirstname.Text = objDV(0)("Firstname").tostring
txtSurname.Text = objDV(0)("Surname").tostring
' Fill all other text boxes following above lines
Catch ex As Exception
lblMessage.Text = "The ID you have entered doesn't exist."
End Try
End Sub