I am new with VB.net. I am having problems passing a null value from a VB.net textbox to the sql query string. this is my current code:
Dim sqlstatement as string
If generic_jobTxt.Text == '' Then
generic_jobTxt = DBNull.Value
End If
sqlstatement = "Insert into Job_db (generic_job) values('"+generic_jobTxt+"')"
how can i pass a null value to the sql string so that when i run the sql i get a null value in the generic_job column. Thank you!
First, never concatenate strings to build your sql query, instead use parameterized queries. Otherwise you're open for sql injection and other issues.
On that way you also don't need to fiddle around with apostrophes. But you should use the correct types.
Presuming you're using SQL-Server and the column type is varchar:
Dim sqlstatement = "Insert into Job_db (generic_job) values(#generic_job)"
Using con As New SqlConnection("connection-string")
Using insertCommand = New SqlCommand(sqlstatement, con)
Dim sqlParam = New SqlParameter("#generic_job", SqlDbType.VarChar)
Dim jobTxt As String = generic_jobTxt.Text.Trim()
sqlParam.Value = If(String.IsNullOrEmpty(jobTxt), Nothing, jobTxt)
insertCommand.Parameters.Add(sqlParam)
con.Open()
Dim inserted As Int32 = insertCommand.ExecuteNonQuery()
End Using
End Using
Related
What is the solution if you see the code below there is a value (2000) then I want to change it to textbox so I can custom value.
Thanks
jack
Dim sql As String = "update GSDTS as t1 inner join IFGTS as t2 on t1.[ITM] = t2.[ITM] set t1.[CIU] = t2.[PRSOBNET]+2000 WHERE GDN = 'A.04.01.002.001'AND PNM=#PNM"
Using conn As New OleDbConnection(cn),
cmd As New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#PNM", ComboBox1.SelectedValue)
conn.Open()
cmd.ExecuteNonQuery()
End Using
You can just add another parameter to your query like here
' Read the textbox value here'
Dim newValue as Integer
Int32.TryParse(txtInput.Text, newValue)
' Put the parameter placeholder instead of a constant'
Dim sql As String = "update GSDTS as t1 inner join IFGTS as t2
on t1.[ITM] = t2.[ITM]
set t1.[CIU] = t2.[PRSOBNET]+#addvalue
WHERE GDN = 'A.04.01.002.001'AND PNM=#PNM"
Using conn As New OleDbConnection(cn),
cmd As New OleDbCommand(sql, conn)
' Add the other parameter and its value before the old one. See note below'
cmd.Parameters.AddWithValue("#addvalue", newValue)
cmd.Parameters.AddWithValue("#PNM", ComboBox1.SelectedValue)
conn.Open()
cmd.ExecuteNonQuery()
End Using
Also, take a look at how to replace AddWithValue with a single line Add. AddWithValue is dangerous because it can misrepresents your value when working with dates or decimals and it is inefficient with strings
** IMPORTANT **
You are working with the OleDb provider. In this context the parameters should be added in the same order in which their placeholders appear in the string. So the new parameter should be added before the #PNM one otherwise they will be read in the wrong order when the query is executed.
Your SQL syntax wouldn't work for any RDBMS I know of and you didn't tag the backend. That might be solely a reason for it not to work at all, you should start by correcting it.
Second, do not use AddWithValue but Add and explicitly specify your data type.
Having said that, for example MS SQL server as a backend:
Dim sql As String = <sql>UPDATE GSDTS
SET [CIU] = t2.[PRSOBNET] + #addVal
FROM GSDTS AS t1
INNER JOIN IFGTS AS t2
ON t1.[ITM] = t2.[ITM]
WHERE t1.GDN = 'A.04.01.002.001'
AND t1.PNM = #PNM;</sql>
Dim addVal As Integer = Nothing
If Integer.TryParse(txtAdd.Text, addVal) Then
Using conn As New OleDbConnection(cn),
cmd As New OleDbCommand(sql, conn)
cmd.Parameters.Add("#addVal", OleDbType.Integer).Value = addVal
cmd.Parameters.Add("#PNM", OleDbType.VarChar).Value = ComboBox1.SelectedValue
conn.Open()
cmd.ExecuteNonQuery()
End Using
End If
Note that order of variable declarations are same as their order they are used in the query. That is a necessity with OleDb (positional arguments). If your backend is something like MS SQL server then prefer using backend specific SqlConnection, SqlCommand (then you can also use named parameters).
Please give me a solution.
I think I made the query code wrong
Private Sub PopulateDataGridView()
Dim query = "select ITM,ITC,QOH,PRS FROM IFG (WHERE QOH > 0 AND ITM = #ITM OR ISNULL(#ITM, '') = '')"
Dim constr As String = "provider=Microsoft.Jet.OLEDB.4.0; data source=C:\Users\ADMIN2\Desktop; Extended Properties=dBase IV"
Using con As OleDbConnection = New OleDbConnection(constr)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#ITM", cbCountries.SelectedValue)
Using sda As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
dataGridView1.DataSource = dt
End Using
End Using
End Using
End Sub
Syntax error in FROM clause.
contents of the database
It's a question about SQL syntax, really, and not so much vb.net or oledb.
You had two WHERE clauses, which is invalid SQL. Change the second WHERE to AND
Dim query As String = "select ITM,ITC,QOH,PRS FROM IFG WHERE QOH > 0"
query &= " AND ITM = #ITM"
By the way, since strings are immutable in vb.net, you should not build a string like that (first assigning to, then adding to) when you so clearly can avoid it because every concatenation creates a new string in memory. You can either use &, a StringBuilder, or one long string. For example, taking advantage of vb.net syntax to make a multiline string, you can change the vb.net to
Dim query = "
select ITM,ITC,QOH,PRS
FROM IFG
WHERE QOH > 0
AND ITM = #ITM"
which is [subjectively] much easier to read as a SQL query (add the proper parentheses based on your logic, of course!).
Based on your update, you need to add a parameter to the query. Here is a more or less complete example of a query with one parameter
Using con As New OleDbConnection("connection string")
Dim query = "
select ITM,ITC,QOH,PRS
FROM IFG
WHERE QOH > 0
AND ITM = #ITM"
Using cmd As New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#ITM", itmValue)
Using rdr = cmd.ExecuteReader()
For Each result In rdr.AsQueryable()
' do something with each result
Next
End Using
End Using
End Using
This question already has answers here:
How can I add user-supplied input to an SQL statement?
(2 answers)
'No value given for one or more required parameters.' Error, Can't get over it
(2 answers)
Closed 2 years ago.
I have the issue with the following function:
Public Function collectuserid(conn, username)
Dim sql As String = "select ID from tblUserDetails where Username =" & username
Dim usersid As String = Nothing
Using connection As New OleDbConnection(conn)
Using command As New OleDbCommand(sql, connection)
connection.Open()
usersid = CStr(command.ExecuteNonQuery())
connection.Close()
End Using
End Using
Return usersid
End Function
The problem occurs in the following line:
usersid = CStr(command.ExecuteNonQuery())
The variable conn holds the connection string, and username holds a value for the username present in the database.
I want to collect the userid of the record, but cant seem to get it right. I have the exact same function open in another program with a different database and it works perfectly. All table and variable names are correct also. Any help?
Program for generating the record:
Sub insertuservalues(conn, a, b, c, d)
Dim sql As String = "INSERT INTO tblUserDetails(Name,Username,[Password],Email) VALUES (#name, #username, #password, #email)"
Using connection As New OleDbConnection(conn)
Using command As New OleDbCommand(sql, connection)
connection.Open()
command.Parameters.Add("#name", OleDbType.VarWChar).Value = a
command.Parameters.Add("#username", OleDbType.VarWChar).Value = b
command.Parameters.Add("#password", OleDbType.VarWChar).Value = c
command.Parameters.Add("#email", OleDbType.VarWChar).Value = d
command.ExecuteNonQuery()
connection.Close()
End Using
End Using
End Sub
Strictly speaking, the mistake you made was that you didn't wrap your literal text value within the SQL code in single quotes. Just as VB literal text must be wrapped in double quotes, so SQL literal text must be wrapped in single quotes:
Dim sql As String = "SELECT ID FROM tblUserDetails WHERE Username = '" & username & "'"
or:
Dim sql As String = String.Format("SELECT ID FROM tblUserDetails WHERE Username = '{0}'", username)
or:
Dim sql As String = $"SELECT ID FROM tblUserDetails WHERE Username = '{username}'"
If you do it the right way though, and follow the advice to use parameters, this becomes redundant. ALWAYS use parameters to avoid formatting issues, special character issues and, most importantly, SQL injection issues.
You need single quotes around string values in the SQL. But don't do that! Instead, define this as a query parameter:
Public Function collectuserid(conn As String, username As String) As String
'No string concatentation!
' Also, OleDb tends to use ? placeholders for positional parameters, rather than parameter names.
Dim sql As String = "select ID from tblUserDetails where Username = ?"
Using connection As New OleDbConnection(conn)
Using command As New OleDbCommand(sql, connection)
'Use the actual type and length from the database here
command.Parameters.Add("username", OleDbtype.VarWChar, 20).Value = username
connection.Open()
Return CStr(command.ExecuteNonQuery())
'No need to call connection.Close()
' The Using block guarantees the connection will close, even though we Return before reaching the end of it.
End Using
End Using
End Function
This question already has an answer here:
Escaping apostrophe/single quote in parameterized sql in asp
(1 answer)
Closed 4 years ago.
I am trying to insert data using sql query in vb.net as follows. name = corp int'l poc = 1
When I tried to insert, I get an error ("Unclosed Quotation Mark after the character String '"). This happens when I tried to insert name with only 1 single quote.
Therefore I added a replace function to replace 1 single quote with 2 single quote to escape the symbol. There was no error but when I look into my database, 2 single quotes are added instead of 1.
Can anyone advise me how I can escape the single quote with my parameterized query? Thanks!
Public Function InsertData(ds As DataSet) As Boolean
Dim cmd As New SqlCommand
Dim cmd1 As New SqlCommand
Dim status As Boolean
Dim name As String
Dim poc As String
Dim id_p As New SqlParameter("id", SqlDbType.VarChar)
Dim name_p As New SqlParameter("name", SqlDbType.VarChar)
cmd.Parameters.Add(id_p)
cmd.Parameters.Add(name_p)
For i = 0 To ds.Tables(0).Rows.Count - 1
If checkExists(ds.Tables(0).Rows(i)(1).ToString(), ds.Tables(0).Rows(i)(2).ToString(), ds.Tables(0).Rows(i)(3).ToString()) = True Then
name = ds.Tables(0).Rows(i)(1).ToString()
poc = ds.Tables(0).Rows(i)(2).ToString()
If name.Contains("'") Then
name = name.Replace("'", "''")
End If
If poc.Contains("'") Then
poc = poc.Replace("'", "'")
End If
name_p.SqlValue = name
id_p.SqlValue = poc
cmd.CommandText = "INSERT INTO Code (Name,ID)" _
& " VALUES (#name,#id)"
status = ExecuteNonQuerybySQLCommand(cmd)
End If
Next
Return status
End Function
Dim strcon As String = "Data Source=x.x.x.x,1433;Network Library=DBMSSOCN;Initial Catalog=code_DB;User ID=xxx;Password=xxx;"
Public Function ExecuteNonQuerybySQLCommand(ByVal cmd As SqlCommand) As Boolean
Dim sqlcon As New SqlConnection
Dim i As Integer = 0
sqlcon.ConnectionString = strcon
cmd.Connection = sqlcon
Try
sqlcon.Open()
i = cmd.ExecuteNonQuery()
sqlcon.Close()
If i > 0 Then
Return True
Else
Return False
End If
Catch ex As Exception
Console.Write(ex)
Return False
End Try
End Function
Values passed as parameters (i.e. SqlParameter object) do not need to be escaped. This is because the client API uses an RPC call to execute the query, with the query itself and parameters passed separately. With an RPC call, the actual parameter values are sent to SQL Server in native (binary) format over the TDS protocol rather than embedded within the statement. This mitigates SQL injection concerns and provides other benefits, such as strong-typing and improved performance.
I got this error when trying to use parameters to my sql statement, but it works fine when not use it. My codes are below:
Dim i As String
Dim sql as String
sql = "SELECT * FROM tblStaff WHERE Username = #User AND Password = #Pass"
myCommand = New SqlCommand(sql, myConnection)
myCommand.Parameters.AddWithValue("#User", txtUser.Text)
myCommand.Parameters.AddWithValue("#Pass", txtPassword.Text)
i = myCommand.ExecuteScalar
txtUserType.Text = i.ToString
And when I comment on txtUserType.Text = i.ToString, it works fine. Any idea?
ExecuteScalar should only give you one value back, like an integer. So if you specify only one column in your SQL statement for example (Select usertype from tblStaff...) the executescalar should return an integer (if that column is a number).
Then it should work.
and by the way.. you don't have to use ToString on a variable that is a string. Just use the variables name
txtUserType.Text = i