Error in My Add button SQL Server Management Studio And Visual Basic 2010 - sql

Here is the thing I can't use insert query in my code there is an error in my SqlCommand that says the ExecuteNonQuery() not match with the values blah blah
Here is my code
Dim con As New SqlClient.SqlConnection("Server=.\SQLExpress;AttachDBFilename=C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\Finals.mdf;Database=Finals;Trusted_Connection=Yes;")
Dim cmd As New SqlClient.SqlCommand
cmd.Connection = con
cmd.CommandText = "Insert Into [Finals].[dbo].[Nokia] Values ('" & Unit.Text & "'),('" & Price.Text & " '),('" & Stack.Text & "'),('" & Processor.Text & "'),('" & Size.Text & "'),('" & RAM.Text & "'),('" & Internal.Text & "'),('" & ComboBox1.Text & "')"
con.Open()
cmd.ExecuteNonQuery()
con.Close()
The problem is the cmd.CommandText can anyone please help me?

You need to rewrite your query to use a parameterized query. This would avoid parsing problems if your textboxes contains single quotes and, most important, would remove any possibility of Sql Injection.
So you code could look like this
Dim cmdText = "Insert Into [Finals].[dbo].[Nokia] Values (#unit, #price,#stack," & _
"#processor,#size,#ram,#internal,#lastvalue"
Using con As New SqlConnection(......)
Using cmd As New SqlCommand(cmdText, con)
con.Open()
cmd.Parameters.AddWithValue("#unit",Unit.Text )
cmd.Parameters.AddWithValue("#price",Price.Text)
cmd.Parameters.AddWithValue("#stack",Stack.Text)
cmd.Parameters.AddWithValue("#processor", Processor.Text)
cmd.Parameters.AddWithValue("#size",Size.Text)
cmd.Parameters.AddWithValue("#ram", RAM.Text)
cmd.Parameters.AddWithValue("#internal",Internal.Text)
cmd.Parameters.AddWithValue("#lastvalue", ComboBox1.Text)
cmd.ExecuteNonQuery()
End Using
End Using
Said that, be aware of two more problems:
You don't specify a column list before the VALUES statement. This means that you need to pass the exact number of parameters for every column present in your table named Nokia AND in the EXACT ORDER of the underlying columns. If you forget one parameter you will receive an exception and if you swap the order of the parameters you end writing your data in the wrong column (with an exception waiting for you if the datatype doesn't match).
The second problem concerns the datatype of every parameter passed to the query. In your case you use the Text property of the textboxes and this means that you are passing a string for every column in the datatable. Of course, if a column expects a numeric value you get a mismatch error.
For example the #price parameter could be used to update a decimal column in the datatable and thus you need to convert the parameter from string to decimal before adding it using the AddWithValue method
cmd.Parameters.AddWithValue("#price",Convert.ToDecimal(Price.Text))

Related

Select value and display in a combobox if the datetimepicker value lies between two extreme dates in a table in database

I am creating an attendance management system in vb.net and using MS access as my database. I created a leave form in which the student on leave has a roll number and his details along with the from date and to date field.
What I'm trying to do is to show all the roll numbers of students in the ComboBox on leave if the DateTimePicker value is in between the to date and from date, the command that I created as MS access query is selecting the from date and to date ie., extreme dates matching with the DateTimePicker value but not showing the values if date is between the to and from date.
this is the code and query:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
con.Open()
Dim cmd1 As New OleDbCommand("Select roll_no From leaves Where semester= " + ComboBox3.SelectedItem + " and (from_date<= #" & DateTimePicker1.Value.ToShortDateString & "# and to_date >= #" & DateTimePicker1.Value.ToShortDateString & "#)", con)
Dim da1 As New OleDbDataAdapter
da1.SelectCommand = cmd1
Dim dt1 As New DataTable
dt1.Clear()
da1.Fill(dt1)
ComboBox4.DataSource = dt1
ComboBox4.DisplayMember = "roll_no"
ComboBox4.ValueMember = "roll_no"
con.Close()
End Sub
Is there any modification in query through which I can get my desired results to get all the roll no if DateTimePicker value is between dates in database?
Well, you probably do want to wrap the code in a using block - that way if you have a error, it will STILL close the connection. Also, it means you don't have to close the connection - a using block ALWAYS will (so, this costs you ONLY one extra line of code, but it more robust - will not leave stray connections open.
Next up:
While everyone warns and suggests to try and avoid string concertation for reasons of SQL injection?
Actually, the BETTER case is that string concatenation is tricky, messy, and you have to remember to use quotes to surround strings, maybe "#" for dates, and for numbers no surrounding delimiters. And one tiny missing single quote or whatever, and your sql is now wrong. So, this is a BETTER case and reason to use parameters - to allow you to write code, and write code that is easer to fix, read, maintain, and even add more parameters to without complex string concatenations.
So, I would suggest this:
Using conn As New OleDbConnection(My.Settings.AccessDB)
Dim strSQL As String =
"Select roll_no From leaves Where from_date >= #cboDate and to_date <= #cboDate " &
"AND semester = #Semester"
Using cmd = New OleDbCommand(strSQL, conn)
cmd.Parameters.Add("#cboDate", OleDbType.DBDate).Value = DateTimePicker1.Value
cmd.Parameters.Add("#Semester", OleDbType.Integer).Value = ComboBox3.SelectedValue
conn.Open()
ComboBox4.DisplayMember = "roll_no"
ComboBox4.ValueMember = "roll_no"
ComboBox4.DataSource = cmd.ExecuteReader
End Using
End Using
And note how I dumped the need for a data adaptor - don't' need it.
And note how I dumped the need for a data table - don't' need it.
However, you do OH SO VERY often need a data table. So, since we humans do things over and over without thinking - memory muscle - then I would suggest that it is ok to create and fill a data table and shove that into the "on leave".
So since we "often" will need a data table, then for the sake of learning, then you could write it this way (so we now learn how to fill a data table).
Using conn As New OleDbConnection(My.Settings.AccessDB)
Dim strSQL As String =
"Select roll_no From leaves Where from_date >= #cboDate and to_date <= #cboDate " &
"AND semester = #Semester"
Using cmd = New OleDbCommand(strSQL, conn)
cmd.Parameters.Add("#cboDate", OleDbType.DBDate).Value = DateTimePicker1.Value
cmd.Parameters.Add("#Semester", OleDbType.Integer).Value = ComboBox3.SelectedValue
conn.Open()
Dim dt1 As New DataTable
dt1.Load(cmd.ExecuteReader)
ComboBox4.DisplayMember = "roll_no"
ComboBox4.ValueMember = "roll_no"
ComboBox4.DataSource = dt1
End Using
End Using
But, either way? Note how I did not have to remember, think about, worry about, and try to figure out the delimiters. Is that a " # " we need for dates, or is that a " ' " we need around the date?
Of course this code would be placed in the timepicker value changed event.

cannot insert datetime in visual basic

I have one question and was wondering if someone could help..
I have created a program in vb net. When I press a button then it should insert in my sql database in the column "date" the current date and time. I use for this purpose the following code :
query1 = "insert into visit(visit,textfile,p_id) VALUES('" & Date.Today & "','" & s & "',(select patient.p_id from patient where (patient.name=('" & ComboBox1.Text & " '))))"
Well it does its job but when i look in my database in the column 'visit' it displays only zeros.
Any ideas?
Use a parameterized query (this example is for Sql Server). In this way you don't need to worry how to quote a date, a string or what is the correct decimal separator required by the database.
Moreover you avoid any problem with Sql Injection attacks
query1 = "insert into visit(visit,textfile,p_id) VALUES(#p1, #p2, " & _
"(select patient.p_id from patient where patient.name=#p3)"
Dim cmd As MySqlCommand = new MySqlCommand(query1, connection)
cmd.Parameters.AddWithValue("#p1", Date.Today)
cmd.Parameters.AddWithValue("#p2", s)
cmd.Parameters.AddWithValue("#p3", ComboBox1.Text)
cmd.ExecuteNonQuery()

How can I use where function using insert into module

My command is error in my sql command where clause, how can I handle it? any suggestion or any help?
This is my Error:
syntax to use near 'WHERE controlNumber = '' at line 1
cmd = New Odbc.OdbcCommand("INSERT INTO alamnotice (correctivePreventive) VALUES('" & Trim(txtremarks.Text.TrimEnd()) & "') WHERE controlNumber ='" & Trim(Form1.txtcontrolNumber.Text.TrimEnd()) & "'", con)
cmd.ExecuteNonQuery()
You havent said what the error is, it could be something to do with Disconnect, but I suspect it is a SQL syntax error because INSERT doesnt use a WHERE (you are inserting new data).
Here is a way to use params to make the code easier to read and avoid SQL injection attacks:
Dim SQL As String = "INSERT INTO alamnotice (correctivePreventive,
sectionInCharge, shiftInCharge, SectionHead, status,
dateResponded, remarksSurrendingAlarm, Remarks)
VALUES ("#p1", "#p2", "#p3", "#p4", "#p5", "#p6", "#p7", "#p8")"
' I am assuming OleDB, but much the same for others
' be sure to add the values in the same order with OleDB
Using cmd As New OleDbCommand(SQL, dbCon)
cmd.Parameters.AddWithValue("#p1", txtcorPrevAction.Text )
cmd.Parameters.AddWithValue("#p2", txtCause.Text)
cmd.Parameters.AddWithValue("#p3", cmbstatus.Text)
' etc
cmd.ExecuteNonQuery()
End Using
for non string columns, such as a date, convert the textbox text:
cmd.Parameters.AddWithValue("#pX", COnvert.ToInt32(txtSomeValue.Text))
the code is easier to read and if you arent gluing ticks and stuff into a string, there are far fewer string format errors like a missing '
try this one :
UPDATE alamnotice SET correctivePreventive = '" & Trim(txtremarks.Text.TrimEnd()) & "' WHERE controlNumber ='" & Trim(Form1.txtcontrolNumber.Text.TrimEnd()) & "'"

Can't compare vb.net item with access number

Edit: For anyone facing this problem, don't miss the tips about only using
parameters instead of inserting the values directly into the SQL queries.
i'm facing a big problem with my vb.net project, i'm stuck with this for a week
i've a combobox item that i need to compare with an access number which is my database to retrieve some information, but i just got an error, no matter what format i convert my combobox item, it says my datatype is inconpatible with the expression
Here's one of the SQL queries from my code:
Dim dt1 As New DataTable
'This query select some itens from a row that match with the selected combobox number
Dim find1 As New OleDb.OleDbDataAdapter("SELECT Product, Number," _
& " Customer, Quantity, ProductionDate, AskDay, Pack, Company FROM RegOPE" _
& " WHERE Number ='" & CInt(mycombobox.SelectedItem) & "'", cn)
'Ive tried SelectedItem, Item, Text, SelectedValue...
'For conversion i tried parse, tryparse, conversion...
cn.Open() 'Opens database connection
find1.Fill(dt1) <- I got the error here
cn.Close() 'Close database connect
mydatagrid.DataSource = dt1 'Show the result in datagridview
number criteria should be without quote
Dim find1 As New OleDb.OleDbDataAdapter("SELECT Product, Number, " _
& "Customer, Quantity, ProductionDate, AskDay, Pack, Company FROM RegOPE " _
& "WHERE Number =" & CInt(mycombobox.SelectedItem), cn)
But better always use parameters:
Dim comm = New OleDb.OleDbCommand("SELECT Product, Number, " _
& "Customer, Quantity, ProductionDate, AskDay, Pack, Company FROM RegOPE " _
& "WHERE Number =?", cn)
comm.Parameters.AddWithValue("unusedName", mycombobox.SelectedItem)
Dim find1 As New OleDb.OleDbDataAdapter(comm)
In your WHERE clause have you tried to remove the quotes ? They are not required if you are looking for a number.
First, I must mention that you really ought to be using parameters. You should not concatenate the values directly into the SQL command string like that. Your SQL command string should simply contain parameter name placeholders for those values and then you should specify the values for those parameters separately.
However, if you are going to concatenate the value with the command like that, the command is a string, not an integer. It makes little sense to use CInt to convert the item to an integer just before concatenating it with a string (which requires first converting it from the integer into a string). It would make more sense to simply call ToString to convert it to a string, instead of CInt. Also, if the Number column in your database is typed as a number, rather than as text, then you should not be surrounding the value with quotes.
I recommend trying this:
Dim find1 As New OleDb.OleDbDataAdapter("SELECT Product, Number," _
& " Customer, Quantity, ProductionDate, AskDay, Pack, Company FROM RegOPE" _
& " WHERE Number =" & mycombobox.SelectedItem.ToString(), cn)
Although, recommend is to strong a word, since I would never recommend doing it that way in the first place. Use parameterized queries!

Update Query in Visual Basic Express 2010

I'm trying to update an Access 2003 database using Visual Basic Express 2010 via SQL, I have so far got SELECT, DELETE and INSERT queries to work, but update will not...
con.ConnectionString = dbProvider & dbSource
con.Open() 'Open connection to the database
sqlstatement = "UPDATE users SET password = '" & NewPassword & "' WHERE USERID = " & ID & ";"
Dim dc As New OleDb.OleDbCommand(sqlstatement, con)
dc.ExecuteNonQuery()
con.Close()
Like I said, all other statements work, the error produced is:
http://i.stack.imgur.com/acFBT.png
Thank you!
The first problem is the word PASSWORD. It is a reserved keyword in MS-Access database. If you want to use it you should enclose it in square brackets.
Said that, please start using a parameterized query and not a string concatenation when you work with any type of database
So your code should be:
sqlstatement = "UPDATE users SET [password] = ? WHERE USERID = ?"
Using con = new OleDbConnection(dbProvider & dbSource)
Using dc = new OleDbCommand(sqlstatement, con)
con.Open()
dc.Parameters.AddWithValue("#p1", NewPassword)
dc.Parameters.AddWithValue("#p2", ID)
dc.ExecuteNonQuery()
End Using
End Using
You could read about the importance of Parameterized Queries and Sql Injection in many places, this link is a most famous one to start with