INSERT Query with Parameters in VS2010 - vb.net

I do not understand why it's not inserting to my database whenever I include an apostrophe in my txtParticulars.Text and txtPayTo.Text.
The error is this:Syntax error (missing operator) in query expression ''Joy's Boutique','Top's,'Issued')'.
My textbox values are:
txtPayTo.Text > Joy's Boutique
txtParticulars > Top's
cmbRemarks.SelectedItem > Issued
But whenever my txtParticulars and txtPayTo values does not have an apostrophe, my data saves.
The following is my code:
sql1 = "INSERT INTO Table1(Check_No,Voucher_No,Issue_Date,Company_Name,Bank_Type,Amount_in_Figure,Amount_in_Words,Payee,Particulars,Remarks) VALUES(#CheckNo,#VoucherNo,#Date,#CompName,#BankType,#AmtInFigure,#AmtInWords,#PayTo,#Particulars,#Remarks)"
Dim cmd1 As OleDbCommand = New OleDbCommand(sql1, myConnection)
cmd1.Parameters.AddWithValue("#CheckNo", txtCheckNo.Text)
cmd1.Parameters.AddWithValue("#VoucherNo", txtVoucherNo.Text)
cmd1.Parameters.AddWithValue("#Date", dtpDate.Text)
cmd1.Parameters.AddWithValue("#CompName", txtCompName.Text)
cmd1.Parameters.AddWithValue("#BankType", txtBankType.Text)
cmd1.Parameters.AddWithValue("#AmtInFigure", txtAmtInFigure.Text)
cmd1.Parameters.AddWithValue("#AmtInWords", txtAmtInWords.Text)
cmd1.Parameters.AddWithValue("#PayTo", txtPayTo.Text)
cmd1.Parameters.AddWithValue("#Particulars", txtParticulars.Text)
cmd1.Parameters.AddWithValue("#Remarks", cmbRemarks.SelectedItem)
cmd1.ExecuteNonQuery()

Use Add instead of AddWithValue.
The latter has to guess the correct database type by the value passed in.
The Add method is more reliant on that (as long as you donĀ“t use the Add(string, object) overload).
Based on your example:
cmd1.Parameters.Add("#PayTo", SqlDbType.Varchar)
cmd1.Parameters("#PayTo").Value = txtPayTo.Text
or as one line (thanks to Plutonix):
cmd1.Parameters.Add("#PayTo", SqlDbType.Varchar).Value = txtPayTo.Text

Related

parameter has no default value vb.net

I'm getting the error System.Data.OleDb.OleDbException: 'Parameter #client_address has no default value.' but I have sent all the parameters needed.
cmd.Connection = cn
cmd.CommandText = "insert into invoice([invoice_date],[client_name],[client_company_name],[client_email],[client_contact_no],[client_address],[client_delivery_address],[total_basic_amount],[freight_rate],[delivery_rate],[advanced_amount],[pending_amount])
Values(#invoice_date,#client_name,#client_company_name,#client_email,#client_contact_no,#client_address,#client_delivery_address,#total_basic_amount,#freight_rate,#delivery_rate,#advanced_amount,#pending_amount)"
cmd.Parameters.AddWithValue("#invoice_date", datetime.Value)
cmd.Parameters.AddWithValue("#client_name", client_name.Text)
cmd.Parameters.AddWithValue("#client_company_name", company_name.Text)
cmd.Parameters.AddWithValue("#client_email", email.Text)
cmd.Parameters.AddWithValue("#client_contact_no", contact_no.Text)
cmd.Parameters.AddWithValue("#client_address", address.Text)
cmd.Parameters.AddWithValue("#client_delivery_address", delivery_address.Text)
cmd.Parameters.AddWithValue("#total_basic_amount", total_basic_amount.Text)
cmd.Parameters.AddWithValue("#freight_rate", freigh_rate.Text)
cmd.Parameters.AddWithValue("#delivery_rate", delivery_rate.Text)
cmd.Parameters.AddWithValue("#advanced_amount", advance_received_amount.Text)
cmd.Parameters.AddWithValue("#pending_amount", total_pending_amount.Text)
cmd.ExecuteNonQuery()
MessageBox.Show("Invoice Stored")
I'm using accessdb in vb.net. and all variables has value nothing is empty. when I comment or remove client_address it start giving error on client_delivery_address.
Changes the way to create the parameter specifying the type and size, as in the example below:
cmd.Parameters.Add("#client_address", System.Data.OleDb.OleDbType.BSTR, 100);

Input string was not in correct format | decimal/integer to "NULL"

I've recently started learning .net and I wrote a basic sql connected data entry form. Almost all of my data types are integer or decimals. Sometimes I need to remain empty the textboxes and enter "NULL" data and I receive with this error "Input string was not in correct format".
How I can fix this error ? Key point; I don't want to enter "0" it must be "NULL" in sql server because I use some charts to track all of these data, so when there is data equal the "0" its ruined my charts. As far as I understand from my researches Tryparse is fit for it but I couldn't find any information to use it properly in .net.
I'll share my transformation code below.
Try
Dim command As New SqlCommand()
command.Parameters.Add("A", SqlDbType.Decimal).Value = Decimal.Parse(A)
command.Parameters.Add("B", SqlDbType.Int).Value = Integer.Parse(B)
command.Parameters.Add("C", SqlDbType.Decimal).Value = Decimal.Parse(C)
command.Parameters.Add("D", SqlDbType.Decimal).Value = Decimal.Parse(D)
command.Parameters.Add("E", SqlDbType.Decimal).Value = Decimal.Parse(E)
command.Parameters.Add("F", SqlDbType.Decimal).Value = Decimal.Parse(F)
command.Parameters.Add("G", SqlDbType.Int).Value = Integer.Parse(G)
command.Parameters.Add("H", SqlDbType.Int).Value = Integer.Parse(H)
c.CUD(command, sql)
list()
clear()
MessageBox.Show("Data Successfully Saved")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
command.Parameters.Add("strokeTB", SqlDbType.Decimal).Value = If(strokeTB.TextLength = 0, CObj(DBNull.Value), Decimal.Parse(strokeTB.Text))
This assumes that you have already validated the contents of the TextBox and it is guaranteed to either be empty or contain a valid Decimal value.
This If operator is similar to the old IIf function but it's better because it short-circuits, i.e. the third argument operand is only evaluated if the first operand is False. Because IIf is a function, it evaluates all three arguments first, so Decimal.Parse would still be called and it would fail. Using If, Decimal.Parse will only be called if there is text to parse.

VB & Access: no value given for one or more required parameters when inserting data

Hello so I have a problem with my simple program that I'm practicing. I'm trying to insert data from vb input box to MS Access database, there are 5 columns in employeeInfo table but the other one is AutoNumber so I didn't include it in the code. The employeeDB has only 3 columns ID, username, pword but I didn't include ID since it's AutoNumber. When I hit the button to add data it will throw an error No value given for one or more required parameters # database_reader = cmd_personal.ExecuteReader even if I did input all the input box that has connection to the database.
Private Sub signUp_btn_Click(sender As Object, e As EventArgs) Handles signUp_btn.Click
Dim usernameInput As String = inputBoxUsername.Text
Dim inputPword As String = inputBoxPword.Text
Dim input_FirstName As String = FirstName_Box.Text
Dim input_MidName As String = MidName_Box.Text
Dim input_LastName As String = LastName_Box.Text
Dim input_ContactNum As String = ContactNumber_Box.Text
dbConnection.Open()
Dim str_personal As String
Dim str_acctInfo As String
str_personal = "INSERT INTO employeeInfo([FirstName], [MiddleName], [LastName], [PhoneNumber]) Values (?, ?, ?, ?)"
str_acctInfo = "INSERT INTO employeeDB([username], [password]) Values (?, ?)"
Dim cmd_personal As OleDbCommand = New OleDbCommand(str_personal, dbConnection)
Dim cmd_acctInfo As OleDbCommand = New OleDbCommand(str_acctInfo, dbConnection)
database_reader = cmd_personal.ExecuteReader
database_reader = cmd_acctInfo.ExecuteReader
database_reader.Read()
' Check If Input box has values
If usernameInput = "" Then
MessageBox.Show("Please Insert Username.")
inputBoxUsername.Clear()
ElseIf inputPword = "" Then
MessageBox.Show("Please Insert Password.")
ElseIf input_FirstName = "" Then
MessageBox.Show("Please insert First Name.")
ElseIf input_MidName = "" Then
MessageBox.Show("Please insert Middle Name.")
ElseIf input_LastName = "" Then
MessageBox.Show("Please insert Last Name.")
ElseIf input_ContactNum = "" Then
MessageBox.Show("Please insert Phone Number.")
End If
' Insert into employeeInfo DB
cmd_personal.Parameters.Add(New OleDbParameter("FirstName", CType(input_FirstName, String)))
cmd_personal.Parameters.Add(New OleDbParameter("MiddleName", CType(input_MidName, String)))
cmd_personal.Parameters.Add(New OleDbParameter("LastName", CType(input_LastName, String)))
cmd_personal.Parameters.Add(New OleDbParameter("PhoneNumber", CType(input_ContactNum, String)))
' Insert into employeeDB acct DB
cmd_acctInfo.Parameters.Add(New OleDbParameter("username", CType(usernameInput, String)))
cmd_acctInfo.Parameters.Add(New OleDbParameter("password", CType(inputPword, String)))
MessageBox.Show("Success! User has been created.")
dbConnection.Close()
I don't need advance solution just a simple one. Thanks!
(I already connect it to the Access Database I just didn't include the code at this post.)
If your SQL contains N ?, then you cannot call cmd_personal.ExecuteReader before you call cmd_personal.Parameters.Add N times to create the parameters (and give them a value)
If your intention is to call the command repeatedly, you can adopt a pattern of:
create command with ? placeholders
add parameters without values, or with representative dummy values if you're using "AddWithValue"/its equivalent (using the paramname,paramvalue constructor, as your code does, is equivalent to calling AddWithValue)
start a loop
set values
execute command
In this case it looks like your code is merely in the wrong order
Ok a few things. There is really no use to write a bunch of separate statements to test if a text box has a value. Like FoxPro, Access, dabase, or just about any system?
They have the ability to "validate" each text box.
So, move that code out. For each control that you want say as required?
So for say FirstName_Box?
Then in the events of the property sheet, use this event:
So, we double click in that Validating event, and we can write this:
Private Sub FirstName_Box_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles FirstName_Box.Validating
If FirstName_Box.Text = "" Then
MsgBox("First name is required")
e.Cancel = True
End If
End Sub
So, now if I click any button on the form, the text box will validate, and also pop up a nice message.
So, now we can dump, and assume our button code will not run until each control and its validation event is ok. It not only saves some code, but what happens if we have 2 or 4 buttons on the form, and now we going to write code to check all those text boxes each time? (nope!!!).
Ok, so now we can assume in our code that any required text box has a value. And if not, then the button click for any button code will not run for us - nice and simple, but more important nice and CLEAN. Since I can now know where to look for any code for a SINGLE control that has some criteria for input.
It also means that you have less code to work with, and deal with at one point in time.
This is much like the answer to this question:
How do you eat a elephant?
Answer: One bite at a time!!!
Ok, now that we have that all fixed up, we can clean up our code to insert.
I actually in a lot of cases suggest using a Datatable, since then we don't have to mess with parameters, but MORE important, it gives us the ability to EASY check if the information or "user" in this case already exists. I mean, you don't want to add the same user two times? Right?
So, now we can clean this up and ALSO check for if the user already exists.
Say somthing like this (warning: air code).
Using conn As New OleDbConnection(My.Settings.AccessDB)
conn.Open()
Dim strSQL As String =
"SELECT * FROM employeeDB WHERE UserName = #User"
Using cmdSQL As New OleDbCommand(strSQL, conn)
Dim da As New OleDbDataAdapter(cmdSQL)
Dim daU As New OleDbCommandBuilder(da)
cmdSQL.Parameters.Add("#User", OleDbType.VarWChar).Value = inputBoxUserName.Text
Dim rstAcctInfo As New DataTable
rstAcctInfo.Load(cmdSQL.ExecuteReader)
If rstAcctInfo.Rows.Count > 0 Then
MsgBox("This user already exists")
return ' bail out and exit
End If
' if we get here, user does not exist, so add this user
Dim OneRow As DataRow = rstAcctInfo.NewRow
OneRow("username") = inputBoxUsername.Text
OneRow("password") = inputBoxPword.Text
rstAcctInfo.Rows.Add(OneRow)
da.Update(rstAcctInfo) ' add this new user
' now add the data to personal
cmdSQL.Parameters.Clear()
cmdSQL.CommandText =
"INSERT INTO employeeInfo([FirstName], [MiddleName], [LastName], [PhoneNumber]) Values " &
"(#FN, #MN,#LN , #Phone)"
With cmdSQL.Parameters
.Add("#FN", OleDbType.VarWChar).Value = FirstName_Box.Text
.Add("#MN", OleDbType.VarWChar).Value = MidName_Box.Text
.Add("#LN", OleDbType.VarWChar).Value = LastName_Box.Text
.Add("#Phone", OleDbType.VarWChar).Value = ContactNumber_Box.Text
End With
cmdSQL.ExecuteNonQuery()
End Using
End Using

How can i resolve ExecucuteNonQuery throwing exception Incorrect syntex near '?'

Dim StrSql = "update student set id=?"
Updated (StrSql,15)
Public Function Updated (ByVal strSql As String, ByVal ParamArray Parameters As String ())
For Each x In Parameters
cmd.Parameters.AddWithValue("?",x)
Next
cmd.ExecuteNonQuery()
End Function
You didn't leave us much to go on; as jmcilhinney points out, you need to add more detail to future questions. For example in this one you have code there that doesn't compile at all, doesnt mention the types of any variable, you don't give the name of the database...
...I'm fairly sure that "Incorrect syntax near" is a SQL Server thing, in which case you need to remember that it (re)uses named parameters, unlike e.g. Access which uses positional ones:
SQL Server:
strSql = "SELECT * FROM person WHERE firstname = #name OR lastname = #name"
...Parameters.AddWithValue("#name", "Lee")
Access:
strSql = "SELECT * FROM person WHERE firstname = ? OR lastname = ?"
...Parameters.AddWithValue("anythingdoesntmatterwillbeignored", "Lee")
...Parameters.AddWithValue("anythingdoesntmatterwillbeignoredalso", "Lee")
This does mean your function will need to get a bit more intelligent; perhaps pass a ParamArray of KeyValuePair(Of String, Object)
Or perhaps you should stop doing this way right now, and switch to using Dapper. Dapper takes your query, applies your parameters and returns you objects if you ask for them:
Using connection as New SqlConnection(...)
Dim p as List(Of Person) = Await connection.QueryAsync(Of Person)( _
"SELECT * FROM person WHERE name = #name", _
New With { .name = "John" } _
)
' use your list of Person objects
End Using
Yep, all that adding parameters BS, and executing the reader, and converting the results to a Person.. Dapper does it all. Nonquery are done like connection.ExecuteAsync("UPDATE person SET name=#n, age=#a WHERE id=#id", New With{ .n="john", .a=27, .id=123 })
http://dapper-tutorial.net
Please turn on Option Strict. This is a 2 part process. First for the current project - In Solution Explorer double click My Project. Choose Compile on the left. In the Option Strict drop-down select ON. Second for future projects - Go to the Tools Menu -> Options -> Projects and Solutions -> VB Defaults. In the Option Strict drop-down select ON. This will save you from bugs at runtime.
Updated(StrSql, 15)
Your Updated Function calls for a String array. 15 is not a string array.
Functions need a datatype for the return.
cmd.Parameters.AddWithValue("?", X)
cmd is not declared.
You can't possible get the error you mention with the above code. It will not even compile, let alone run and produce an error.
It is not very helpful to write a Function that is trying to be generic but is actually very limited.
Let us start with your Update statement.
Dim StrSql = "update student set id=?"
The statement you provided will update every id in the student table to 15. Is that what you intended to do? ID fields are rarely changed. They are meant to uniquely identify a record. Often, they are auto-number fields. An Update command would use an ID field to identify which record to update.
Don't use .AddWithValue. See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
Here is another
https://andrevdm.blogspot.com/2010/12/parameterised-queriesdont-use.html
Since you didn't tell us what database you are using I guessed it was Access because of the question mark. If it is another database change the connection, command and dbType types.
Using...End Using block ensures you connection and command are closed and disposed even if there is an error.
Private ConStr As String = "Your Connection String"
Public Function Updated(StudentNickname As String, StudentID As Integer) As Integer
Dim RetVal As Integer
Using cn As New OleDbConnection(ConStr),
cmd As New OleDbCommand("Update student set NickName = #NickName Where StudentID = #ID", cn)
cmd.Parameters.Add("#NickName", OleDbType.VarChar, 100).Value = StudentNickname
cmd.Parameters.Add("#ID", OleDbType.Integer).Value = StudentID
cn.Open()
RetVal = cmd.ExecuteNonQuery
End Using
Return RetVal
End Function
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim RowsUpdated = Updated("Jim", 15)
Dim message As String
If RowsUpdated = 1 Then
message = "Success"
Else
message = "Failure"
End If
MessageBox.Show(message)
End Sub
This code keeps your database code separated from user interface code.

Data type mismatch when inserting record

I've this piece of code for inserting records into an Access table.
LastUpdated field is defined as Date/Time at database level. It fails when inserting giving the error
Data type mismatch in criteria expression
I'm using parameterized query which avoid problems with formatting values and it's very weird because I've the same code (with more parameters) to insert records on another table on which LastUpdated is defined in the same way and it's working fine.
Any idea?
SqlQuery = "INSERT INTO History (ActivityID, LastUpdated) VALUES (#p1,#p2)"
With sqlcommand
.CommandText = SqlQuery
.Connection = SQLConnection
.Parameters.AddWithValue("#p1", IDAct)
.Parameters.AddWithValue("#p2", DateTime.Today)
End With
result = sqlcommand.ExecuteNonQuery()
If (result = 1) Then
LabelWarning.Text = "Activity filled"
LabelWarning.BackColor = Color.ForestGreen
LabelWarning.Visible = True
ButtonSave.Visible = False
ButtonBack.Visible = False
ButtonOK.Visible = True
BlockControls()
End If
Maybe the problem is linked to parameter placeholder.
This MSDN doc states that OleDbCommand does not support named parameter (only positional) and the correct placeholder should be "?" and not "#p1".
https://msdn.microsoft.com/en-us/library/yy6y35y8%28v=vs.110%29.aspx
Edit
It turned out in comments that the placeholder have not to be so strictly adherent to the doc syntax. Only the order has to be absolutely preserved.
Explicitly declaring the parameter type however seemed to do the trick:
.Parameters.Add("#p2", OleDbType.DBTimeStamp)
.Parameters("#p2").Value = DateTime.Today