I have just started learning VB.net for several weeks. i want to make a form and send data from a text box to a specific cell in ms access database (*.accdb) file. but the code i have writen gives the following error:
Syntax error in UPDATE statement.
i have checked several books and spent hours on internet, but no answer!
Dim con As New OleDb.OleDbConnection
Dim ds As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim sql As String
Dim cnn1 As New OleDb.OleDbConnection
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=
E:\Ebook\hararat\GUI\Heat Exchanger Designer\heat.accdb"
con.Open()
sql = "SELECT * FROM flow1"
da = New OleDbDataAdapter(sql, con)
da.Fill(ds, "flow1")
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("flow1").Rows(1).Item(1) = "name"
da.Update(ds, "flow1")
con.Close()
You need to use the .QuotePrefix and .QuoteSuffix properties of the OleDbCommandBuilder to wrap table and field names in square brackets. That is, instead of just
Dim cb As New OleDb.OleDbCommandBuilder(da)
you need to do
Dim cb As New OleDb.OleDbCommandBuilder(da)
cb.QuotePrefix = "["
cb.QuoteSuffix = "]"
That will generate an UPDATE statement of the form
UPDATE [TableName] SET [ColumnName]= ...
which is necessary if the table name or any of the field names happen to be reserved words in Access SQL.
Try this one
dim sqlupdate as string = "UPDATE tablename SET column_name = '" & textname.text & "' WHERE column_name = '" & textname.text & "'"
Sometimes errors occur when using the following column names: Username, Password, Date, Time, and much more of this type, try to avoid these column names because this might cause the problem of your issue regarding updating tables. Enable for you to update this kind of column name you need to enclose it with [ and ] so it comes like this: [Username], [Date], etc. so the syntax might go like this:
UPDATE tablename SET [Username] = '" & textname.text & "' WHERE column_name = '" & textname.text & "'"
my codes goes like this:
Open_Con()
Dim sqlUpdate As String
Dim sqlUpdatePass As DialogResult
sqlUpdate = "UPDATE tblAccounts SET [Password] = '" & txtRPassword.Text & "' WHERE [Username] = '" & txtUsername.Text & "'"
sqlCmd = New OleDbCommand(sqlUpdate, sqlCon)
Try
sqlUpdatePass = MessageBox.Show("Are you sure to save this changes?", "Save changes?", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If sqlUpdatePass = vbYes Then
sqlCmd.ExecuteNonQuery()
MsgBox("Changes are now saved", MsgBoxStyle.Information, "New password has been set.")
Call ClearAll()
Me.Hide()
Else
Exit Sub
End If
Catch ex As Exception
MsgBox("Could not perform this task because " & ex.Message, MsgBoxStyle.Exclamation, "Error")
End Try
sqlCmd = Nothing
sqlCon.Close()
hope this things mention above codes helps your problem. have a nice day and happy coding :)
dim sqlupdate as string="UPDATE [tablename] SET [column_name] = '"& textname.text &"' WHERE [column_name] = '"& textname.text &"';"
By enclose attributes with square brackets, it appears to work I have tried it, it works
Imports System.Data.OleDb
Imports System.Data
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'Database2DataSet.identitas' table. You can move, or remove it, as needed.
Me.IdentitasTableAdapter.Fill(Me.Database2DataSet.identitas)
End Sub
Public Sub clean()
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
End Sub
Public Sub read()
Call openconn()
str = "select * from identitas"
dtadapter = New OleDbDataAdapter(str, con)
Dim dg As New DataTable
dg.Clear()
dtadapter.Fill(dg)
dgv.DataSource = dg
End Sub
Public Sub create()
Call openconn()
str = "insert into identitas values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "') "
cmd = New OleDbCommand(str, con)
cmd.Connection = con
cmd.ExecuteNonQuery()
MsgBox("data lebet")
read()
clean()
End Sub
Public Sub update()
Call openconn()
str = "UPDATE identitas SET [Nama] = '" & TextBox2.Text & "',[Alamat] = '" & TextBox3.Text & "', [No] = '" & TextBox4.Text & "' where [NIK] = '" & TextBox1.Text & "'"
cmd = New OleDbCommand(str, con)
cmd.Connection = con
cmd.ExecuteNonQuery()
MsgBox("data ter ubah")
clean()
read()
End Sub
Public Sub delete()
Call openconn()
str = "delete from identitas where NIK = '" & TextBox1.Text & "'"
cmd = New OleDbCommand(str, con)
cmd.Connection = con
cmd.ExecuteNonQuery()
clean()
End Sub
Private Sub btnclose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnclose.Click
Me.Close()
End Sub
Private Sub btnc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnc.Click
create()
End Sub
Private Sub btnr_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnr.Click
read()
End Sub
Private Sub btnclean_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnclean.Click
clean()
End Sub
Private Sub btnd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnd.Click
Dim pesan As String = MsgBox("yakin mau hapus = " & TextBox1.Text & "?", MsgBoxStyle.YesNo)
If pesan = vbYes Then
delete()
End If
read()
End Sub
Private Sub btnu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnu.Click
update()
End Sub
End Class
I had same problem, this helped.
"Sometimes errors occur when using the following column names: Username, Password, Date, Time, and much more of this type, try to avoid these column names because this might cause the problem of your issue regarding updating tables. Enable for you to update this kind of column name you need to enclose it with [ and ] so it comes like this: [Username], [Date], etc. so the syntax might go like this: "
I renamed the columns in Access (e.g Password1,Username1) as the same words password, username might be reserved in vb.net. Thanks for this response.
Related
I'm trying to refresh the DataGridView right after executing an SQL Command, so when the user presses the update button all details must change as well as the DataGridView. This is my code and I don't know where to add this function.
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click, Button5.Click
Try
Dim a As String
cn.Open()
Dim cmd As New System.Data.SqlClient.SqlCommand
cmd = New SqlCommand("update Addemployees set Fname= '" & TextBox1.Text & "', Lname= '" & TextBox3.Text & "', ID= '" & TextBox4.Text & "', CIN= '" & TextBox2.Text & "', phone= '" & TextBox6.Text & "', Email= '" & TextBox5.Text & "', fromD= '" & TextBox8.Text & "', toD= '" & TextBox7.Text & "' where ID='" & ComboBox1.Text & "' ", cn)
cmd.Connection = cn
a = cmd.ExecuteNonQuery()
MessageBox.Show("Process successful!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information)
cn.Close()
Catch
MessageBox.Show("Error!", "exit", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
cn.Dispose()
End Try
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox5.Clear()
TextBox6.Clear()
TextBox7.Clear()
TextBox8.Clear()
DateTimePicker2 = Nothing
DateTimePicker1 = Nothing
End Sub
You can just create a Method or a Function that displays data in the DATAGRIDVIEW and then call the method whenever you add/delete/update just be sure to add/delete/update first before calling the method or function
Sub display()
Dim temp As Double = 0
Dim lt As String = "select id as ID, vlname as Last, vfname as First,
vmname as Middle, vgnd as Gender, vdob as Birthday, iage as
Age, vcourse as Course from tbreg where vlname Like '" +
tbsearch.Text + "%' or vfname Like '" + tbsearch.Text + "%'
order by vlname asc"
Dim da As New MySqlDataAdapter(lt, con)
con.Open()
Dim ds As New DataSet
da.Fill(ds, "tbreg")
da.Dispose()
dgv.DataSource = ds.Tables(0)
con.Close()
End Sub
Just add the display() method right after saving/deleting/updating your database
'updating and then refreshing the datagridview right after doing the update you
just have to call the method
Dim supdate As String = "Update tbuser set vname = '" & tbname.Text & "',
vemail = '" & tbemail.Text & "', vuser = '" &
tbuser.Text & "', vpass = '" & tbpass.Text & "' where
vid = '" & dgv.SelectedCells(0).Value & "'"
Dim cmd As New MySqlCommand(supdate, con)
con.Open()
cmd.ExecuteNonQuery()
MsgBox("Successfully Updated!!!", MsgBoxStyle.Information,
"System COnfirmed!")
con.Close()
'display method here!
display()
You can do one thing here. After the save is successful, call the procedure you used to view the contents in DataGridView This works.
I will show you my example:
I have a student attendance adding/viewing form. There is a TabControl with two tabs, one for adding and another for viewing.
In the add tab, there is a button which submits the attendance of students to a database. After the submission is done, I then show a message like this:
Private Sub SubmitBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SubmitBtn.Click
'{rest of the code}
'add attendance success
MsgBox("Attendance added for " & yyyy_txt.Text & "/" & mm_txt.Text & "/" & dd_txt.Text, MsgBoxStyle.Information)
End Sub
In the view tab, there are few option on how the user wants to see the attendance record which is done by selecting option from ComboBoxes and then clicking the SearchBtn button.
'search attendance
Private Sub SearchBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SearchBtn.Click
If SelectClass2.Text = "" Or SearchType.Text = "" Or SearchKey.Text = "" Then
MsgBox("Select search options to continue", MsgBoxStyle.Critical)
Else
If SearchType.Text = "By Date" Then
'search by date, call procedure 'displayatt'
Dim xyz As String = SearchKey.Text.Substring(0, 5)
displayatt(SearchKey.Text, SelectClass2.Text, String.Format("YYYY/MM/DD", xyz), True)
Else
'search by student, call procedure 'displayatt'
displayatt(SearchKey.Text.Substring(3, SearchType.Text.Length - 3), SelectClass2.Text, SearchKey.Text.Substring(0, 5), False)
End If
End If
End Sub
Well, you can update the DataGridView1 contents by calling the procedure which shows the contents. In my case, I would add SearchBtn_Click(SearchBtn, Nothing) right after showing the messagebox about the completion of adding the attendance. Then it will look like this:
Private Sub SubmitBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SubmitBtn.Click
'{rest of the code}
'add attendance success
MsgBox("Attendance added for " & yyyy_txt.Text & "/" & mm_txt.Text & "/" & dd_txt.Text, MsgBoxStyle.Information)
SearchBtn_Click(SearchBtn, Nothing)
End Sub
Try it. :)
Use this class for Microsoft SQL and see the LoadDB for how to use it. Also don't hardcode you query like you did. Someone using your app could do SQL injection and drop your tables. Use params like I showed you. You probably also want to update only a specific record so add the WHERE instruction in your query
Sub LoadDB
dim xdb as new dbMSSQL
dim SQLQuery as String = "update Addemployees set fname=#colfname, lname=#collanme, etc WEHRE ID=#colID"
xdb.addparam("#colid",RecordID)
xdb.addparam("#colfname",textbox1.text)
xdb.addparam("#collname",textbox2.text)
.......
xdb.execquery(Sqlquery)
datagridview1.datasource=xdb.dbdt
end sub
Imports System.Data.SqlClient
Public Class dbMSSQL
' CREATE YOUR DB CONNECTION
Public SQLSource As String = "Data Source=[yourcomputer]\sqlexpress;Integrated Security=True"
Private DBCon As New SqlConnection(SQLSource)
'Private DBCon As New MySqlConnection(SQLSource)
' PREPARE DB COMMAND
Private DBCmd As SqlCommand
' DB DATA
Public DBDA As SqlDataAdapter
Public DBDT As DataTable
' QUERY PARAMETERS
Public Params As New List(Of SqlParameter)
' QUERY STATISTICS
Public RecordCount As Integer
Public Exception As String
Public Sub ExecQuery(Query As String)
' RESET QUERY STATS
RecordCount = 0
Exception = ""
Try
' OPEN A CONNECTION
DBCon.Open()
' CREATE DB COMMAND
DBCmd = New SqlCommand(Query, DBCon)
' LOAD PARAMS INTO DB COMMAND
Params.ForEach(Sub(p) DBCmd.Parameters.Add(p))
' CLEAR PARAMS LIST
Params.Clear()
' EXECUTE COMMAND & FILL DATATABLE
DBDT = New DataTable
DBDA = New SqlDataAdapter(DBCmd)
RecordCount = DBDA.Fill(DBDT)
Catch ex As Exception
Exception = ex.Message
End Try
' CLOSE YOUR CONNECTION
If DBCon.State = ConnectionState.Open Then DBCon.Close()
End Sub
' INCLUDE QUERY & COMMAND PARAMETERS
Public Sub AddParam(Name As String, Value As Object)
Dim NewParam As New SqlParameter(Name, Value)
Params.Add(NewParam)
End Sub
End Class
here actual code from a project
Dim xDB As New mysql
xDB.AddParam("#colisconnected", 1)
xDB.AddParam("#colcpuid", CPUid)
xDB.AddParam("#colfwuid", userId)
xDB.ExecQuery("UPDATE clients.computerinfo SET isconnected=#colisconnected WHERE (cpuid=#colcpuid) and (customerid=#colfwuid)")
First I populated the datagridview by data of sqlserver 2008 database table, now i have muliple rows in datagridview containing data, i am trying to update any row but, in the database table it replaces other rows data by the row data that iam trying to update
the code for update statement is given below
Plz help me
Dim cmd As New SqlCommand("Update EmployeeDetail Set Salary = '" &
dgvEmpDetail.Rows(0).Cells(1).Value & "', Experience ='" &
dgvEmpDetail.Rows(0).Cells(2).Value & "', Skills='" &
dgvEmpDetail.Rows(0).Cells(3).Value
& "' where Emp_ID = '" & dgvEmpDetail.Rows(0).Cells(0).Value & "'", con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
You've hard coded the row - dgvEmpDetail.Rows(0).
I imagine you are calling this in a loop. You should do something like:
For i As Integer = 0 To dgvEmpDetail.Rows.Count - 1
Dim cmd As New SqlCommand("Update EmployeeDetail Set Salary = '" & dgvEmpDetail.Rows(i).Cells(1).Value & "', Experience ='" & dgvEmpDetail.Rows(i).Cells(2).Value & "', Skills='" & dgvEmpDetail.Rows(i).Cells(3).Value()& "' where Emp_ID = '" & dgvEmpDetail.Rows(i).Cells(0).Value & "'", con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Next
Your code is susceptible to SQL injection. You should put the update SQL in to a stored procedure - its faster and safer!
Protected Sub Page_Load()
If Not Page.IsPostBack Then
' Create a new table.
Dim taskTable As New DataTable("TaskList")
' Create the columns.
taskTable.Columns.Add("Id", GetType(Integer))
taskTable.Columns.Add("Description", GetType(String))
taskTable.Columns.Add("IsComplete", GetType(Boolean))
'Add data to the new table.
For i = 0 To 19
Dim tableRow = taskTable.NewRow()
tableRow("Id") = i
tableRow("Description") = "Task " + i.ToString()
tableRow("IsComplete") = False
taskTable.Rows.Add(tableRow)
Next
'Persist the table in the Session object.
Session("TaskTable") = taskTable
'Bind data to the GridView control.
BindData()
End If
End Sub
Protected Sub TaskGridView_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
TaskGridView.PageIndex = e.NewPageIndex
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub TaskGridView_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
'Set the edit index.
TaskGridView.EditIndex = e.NewEditIndex
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub TaskGridView_RowCancelingEdit()
'Reset the edit index.
TaskGridView.EditIndex = -1
'Bind data to the GridView control.
BindData()
End Sub
Protected Sub TaskGridView_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
'Retrieve the table from the session object.
Dim dt = CType(Session("TaskTable"), DataTable)
'Update the values.
Dim row = TaskGridView.Rows(e.RowIndex)
dt.Rows(row.DataItemIndex)("Id") = (CType((row.Cells(1).Controls(0)), TextBox)).Text
dt.Rows(row.DataItemIndex)("Description") = (CType((row.Cells(2).Controls(0)), TextBox)).Text
dt.Rows(row.DataItemIndex)("IsComplete") = (CType((row.Cells(3).Controls(0)), CheckBox)).Checked
'Reset the edit index.
TaskGridView.EditIndex = -1
'Bind data to the GridView control.
BindData()
End Sub
Private Sub BindData()
TaskGridView.DataSource = Session("TaskTable")
TaskGridView.DataBind()
End Sub
</script>
I have a access connection with textbox as data feeder to database change it to SQL if u want. The code is:
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class Form2
Dim conaccess As New OleDbConnection
Dim conreader As OleDbDataReader
Dim concmd As New OleDbCommand
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DataGridView1.EditMode = False
conaccess.ConnectionString = "Provider=Microsoft.jet.oledb.4.0;data source=d:\vijay.mdb"
conaccess.Open()
loadGrid()
End Sub
Private Sub loadGrid()
Dim access As String
access = "select * from vijay"
Dim DataTab As New DataTable
Dim DataAdap As New OleDbDataAdapter(access, conaccess)
DataAdap.Fill(DataTab)
DataGridView1.DataSource = DataTab
End Sub
Private Sub new_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles new_btn.Click
Dim no As String
no = "select Max(ID) from vijay"
Dim concmd As New OleDbCommand(no, conaccess)
conreader = concmd.ExecuteReader
If (conreader.Read) Then
If (IsDBNull(conreader(0))) Then
id_txt.Text = "1"
Else
id_txt.Text = conreader(0) + 1
End If
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End If
End Sub
Private Sub DataGridView1_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellClick
Dim i As Integer
i = DataGridView1.CurrentRow.Index
Try
id_txt.Text = DataGridView1.Item(0, i).Value
name_txt.Text = DataGridView1.Item(1, i).Value
class_txt.Text = DataGridView1.Item(2, i).Value
gen_txt.Text = DataGridView1.Item(3, i).Value
branch_txt.Text = DataGridView1.Item(4, i).Value
age_txt.Text = DataGridView1.Item(5, i).Value
Catch ex As Exception
End Try
End Sub
Private Sub del_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles del_btn.Click
Dim delcmd As New OleDbCommand("delete from vijay where id=" & id_txt.Text & " ", conaccess)
delcmd.ExecuteNonQuery()
MsgBox("Record is deleted")
loadGrid()
id_txt.Clear()
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End Sub
Private Sub save_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles save_btn.Click
Dim access As String = String.Format("INSERT INTO vijay (Name,Class,Branch,Gender,Age) VALUES('{0}','{1}','{2}','{3}','{4}')", name_txt.Text, class_txt.Text, branch_txt.Text, gen_txt.Text, age_txt.Text)
concmd.Connection = conaccess
concmd.CommandText = access
concmd.ExecuteNonQuery()
MsgBox("Record Successfully Saved")
loadGrid()
id_txt.Clear()
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End Sub
Private Sub up_btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles up_btn.Click
Dim access As String
access = "UPDATE vijay SET Name = '" & name_txt.Text & "', Age = '" & age_txt.Text & "', Gender ='" & gen_txt.Text & "' , Branch ='" & branch_txt.Text & "' , Class = '" & class_txt.Text & "' where id=" & id_txt.Text & ""
Dim cmd As New OleDbCommand(access, conaccess)
cmd.ExecuteNonQuery()
loadGrid()
id_txt.Clear()
name_txt.Clear()
branch_txt.Clear()
age_txt.Clear()
class_txt.Clear()
gen_txt.Clear()
End Sub
End Class
Use looping and parameter (to handle sql injection):
con.Open() 'Open connection to database
'Looping throung dgv
For i As Integer = 0 To dgvEmpDetail.Rows.Count - 1
If IsDBNull(dgvEmpDetail.Rows(i).Cells("Emp_ID").Value) Then Exit For
Dim cmd As New SqlCommand("Update EmployeeDetail Set [Salary] = ?, [Experience]=?, [Skills]=? WHERE [Emp_ID] =?", con)
With cmd.Parameters
.AddWithValue("#Salary", dgvEmpDetail.Rows(i).Cells("Salary").Value )
.AddWithValue("#Experience", dgvEmpDetail.Rows(i).Cells("Experience").Value )
.AddWithValue("#Skills", dgvEmpDetail.Rows(i).Cells("Skills").Value )
.AddWithValue("#Emp_ID", dgvEmpDetail.Rows(i).Cells("Emp_ID").Value )
End With
cmd.ExecuteNonQuery()
Next i
con.Close() 'Close connection with Database
I have ID, FullName , Age, Sex as textbox and similar column in database.
Below is my code for search from database by ID.
But i don;t know how to update after search these data.
Imports System.Data.OleDb
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Src_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Src.Click
Form2.Show()
Dim Connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Satyam\Documents\Satyam.accdb;" & "Persist Security Info=False;" & "Jet OLEDB:Database Password=" & "your pass" & ";")
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Try
Connection.Open()
cmd = New OleDbCommand("SELECT * from DailyWorkLoadRegister WHERE ID=" & txtID.Text & "", Connection)
dr = cmd.ExecuteReader
If dr.Read Then
Form2.txtID.Text = dr("ID")
Form2.txtAge.Text = dr("Age")
Form2.txtSex.Text = dr("Sex")
Form2.txtFullName.Text = dr("FullName")
dr.Close()
Else
MsgBox("No Record")
End If
Catch
End Try
Connection.Close()
End Sub
End Class
You would need to execute a non-query method which returns:
For UPDATE, INSERT, and DELETE statements, the return value is the
number of rows affected by the command. For all other types of
statements, the return value is -1. If a rollback occurs, the return
value is also -1.
Microsoft documentation -> Here
Which is as simple as:
Dim ID : ID = Form2.txtID.Text
Dim Age : Age = Form2.txtAge.Text
Dim Sex : Sex = Form2.txtSex.Text
Dim FN : FN = Form2.txtFullName.Text
Dim command As New OleDbCommand("UPDATE YOUR_TABLE_NAME SET _
FullName = '" & FN & "',_
Age = '" & Age & "',_
Sex = '" & Sex & "'_
WHERE ID = '" & ID & "'", Connection)
command.ExecuteNonQuery()
Someone help me
I am working on our project and I need to check if my DB has already 20 records.
If so, then it will not accept records anymore.
I've been trying the codes below:
Public Class Form1
Dim con As New OleDb.OleDbConnection
Dim ds, ds2 As New DataSet
Dim da, da2 As OleDb.OleDbDataAdapter
Dim sql, sql1 As String
Dim int As Integer
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
con.ConnectionString = "Provider=Microsoft.jet.OLEDB.4.0; data source = |datadirectory|\Database6.mdb"
con.Open()
Dim cmd As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM Accounts WHERE Username='" & TextBox1.Text & "'", con)
Dim sdr As OleDb.OleDbDataReader = cmd.ExecuteReader
Dim cmd1 As OleDb.OleDbCommand = New OleDb.OleDbCommand("SELECT * FROM Accounts")
sql = "INSERT INTO Accounts ([Username], [Password], [FirstName], [LastName]) VALUES ('" & TextBox1.Text & "','" & TextBox2.Text & "', '" & TextBox3.Text & "','" & TextBox4.Text & "') "
sql1 = "SELECT Count([AccountID]) FROM Accounts"
cmd = New OleDb.OleDbCommand(sql, con)
cmd1 = New OleDb.OleDbCommand(sql1, con)
Convert.ToInt32(sql1)
cmd1.ExecuteScalar()
If sql1 < 20 Then
MsgBox("Cannot accept records")
ElseIf sdr.HasRows = False Then
cmd.ExecuteNonQuery()
MsgBox("Account Added")
ElseIf sdr.HasRows = True Then
MsgBox("Username is taken")
End If
con.Close()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Me.Hide()
Form2.Show()
End Sub
End Class
But the convert code fires an error :
Input string was in incorrect format
But if I delete the convert code it gives me the error
Conversion from string "SELECT Count([AccountID]) FROM A" to type 'Double' is not valid."
Help me please.
TIA
I dont know VB all that well, this is from the top of my head. Your trying to convert your SQL text, which will never work. Try something like this:
dim result as object
result = cmd1.ExecuteScalar()
dim count as int
count = Convert.ToInt32(result)
If count < 20 Then
I'm having trouble trying to read from a MySQL databse using VB.NET, the error message I get is "ArgumentExcpetion was unhandled"
Also, the reading should return 'F', since this is the value allocated on that specific place on the table.
Imports MySql.Data.MySqlClient
Public Class Form1
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Application.Exit()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim query As String = "SELECT DO FROM klein WHERE COMMAND='DELETE'"
Dim connStr As String = "server=" & TextBox1.Text & ";" _
& "user id=" & TextBox2.Text & ";" _
& "password=" & TextBox3.Text & ";" _
& "database=hidro201_liberato"
Dim connection As New MySqlConnection(connStr)
Dim cmd As New MySqlCommand(query, connection)
connection.Open()
Dim reader As MySqlDataReader
reader = cmd.ExecuteReader()
While reader.Read()
TextBox4.Text = (reader.GetChar(1)) '<- **problem is here**
End While
End Sub
End Class
The field index is zero based.
TextBox4.Text = (reader.GetChar(0))
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getchar.aspx
Parameter i: "The zero-based column ordinal."
You have only one column in your query and the index of the column should be zero
TextBox4.Text = (reader.GetChar(0))
This is for SqlServer but the rules are the same for a MySqlDataReader
TextBox4.Text = (reader.GetChar("Name of column to get the value"))
All the best