How can I use where function using insert into module - vb.net

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()) & "'"

Related

If not exists query results in "error in your SQL syntax"

I would like to insert a row with SQL (in Visual Basic) and receive something like: "Error: You have an errin in your SQL syntax near IF NOT EXISTS ... at line 1"
Code looks like:
...
Try
query = "IF NOT EXISTS (Select Movie_Name from MovieDB where Movie_Name=" & placeholder & ") INSERT INTO MovieDB (Movie_Name) VALUES ('" & placeholder & "')"
'PREPARE CONNECTION
MySQLCmd = New MySqlCommand(query, dbConnection)
'OPEN DB
dbConnection.Open()
'EXECUTE QUERY
MySQLCmd.ExecuteNonQuery()
'CLOSE DB
dbConnection.Close()
Catch ex As Exception
...
I really dont get it anymore. Some ideas?
At a minimum you need single quotes around the first string as well:
--V --V
query = "IF NOT EXISTS (Select Movie_Name from MovieDB where Movie_Name='" & placeholder & "'); INSERT INTO MovieDB (Movie_Name) VALUES ('" & placeholder & "')"
As #Cameron astutely noticed, you also need a semicolon between the EXISTS function and the INSERT command
But you should look into using parameters instead of concatenating SQL - not only does it remove the need to delimit strings, but it prevents SQL injection and avoids syntax error if the string contains an apostrophe.
As far as I know "IF NOT EXISTS INSERT" is no valid MySQL syntax. This should work:
query = "INSERT INTO MovieDB (Movie_Name) VALUES ('" & placeholder & "') ON DUPLICATE KEY UPDATE Movie_Name = Movie_Name";
This tries to insert the new movie name and if this fails it does virtually nothing. (For this to work there must be a unique index on Movie_Name.)

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()

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

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

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))

SQL output as variable in VB.net

I cannot seem to figure out how to get an output of a SQL query as a variable in VB. I need something like what's below so that I can use that variable in another SQL query. SQL doesn't allow the use of variables as column headers when running queries, so I thought I could use VB to insert the actual output of one SQL task as the dynamic variable in a loop of update queries. Let me (hopefully) explain.
I have the following query:
DECLARE #id int = (SELECT max(id) FROM [views]), #ViewType nvarchar(3);
WHILE #id IS NOT NULL
BEGIN
SELECT #ViewType = (SELECT [View] FROM [views] WHERE id = #id);
UPDATE a
SET a.[#ViewType] = '1'
FROM [summary] a
INNER JOIN [TeamImage] b
ON a.[Part_Number] = b.[PartNum]
WHERE b.[View] = #ViewType;
SELECT #id = max(id) FROM [views] WHERE id < #id;
END;
The SET a.[#ViewType] = '1' obviously will not work in SQL. But if I could have the (SELECT [View] FROM [views] WHERE id = #id) equal to a variable, then I could write the SQL query in VB and execute it and the variable would become part of the string and therefore execute correctly.
I'm newer to VB, but here's what I have so far:
Dim cn As SqlConnection = New SqlConnection("Data Source=Server1;" & _
"Initial Catalog=DB1;" & _
"Integrated Security=SSPI")
cn.Open()
Dim cmd As New sqlCommand("SELECT max(id) FROM orientation_view_experiment;", cn)
vID = cmd.ExecuteNonQuery()
Do While vID > 0
Dim cmd2 As New sqlCommand("SELECT [View] FROM [views] WHERE id ='" + vID + "'"
vViewType = cmd2.ExecuteNonQuery()
Dim cmd3 As New sqlCommand("UPDATE a
SET a.'" + vViewType + "' = '1' & _
FROM [summary] a & _
INNER JOIN [TeamImage] b & _
ON a.[Part_Number] = b.[PartNum] & _
WHERE b.[View] = '" + vViewType + "';"
cmd3.ExecuteNonQuery()
vID = vID - 1
Loop
cn.Close()
I hope some of that made sense, but I'm kind of lost at this point. I feel like I know what I need the SQL to do, but can't quite figure out how to make the computer/programs submit to my will and just do what I need it to do.
Thank you for any help/direction you can give.
Your code is wrong because you insist in using ExecuteNonQuery for SELECT statements. ExecuteNonQuery doesn't return the rows selected but just a count of the rows affected by an INSERT/DELETE/UPDATE query (I think that for SELECT it returns always zero)
What you need is ExecuteScalar to get the MAX value and the VIEW value because ExecuteScalar is the best choice when you expect to get just the first field of the first row from your SQL statement
Dim cmd As New sqlCommand("SELECT max(id) FROM orientation_view_experiment;", cn)
vID = Convert.ToInt32(cmd.ExecuteScalar())
Do While vID > 0
Dim cmd2 As New sqlCommand("SELECT [View] FROM [views] WHERE id =" + vID.ToString()
Dim result = cmd2.ExecuteScalar()
if Not string.IsNullOrEmpty(result)) Then
vViewType = result.ToString()
Dim cmd3 As New sqlCommand("UPDATE a SET a.[" + vViewType + "] = '1' " & _
"FROM [summary] a " & _
"INNER JOIN [TeamImage] b " & _
"ON a.[Part_Number] = b.[PartNum] " & _
"WHERE b.[View] = #vType"
cmd3.Parameters.AddWithValue("#vType", vViewType)
cmd3.ExecuteNonQuery()
End If
Loop
The last part of your code is not really clear to me, but you could use a couple of square brackets around the column name in table summary and a parameter for the View field in table TeamImage.
As a last advice, be sure that the column View in table TeamImage is not directly modifiable by your end user because a string concatenation like this could lead to a Sql Injection attacks
Do a little research into what the different methods of a command are. When you call ExecuteNonQuery, this return the number of records effected. I think you want ExecuteScalar as your cmd and cmd2 methods, so you can get a value from the database.
Have you tried replacing '" + vViewType + "' with [" + vViewType + "] ... in other words use square brackets to delimit the column name instead of single quotes which are for delimiting string literals?
Also, I would encourage stopping in the debugger, examining the command that you generated into cmd3 and try executing it directly. It might help you identify other similar problems such as the fact that vViewType is giving you a count of records instead of an actual value from the [View] column.