string SqlSelectQuery = " Select * From KTS Where STAFFNAME =" + Convert.ToChar(textBox1.Text);
SqlCommand cmd = new SqlCommand(SqlSelectQuery, CON);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
textBox2.Text = (dr["JOB TITLE"].ToString());
textBox3.Text = (dr["EXTN"].ToString());
textBox4.Text = (dr["Direct No."].ToString());
textBox5.Text = (dr["MOBILE (OFFICE)"].ToString());
textBox6.Text = (dr["SNO"].ToString());
i want to load data from sql server to visual studio by entering the name of the first name for the employee and he's job title mobile ext ....blla blla blla appear in the textboxes and my error is string must be exactly one character long
Convert.ToChar(textBox1.Text) requires a single character string, otherwise it throws a FormatException.
Your query should be
string SqlSelectQuery = " Select * From KTS Where STAFFNAME ='" + Convert.ToString(textBox1.Text)+"'";
You probably should use
Convert.ToString(textBox1.Text);
instead of
Convert.ToChar(textBox1.Text);
because you can't fit a String into a Char, and the textbox content will be most likely longer than one character
As per #RupeshPandey answer, you're also missing the quote to delimit the string in your query. your instruction should be
string SqlSelectQuery = "Select * From KTS Where STAFFNAME = '" +
Convert.ToString(textBox1.Text) +
"'";
Related
I'm having problems trying to make this work, I have this query on an application that Im writing in vb.net 2012:
Dim strSql As String = " SELECT * FROM Table_Master WHERE field & "'= ('" & txtCadena.Text & "')"
What I need is to have the option to choose the field that I'm querying writing the field name on a textbox.
Maybe something like:
strSql As String = string.format("SELECT * FROM Table_Master WHERE [{0}] = '{1}'", txtField.text, txtFieldValue.text.replace("'","''"))
This should work (only for text, not dates, numbers etc) but you have to know that it is not the best practice.
I finally made it doing this.
Dim Query As String
Dimm DT As DataTable = New DataTable
Query = "select Actual, Description, Unit_of_measurement from Table_ARTIClES WHERE NUMPART = '" & txtPartNum.Text & "'"
Dim Table As SqlDataAdapter = New SqlDataAdapter(Query, conn)
Table.Fill(DT)
lblInventory.Text = DT.Rows(0)("Actual").ToString
I am taking over a VB project and with my limited VB skills I cannot get the following to parameterized query to return results:
Dim strSQLUser As String = "Select Name, CompanyID from Users where UserName = #UserName"
dbCommand = New SqlCommand(strSQLUser, dbConn)
dbCommand.Parameters.AddWithValue("#UserName", User)
dr = dbCommand.ExecuteReader
However this is the original code that does work:
Dim strSQLUser As String = "Select Name, CompanyID from Users where UserName ='" & User & "'"
dbCommand = New SqlCommand(strSQLUser, dbConn)
dr = dbCommand.ExecuteReader
As you can see the original code was vulnerable to sql injection and needs to be fixed.
Extra - Here is the line that does the reading:
While dr.Read
DbUser = dr.GetValue(0).ToString
DbCompany = dr.GetValue(1).ToString
End While
Try this:
Dim strSQLUser As String = "Select Name, CompanyID from Users where UserName =#UserName"
dbCommand = New SqlCommand(strSQLUser, dbConn)
dbCommand.Parameters.AddWithValue("#UserName", User.Text)
dr = dbCommand.ExecuteReader
Also the better approach is provide the value as:
dbCommand.Parameters.Add("#UserName", SqlDbType.VarChar).Value = User.Text
Assuming User to be the varchar ie., text type.
When using parameters you do not specify the quotes around parameters '. All the parameters are automatically converted to their respective column types such as date, nvarchar etc. So no more quotes.
Dim strSQLUser As String = "Select Name, CompanyID from Users where UserName =#UserName"
I have this vb.net function:
Function CheckBillingRun(customer, type, month, year)
Dim conn = New MySqlConnection()
Dim myCommand As New MySqlCommand
Dim reader As MySqlDataReader
Dim SQL As String
Dim result As String
conn.ConnectionString = "server=" + global_variables.web_server_ip + "; user id=" + global_variables.web_server_username + "; password=" + global_variables.web_server_password + "; database=" + global_variables.web_server_database + "; "
conn.Open()
SQL = "SELECT COUNT(sequence) from billing_runs WHERE customer = '" + customer + "' AND type = '" + type + "' AND MONTH(datetime) = '" + month + "' AND YEAR(datetime) = '" + year + "' "
myCommand.Connection = conn
myCommand.CommandText = SQL
reader = myCommand.ExecuteReader
reader.Read()
result = reader.GetString(0)
conn.Close()
Return result
End Function
I am trying to call it in my application using this code:
If CheckBillingRun(reader.GetString(0), "Voice Billing", DateTime.Now.ToString("MM"), DateTime.Now.ToString("yyyy") > 0) Then
Continue While
End If
reader.getstring(0) equals 278
but i am getting an error saying:
Additional information: Conversion from string "SELECT COUNT(sequence) from bill" to type 'Double' is not valid.
The string concatenation operators in VB.NET are & or +, but if you use the + operator and you have Option Strict Off set for your project you could have surprises like this. The compiler knows that one or more of the your parameters passed to this function are not strings but number, and in this context the + operator tries to convert everything to a number. Try to use the & operator to concatenate strings.
Said that, DO NOT CONCATENATE strings to build sql commands.
Use a parameterized query to avoid Sql Injection and other parsing problems.
For example, your code could be something like this
Function CheckBillingRun(ByVal customer as String , ByVale type as String, _
ByVal month as Integer, ByVal year as Integer) as Integer
Dim SQL = "SELECT COUNT(sequence) from billing_runs " & _
"WHERE customer = #customer AND type = #type " & _
"AND MONTH(datetime) = #month AND YEAR(datetime) = #year"
Using conn = New MySqlConnection()
Using myCommand As New MySqlCommand(SQL, conn)
Dim result As Integer = 0
conn.ConnectionString = "......."
conn.Open()
myCommand.Parameters.Add("#customer", MySqlDbType.VarChar).Value = customer
myCommand.Parameters.Add("#type", MySqlDbType.VarChar).Value = type
myCommand.Parameters.Add("#month", MySqlDbType.Int).Value = month
myCommand.Parameters.Add("#year", MySqlDbType.Int).Value = year
Using reader = myCommand.ExecuteReader
if reader.Read() Then
result = reader.GetInteger(0)
End If
End Using
Return result
End Using
End Using
End Function
call it with
CheckBillingRun(reader.GetString(0), "Voice Billing", _
DateTime.Now.Month, DateTime.Now.Year)
In this version every variable used has its type specified to avoid any possible unwanted automatic conversion by the compiler. Notice also that COUNT returns a number, not a string. Treating numbers like they were strings is a bad habit to dismiss as soon as possible. Look at your project properties an try what happen if you set the Option Strict to ON
If the first parameter of your method CheckBillingRun accepts double, you should use the method Convert.ToDouble() to convert the value from a string to double, like this:
instead if
If CheckBillingRun(reader.GetString(0), .....
do the following:
If CheckBillingRun(Convert.ToDouble(reader.GetString(0)), .....
All the best.
I have a function in VB.NET that runs a query from an MS SQL DB, puts the results into temporary variables, then updates an Oracle DB. My question is, if the string in the MS SQL contains a single quote ( ' ), how do I update the Oracle DB for something that has that single quote?
For example: Jim's request
Will produce the following error: ORA-01756: quoted string not properly terminated
The ueio_tmpALM_Comments (coming from MS SQL) is the culprit that may or may not contain the single quote.
update_oracle =
"update Schema.Table set ISSUE_ADDED_TO_ALM = '1'," & _
"ISSUE_COMMENTS = '" & ueio_tmpALM_Comments & "'," & _
"where ISSUE_SUMMARY = '" & ueio_tmpALM_Summary & "' "
Dim or_cmd_2 = New NetOracle.OracleCommand(update_oracle, OracleConn)
or_cmd_2.ExecuteNonQuery()
From your question it's clear that you are building the update query using string concatenation.
Something like this
Dim myStringVar as string = "Jim's request"
Dim sqlText as String = "UPDATE MYTABLE SET MYNAME = '" + myStringVar + "' WHERE ID = 1"
this is a cardinal sin in the SQL world. Your code will fail for the single quote problem, but the most important thing is that this code is subject to Sql Injection Attacks.
You should change to something like this
Dim cmd As OraclCommand = new OracleCommand()
cmd.Connection = GetConnection()
cmd.CommandText = "UPDATE MYTABLE SET MYNAME = :myName WHERE ID = 1"
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue(":myName", myStringVar)
cmd.ExecuteNonQuery()
Trying to select an integer from an Access Database using an SQL statement in VB
Dim cmdAutoTypes As New OleDbCommand
Dim AutoTypesReader As OleDbDataReader
cmdAutoTypes.CommandText = "SELECT * FROM AutoTypes WHERE TypeId = '" & cboTypeIds.Text & "'"
AutoTypesReader = cmdAutoTypes.ExecuteReader
Error message says: "OleDbException was unhandled: Data type mismatch in criteria expression." and points to the AutoTypesReader = cmdAutoTypes.ExecuteReader line
Rather make use of OleDbParameter Class
This will also avoid Sql Injection.
You don't need the quotes in the query string. You're searching for a number, not a string.
cmdAutoTypes.CommandText = "SELECT * FROM AutoTypes WHERE TypeId = " & cboTypeIds.Text
Hi In access SQL you can't use single quote around your Integer type.
so
command text will be.. "SELECT * FROM AutoTypes WHERE TypeId = " & cboTypeIds.Text & " and .... "
In Access SQL, don't quote numeric constants.
And test whether IsNull(cboTypeIds). You can't do what you were planning to do until a value has been chosen.
Do not use string concatenation when you build your SQL query, use parameters instead.
Dim cmd As OledbCommand = Nothing
Dim reader as OleDbDataReader = Nothing
Try
Dim query As String = "SELECT * FROM AutoTypes WHERE TypeId = #Id"
cmd = New OledbCommand(query, connection)
//adding parameter implicitly
cmd.Parameters.AddWithValue("#Id", cboTypeIds.Text)
reader = cmd.ExecuteReader()
Catch ex As Exception
Messagebox.Show(ex.Message, MsgBoxStyle.Critical)
End Try
You can also explicitly state the parameter data type.
cmd.Parameters.Add("#Id", OleDbType.Integer).Value = cboTypeIds.Text
Hope this helps.