cannot insert datetime in visual basic - vb.net

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

Related

vbScript - InputBox into .accdb , blank?

After 9 hours of research and trial and error, I've come to all of you with this current issue I am having with another script I wrote to input data into a database. I'll simplify the focal point of this problem in the code view. I have 3 fields, one is a timestampe at the end of the SQL such as .... & now() & "')". That inserts FIND, but by variable inputboxes insert blank data.
Option Explicit
Dim ib
Dim sql1, constring, con
constring="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\users\user\documents\database1.accdb;"
sql1="INSERT INTO table1 (column1) VALUES('" & ib & "')"
set con = createobject("adobd.connection")
con.open constring
Do
ib=inputbox("Input Data")
IF ib="quit" OR ib="QUIT" THEN
con.close
ELSE con.execute sql1
End If
Loop WHILE ib<>"quit" AND ib<>"QUIT"
It is appending rows into the database, but they are blank. Ive designed the table to take short text of <255 chars.
I also ran a test query from within the database and it inserts what I tell it to, but the inputbox data, for some reason, is not making it to the table.
This
sql1="INSERT INTO table1 (column1) VALUES('" & ib & "')"
concats an (empty) ib into sql1 before the loop. con.execute sql1 will insert that into the database until you quit.
Try
con.execute "INSERT INTO table1 (column1) VALUES('" & ib & "')"
and optimize when it works.
Do
ib=inputbox("Input Data")
If LCase(ib) <> "quit" THEN
con.execute "INSERT INTO table1 (column1) VALUES('" & ib & "')"
End If
Loop WHILE ib<>"quit" AND ib<>"QUIT"
con.close
You need to recreate the string that you will execute for each value that you retrieve

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

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

Parameter missing in ExecuteNonQuery command, using in VB.NET and Access

I have a very simple database in Access 2007 that I'm connecting to using VB 2010. There are two tables, MenuItems and Orders, and Orders.orderDate is of type "Date".
I'm running the following code in one of my VB forms (the connection string and everything else is fine):
sql = "SELECT OrderDate, MenuItem FROM MenuItems, Orders WHERE Orders.itemID = MenuItem.ID AND Orders.orderDate BETWEEN '" + fromDate + "' AND '" + toDate + "'"
Dim cmd As New OleDb.OleDbCommand(sql, con)
Dim count As Integer = cmd.ExecuteNonQuery()
But I get an error that:
System.Data.OleDb.OleDbException (0x80040E10): value wan't given for one or more of the required parameters
Nothing seems to be missing. I've used the same code for another query, except the sql was different. But I think my sql is simple enough. Here's the sql that was generated in one instance (I've double checked, all table and column names are correct):
SELECT OrderDate, MenuItem From MenuItems, Orders WHERE Orders.itemID = MenuItem.ID AND Orders.orderDate BETWEEN '11/21/2012' AND '11/24/2012'
You should use parametrized queries for at least two reasons.
You don't have to worry about date (and other) literals and locale problems.
You don't have to worry about SQL injection attacks, where someone enters malicious code in a text box that turns a SQL statement into a harmful one.
Change your statement to
sql = "SELECT Orders.OrderDate, MenuItems.MenuItem " & _
"FROM MenuItems INNER JOIN Orders ON MenuItems.ID = Orders.itemID " & _
"WHERE Orders.orderDate BETWEEN ? AND ?"
Then execute the command like this
Dim fromDate, toDate As DateTime
fromDate = DateTime.Parse(fromDateTextBox.Text)
toDate = DateTime.Parse(toDateTextBox.Text)
Dim dataset As New DataSet()
Using conn As New OleDbConnection(connectionString)
Using adapter As New OleDbDataAdapter()
Dim cmd As New OleDbCommand(sql, conn)
cmd.Parameters.Add("?", fromDate)
cmd.Parameters.Add("?", toDate)
adapter.SelectCommand = cmd
adapter.Fill(dataset)
End Using
End Using
Well, the ExecuteNonQuery method is there for statements for changing data, ie. DELETE / UPDATE /INSERT, and the returned value are the number of rows affected by that statement.
Since you are using Select statement, you should be using oledbDataAdapter and Fil DataSet for use.
Dim conn As New OleDbConnection(con)
Dim adapter As New OleDbDataAdapter()
sql = "SELECT OrderDate, MenuItem FROM MenuItems, Orders WHERE Orders.itemID = MenuItem.ID AND Orders.orderDate BETWEEN '" + fromDate + "' AND '" + toDate + "'"
adapter.SelectCommand = new OleDbCommand(sql, con)
adapter.Fill(dataset)
Return dataset
The issue was a mis-spelled table. (MenuItem instead of MenuItems), but it didn't solve the question, I still got an error. It turned out to be a problem with matching formats between the database and the datepicker values being used as query parameters.
So I made sure I saved to the database in short Date Format:
sql = "INSERT INTO Orders(itemID, OrderDate) VALUES('" + ListBox1.SelectedValue.ToString() + "','" + FormatDateTime(OrderDate.Value, DateFormat.ShortDate) + "')"