check the update command, m i doing mistake in its syntax? - sql

his there all,
i'm working on a cms, while trying the update command to update the records, its not working.
here's m complete code for update,
Dim ID, RegNo, BedNo, BedType, Charges, PatName, PatAge, PatAddr, Phone, CheckupDate, Disease, BloodGroup, Doctor, Remarks As String
RegNo = txtRegNo.Text
BedNo = CmbBedNo.SelectedItem.ToString()
BedType = CmbBedType.SelectedItem.ToString()
Charges = txtCharges.Text
PatName = txtPatName.Text
PatAge = txtPatAge.Text
PatAddr = txtPatAdd.Text
Phone = txtPhone.Text
CheckupDate = txtDate.Text
Disease = txtDisease.Text
BloodGroup = cmbBloodGrp.SelectedItem.ToString()
Doctor = cmbDoctor.SelectedItem.ToString()
Remarks = txtRemarks.Text
ID = txtRegNo.Text
Dim conStudent As New OleDbConnection
Dim comStudent As New OleDbCommand
conStudent.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\DBProject\hspms.mdb"
conStudent.Open()
comStudent.CommandText = "UPDATE AdmitPt SET ID =" & ID & ", Bedcategory='" & BedType & "', BedNo=" & BedNo & ", BedCharges=" & Charges & ", PtName='" & PatName & "', PtAge=" & PatAge & ", Address='" & PatAddr & "', PhoneNo='" & Phone & "', Dates='" & CheckupDate & "', Disease='" & Disease & "', BloodGroup='" & BloodGroup & "', Doctor='" & Doctor & "', Remarks='" & Remarks & "' WHERE ID=" & RegNo
comStudent.Connection = conStudent
comStudent.CommandType = CommandType.Text
If (comStudent.ExecuteNonQuery() > 0) Then
MsgBox("record successfully updated")
End If
conStudent.Close()
one thing, that the fields named with ID, BedNo, BedCharges, Age are set to Number as data type.

First of all, switch to a parameterized query. This will remove any possibilities of Sql Injection, but also avoid the problems with quoting strings, parsing decimal numbers and dates
Dim conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\DBProject\hspms.mdb"
Dim cmdText = "UPDATE AdmitPt SET ID =?, Bedcategory=?, BedNo=?, BedCharges=?, " & _
"PtName=?, PtAge=?, Address=?, PhoneNo=?, Dates=?, Disease=?, " & _
"BloodGroup=?, Doctor=?, Remarks=? WHERE ID=?"
Using conStudent = new OleDbConnection(conString)
Using comStudent = new OleDbCommand(cmdText, conStudent)
conStudent.Open()
comStudent.Parameters.AddWithValue("#p1", Convert.ToInt32(ID))
comStudent.Parameters.AddWithValue("#p2", BedType)
comStudent.Parameters.AddWithValue("#p3", Convert.ToInt32(BedNo))
comStudent.Parameters.AddWithValue("#p4", Convert.ToDecimal(Charges))
.... and so on for every other question marks in the cmdText ....
.... respecting the exact order of the fields ...................
.... try also to pass the correct datatype for every non string field
If (comStudent.ExecuteNonQuery() > 0) Then
MsgBox("record successfully updated")
End If
End Using
End Using

Related

MySqlException: Column count doesn't match value count at row 1

I am trying to save multiple data to my database with this code:
repNo = MainForm.StaffMixname.Text.Substring(0, 3) & DateTime.Now.ToString("yyyyMMddhhmmss")
MetroGrid5.DataSource = Nothing
Dim ds As DataSet = New DataSet
Dim Query As String = "SELECT ci.seq_id, CONCAT(ci.lastname, ci.firstname) AS fullname, ci.amountApplied, ci.province, co.kind, co.specifications, co.regOwner, co.location FROM clientinformation ci LEFT JOIN collateraloffered co ON ci.seq_id=co.seq_id WHERE co.kind IS NOT NULL AND ci.province = '" & MetroComboBox8.Text & "' AND ci.seq_id BETWEEN '" & convertedstrFrom.ToString("yyMMdd") & "%' AND '" & convertedstrTo.ToString("yyMMdd") & "%'"
Dim fetch As New MySqlDataAdapter(Query, connect)
fetch.Fill(ds, "collateral")
MetroGrid5.DataSource = ds.Tables("collateral")
If MetroGrid5.Rows.Count > 0 Then
Dim cm As New MySqlCommand
With cm
.Connection = connect
For i As Integer = 0 To MetroGrid5.RowCount - 1
.CommandText = _
"INSERT INTO collateralrpt Values('" & repNo & _
"', '" & MetroGrid5.Rows(i).Cells("seq_id").Value & _
"', '" & MetroGrid5.Rows(i).Cells("fullname").Value & _
"', '" & MetroGrid5.Rows(i).Cells("amountApplied").Value & _
"', '" & MetroGrid5.Rows(i).Cells("kind").Value & _
"', '" & MetroGrid5.Rows(i).Cells("specifications").Value & _
"', '" & MetroGrid5.Rows(i).Cells("regOwner").Value & _
"', '" & MetroGrid5.Rows(i).Cells("location").Value & _
"', '" & MetroGrid5.Rows(i).Cells("province").Value & "')"
.ExecuteNonQuery()
Next
End With
cm.Dispose()
cm = Nothing
With connect
.Close()
.Dispose()
End With
Else
MsgBox("No Data!")
End If
but unfortunately It shows MySqlException Column count doesn't match value count at row 1.
Is there any mistake with the code above? thanks in advance.
If you want to retrieve data from one table(s) and insert into another, just use a single data adapter. You can even do so if the tables are in a different database - you just need a different connection for the SelectCommand and InsertCommand. Only a single connection is required for a single database though. E.g.
Dim selectSql = "SELECT Column1A, Column1B FROM Table1"
Dim insertSql = "INSERT INTO Table2
(
Column2A,
Column2B
)
VALUES
(
#Column2A,
#Column2B
)"
Using connection As New MySqlConnection("connection string here"),
insertCommand As New MySqlCommand(insertSql, connection),
adapter As New MySqlDataAdapter(selectSql, connection) With {.InsertCommand = insertCommand, .AcceptChangesDuringFill = False}
With insertCommand.Parameters
.Add("#Column2A", MySqlDbType.Int, 0, "Column1A")
.Add("#Column2B", MySqlDbType.VarChar, 50, "Column1B")
End With
Dim table As New DataTable
connection.Open()
adapter.Fill(table)
adapter.Update(table)
End Using
There are a few things to note here.
I wrote the SQL code using a single, multiline literal. That is far
more readable that concatenating every line.
I used parameters. That prevents numerous issues that have been
written about ad nauseum so I won't go into it here.
There's no grid control involved here. You can add one and bind the DataTable after calling Fill but that is only so you can see the data. It has nothing to do with the actual code of retrieving and saving.
The connection is opened explicitly. You can normally let a Fill or Update call open and close the connection implicitly but, in this case, we want to perform both operations and closing and reopening the connection in between is an unnecessary overhead.
The disposable objects are created with a Using statement, which means they will be implicitly disposed at the end of the block. That inclides closing the connection.
The AcceptChangesDuringFill property of the data adapter is set to True so that all RowStates are left as Added so that all DataRows are ready to be inserted.

data is not inserted to database

i tried to insert the data into database with this code
Public Sub AddUser()
Dim con As dbConn = New dbConn()
Dim SqlSelect As String
SqlSelect = "SELECT * FROM login Where user_id='" & WorkerID_.Text & "'"
Dim cmd As New OleDbCommand(SqlSelect, con.oleconnection)
Dim reader As OleDbDataReader
Dim da As New OleDbDataAdapter
con.open()
reader = cmd.ExecuteReader()
reader.Read()
If reader.HasRows() Then
reader.Close()
con.close()
FailureText.Text = "User ID already exists!"
Else
reader.Close()
con.close()
Dim InsertSQL As String
InsertSQL = "INSERT INTO login (user_id, user_role, user_password, user_status) VALUES "
InsertSQL &= "('" & WorkerID_.Text & "', "
InsertSQL &= "'Worker', "
InsertSQL &= "'12345', 1)"
Dim SqlUpdate As String
SqlUpdate = "INSERT INTO Worker (ID, WorkerID, WorkerName, DoB, Address, Phone, Email, CompanyName, PassportNum, PassportExp, VisaExp, VisaStatus, user_id) VALUES (default,"
SqlUpdate &= "'" & WorkerID_.Text & "', "
SqlUpdate &= "'" & WorkerName.Text & "', "
SqlUpdate &= "'" & DoB.Text & "', "
SqlUpdate &= "'" & Address.Text & "', "
SqlUpdate &= "'" & Phone.Text & "', "
SqlUpdate &= "'" & Email.Text & "', "
SqlUpdate &= "'" & Company.SelectedValue & "', "
SqlUpdate &= "'" & PassNum.Text & "', "
SqlUpdate &= "'" & PassExp.Text & "', "
SqlUpdate &= "'" & VisaExp.Text & "', "
SqlUpdate &= "'No Visa', "
SqlUpdate &= "'" & WorkerID_.Text & "') "
Dim insertCommand As New OleDbCommand(SqlUpdate, con.oleconnection)
Dim cmd1 As New OleDbCommand(InsertSQL, con.oleconnection)
Try
con.open()
cmd1.ExecuteNonQuery()
insertCommand.ExecuteNonQuery()
Catch
FailureText.Text = "Unable to add user"
Finally
con.close()
End Try
End If
Response.Redirect("Workers.aspx")
End Sub
the Insert into login part is working. the data is well inserted. but for the insert into worker part is not working. the data is not inserted into the table. the program shows no error and it still can work. what could possibly wrong with this?
Read another answer on OleDb I just answered on another post. You will be wide open to sql-injection too. Parmaeterize queries. By you concatenating strings to build one command, what if one value has a single-quote within the text entry. You are now hosed. What if someone puts malicious SQL commands and then deletes your records or entire table(s). Learn to parameterize your queries and also clean values, especially if coming from a web interface.
Your commands should probably be updated something like
Dim con As dbConn = New dbConn()
Dim SqlSelect As String
SqlSelect = "SELECT * FROM login Where user_id= #parmUserID"
Dim cmd As New OleDbCommand(SqlSelect, con.oleconnection)
cmd.Parameters.AddWithValue( "parmUserID", WorkerID_.Text )
Follow-suit with the Insert and update commands... parameterize them but using #variable place-holders in your commands.
Dim InsertSQL As String
InsertSQL = "INSERT INTO login (user_id, user_role, user_password, user_status) "
InsertSQL &= " VALUES ( #parmUser, #parmRole, #parmPwd, #parmStatus )"
Dim cmdInsert As New OleDbCommand(InsertSQL, con.oleconnection)
cmdInsert.Parameters.AddWithValue( "parmUser", WorkerID_.Text )
cmdInsert.Parameters.AddWithValue( "parmRole", "Worker" )
cmdInsert.Parameters.AddWithValue( "parmPwd", "12345" )
cmdInsert.Parameters.AddWithValue( "parmStatus", 1 )
Dim SqlUpdate As String
SqlUpdate = "INSERT INTO Worker (ID, WorkerID, WorkerName, DoB, Address, Phone, Email, CompanyName, PassportNum, PassportExp, VisaExp, VisaStatus, user_id) "
SqlUpdate &= " VALUES ( #parmID, #parmName, #parmDoB, etc... ) "
Dim cmdUpdate As New OleDbCommand(SqlUpdate, con.oleconnection)
cmdUpdate.Parameters.AddWithValue( "parmID", WorkerID_.Text )
cmdUpdate.Parameters.AddWithValue( "parmName", WorkerName.Text )
cmdUpdate.Parameters.AddWithValue( "parmDoB", DoB.Text )
-- etc with the rest of the parameters.
Final note. Make sure the data types you are trying to insert or update are of same type expected in the table. Such example is your "Birth Date" (DoB) field. If you are trying to insert as simple text, and it is not in an auto-converted format, the SQL-Insert might choke on it and fail. If you have a textbox bound to a DateTime type, then your parameter might be Dob.SelectedDate (such as a calendar control), or you could pre-convert from text to a datetime and then use THAT as your parameter value.
Other numeric values, leave as they are too, they should directly apply for the insert. You could also identify the AddWithValue() call the data type the parameter should represent (string, int, double, datetime, whatever)
You seem to have 12 parameters you wish to insert, and 13 arguments in the VALUES part of your insert query. is the Default seen in the values section below intentional?
INSERT INTO Worker (ID, ... VisaStatus) VALUES (default,"
ensure you have the correct number of parameters defined and added, then let us know, but i could be missing something else.

Vb.net show messagebox text and variable

Hi im new to vb and I want to display in my msgbox the text and variable but I can't seem to figure it out. My code is
Data = "UPDATE [Mc_Koy].[dbo].[User] SET [Balance] = [Balance] - '" & txt_fare.Text & "'WHERE [ID] = '" & txtbox_id.Text & "'"
Command = New SqlCommand(Data, Connection)
Command.ExecuteNonQuery()
Dim Data1 As String = "SELECT [Balance] FROM [Mc_Koy].[dbo].[User] Where [ID] = '" & txtbox_id.Text & "'"
Dim Command1 As New SqlCommand(Data1, Connection)
Command1.ExecuteNonQuery()
Dim dr As SqlDataReader
dr = Command1.ExecuteReader
With dr
.Read()
Dim f As Double
MsgBox("Current Balance is ", .Item(0))
.Close()
End With
But when I run it it only display the message "Current Balance is: "
I think you want to append it to the string, so use &:
MsgBox("Current Balance is " & .Item(0))

UPDATE statement failing when attempting to update access database - VB.Net

I am trying to create a simple ticketing software for myself with a VB.Net front end and an Access 2003 back end. I have with allowing new rows to be added, but when I try to code the Update row button, it is giving me the error that says Microsoft JET Database Engine - Syntax error in UPDATE statement. I cannot find what the problem is.
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim ConnectString As String = ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\aaron-pister\Desktop\New Role Notes\Issue Tracker Express\Issue Tracker Express\Issue Tracker.mdb")
Dim con As New OleDbConnection(ConnectString)
con.Open()
Dim Green42 As String = "UPDATE Issues Basic Details SET [Company Name] = '" & txtClientName.Text & "', [Status] = '" & cbStatus.Text & "', [Company Contact] = '" & txtClientContact.Text & "', [Description] = '" & txtDesc.Text & "', [Notes] = '" & txtRes.Text & "' WHERE [TicketNum] = '" & txtTicket.Text & "'"
'con.Open()
If txtClientName.Text <> "" Then
Try
'MyCom.CommandText = "UPDATE [Issues Basic Details] SET Company Name = '" & txtClientName.Text & "', Status = '" & cbStatus.Text & "', Company Contact = '" & txtClientContact.Text & "', Description = '" & txtDesc.Text & "', Notes = '" & txtRes.Text & "' WHERE TicketNum = '" & txtTicket.Text & "')"
da = New OleDbDataAdapter(Green42.ToString, ConnectString)
da.Fill(dt)
da.Update(EsInfo1, "Issues Basic Details")
MsgBox("Your record has been updated successfully.", MsgBoxStyle.DefaultButton1, "New Ticket Submitted")
Catch ex As Exception
MsgBox(ex.Source & "-" & ex.Message)
con.Close()
Exit Sub
End Try
Else
MsgBox("You must have an entry in the Client Name, Client Contact and Status fields. It is recommended to also have a value in the Description field.", MsgBoxStyle.OkOnly, "Issue Tracker Express")
btnNewIncident_Click(sender, e)
Exit Sub
End If
End Sub
Your table name has to be bracketed too:
Dim Green42 As String = "UPDATE [Issues Basic Details] SET [Company Name]..."
Also, use parameters instead of putting the values into the string. It avoids SQL Injection.
This:
UPDATE Issues Basic Details SET ...
Is not valid SQL. You need to help it by qualifying your table name:
UPDATE [Issues Basic Details] SET ...
A few other suggestions:
Use prepared statements (parameterize your SQL to avoid SQL injection attacks)
Don't define this type of behavior in a click event handler -- have a helper class to do this work so it can be re-used and isn't coupled directly to the UI.
Use Using statements. Your OleDbConnection class implements IDisposable. You aren't properly disposing this connection.
While it's hard to read your code at the moment, it does look like you are trying to do an "AdHoc" query, which can cause a lot of problems.
I'd recommend first changing your statement to a parameterized query to help diagnose issues too.

SQL command will not insert into database

I'm trying to use a VB button to insert data into a database, but it keeps bringing up the error message I have in place for exceptions.
Can anyone help me with why this does not update the database?
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim sqlCnn As SqlConnection
Dim sql As String
Dim adapter As New SqlDataAdapter
Dim Customer As String = TextBox1.Text
Dim Product As String = TextBox2.Text
Dim Location As String = TextBox3.Text
Dim Details As String = TextBox4.Text
Dim Owners As String = DropDownList1.Text
Dim Urgency As String = DropDownList2.Text
connetionString = "Data Source=ZUK55APP02;Initial Catalog=BugFixPortal;User ID=SLC***;Password=rep***"
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details) VALUES ('" & Owners & ", " & Customer & ", " & Product & ", " & Location & ", " & Urgency & ", " & Details & "')"
sqlCnn = New SqlConnection(connetionString)
Try
sqlCnn.Open()
adapter.UpdateCommand = sqlCnn.CreateCommand
adapter.UpdateCommand.CommandText = sql
adapter.UpdateCommand.ExecuteNonQuery()
sqlCnn.Close()
Catch ex As Exception
MsgBox("Unable to update Database with Request - Please speak to Supervisor!")
End Try
End Sub
I would not go down this road as your code is weak against SQL Injection
you should use parameters instead.Something like the below
c.Open();
string insertString = #"insert into YourTable(name, street, city,....) values(#par1, #par2, #parN,....)"
SqlCommand cmd = new SqlCeCommand(insertString, c);
cmd.Parameters.Add("#par1", SqlDbType.VarChar).Value = "MyName";
//etc
cmd.ExecuteNonQuery();
c.Close();
You are incorrectly quoting your values.
This string has an opening and closing single quote around ALL the values, which is incorrect.
VALUES ('" & Owners & ", " & Customer & ", " & Product & ", " & Location & ", " & Urgency & ", " & Details & "')"
Instead, put single quotes around character data, eg., if Product is a varchar, it would look like this:
VALUES (" & Owners & ", " & Customer & ", '" & Product & "', " & Location & ", " & Urgency & ", " & Details & ")"
The real problem, though, is that you should be using parameterized queries instead. This code is prone to SQL injection attacks.
Change this;
MsgBox("Unable to update Database with Request - Please speak to Supervisor!")
to Something like this;
MsgBox("Unable to update Database with Request - Please speak to Supervisor!" & ex.Message)
It will give you more details on the exception, however at a quick glance I can see a problem, the values you are trying to insert are strings, you've enclosed all your values in a single set of ' characters, rather than enclosing each string parameter in a pair of ' values, i.e.
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details) VALUES ('" & Owners & "', '" & Customer & "', '" & Product & "',' " & Location & "', '" & Urgency & "', '" & Details & "')"
You really should look at parameterizing your queries as you're wide open to SQL injection attacks. See HERE
In terms of your code itself, your SQL syntax is wrong as you need to put apostrophes around each value. Try this:
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details)
VALUES ('" & Owners & "', '" & Customer & "', '" & Product &
"', '" & Location & "', '" & Urgency & "', '" & Details & "')"
Here's an example using Parameters
sql = "INSERT INTO Requests (Owner, Customer, Product, Location, Urgency, Details)
VALUES ('#Owners', '#Customer', '#Product', '#Location', '#Urgency', '#Details')"
Then add parameters like so:
command.Parameters.AddWithValue("#Owners", Owners)
command.Parameters.AddWithValue("#Customer", Customer)
command.Parameters.AddWithValue("#Product", Product)
command.Parameters.AddWithValue("#Location", Location)
command.Parameters.AddWithValue("#Urgency", Urgency)
command.Parameters.AddWithValue("#Details", Details)
I think you want to use adapter.InsertCommand instead of adapter.UpdateCommand
in
Try
sqlCnn.Open()
adapter.UpdateCommand = sqlCnn.CreateCommand //(adapter.InsertCommand)
adapter.UpdateCommand.CommandText = sql //(adapter.InsertCommand)
adapter.UpdateCommand.ExecuteNonQuery() //(adapter.InsertCommand)
sqlCnn.Close()
Catch ex As Exception
MsgBox("Unable to update Database with Request - Please speak to Supervisor!")
End Try
and agree with parametrized sql query
see http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.aspx for more infos