473,804 Members | 3,672 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Query SQL using variables.

Hi,
I have a simple (?) question for you all experts.
I have a button that performs a query on my SQL and fill a datagrid on
the form
The code:
Dim sconn As New SqlConnection()
sconn.Connectio nString = "Data Source=(my.Serv er;Initial
Catalog=MyDB;Pe rsist Security Info=True;User ID=sa;Password= Mypass"
Dim filterresults As New SqlDataAdapter( "Select * from
contacts ", sconn)
Dim contactsresult As New DataSet("result ")
If Not IsNothing(filte rresults) Then
filterresults.F ill(contactsres ult)
filterresults.D ispose()
End If
Me.ContactsData GridView.DataSo urce = contactsresult. Tables(0)

The code works, and I get my results.

My next step would be taking two variables from my code and use them
on the query IE: (which btw I collect from two combo boxes on the same
form)
Select * from contacts WHERE CITY=VARIABLE AND TYPE=VARIABLE"

I lack the knowladge ƒ¼ could anyone help me out here?
Code sample would be GREATLY appreciated
Jan 1 '08 #1
17 1767

<R.*****@gmail. comwrote in message
news:3e******** *************** ***********@t1g 2000pra.googleg roups.com...
Hi,
I have a simple (?) question for you all experts.
I have a button that performs a query on my SQL and fill a datagrid on
the form
The code:
Dim sconn As New SqlConnection()
sconn.Connectio nString = "Data Source=(my.Serv er;Initial
Catalog=MyDB;Pe rsist Security Info=True;User ID=sa;Password= Mypass"
Dim filterresults As New SqlDataAdapter( "Select * from
contacts ", sconn)
Dim contactsresult As New DataSet("result ")
If Not IsNothing(filte rresults) Then
filterresults.F ill(contactsres ult)
filterresults.D ispose()
End If
Me.ContactsData GridView.DataSo urce = contactsresult. Tables(0)

The code works, and I get my results.

My next step would be taking two variables from my code and use them
on the query IE: (which btw I collect from two combo boxes on the same
form)
Select * from contacts WHERE CITY=VARIABLE AND TYPE=VARIABLE"

I lack the knowladge ƒ¼ could anyone help me out here?
Code sample would be GREATLY appreciated
Dim var1 as string
Dim var2 as string
dim sqlstr as string

var1 = "hello"
var2 = "to me"
sqlstr = "Select * from contacts WHERE CITY = " &var1 &" AND TYPE = " &var2

SqlDataAdapter( strsql, sconn)

if the data you needed was numeric, then you do this.

dim var1 as int
dim var2 as int

var1 = 9
var2 = 10
sqlstr = "Select * from contacts WHERE CITY CODE = " &var1.ToSrting( ) &" AND
TYPE = " &var2.ToString( )

Jan 1 '08 #2
On Jan 1, 2:49 pm, "Mr. Arnold" <MR. Arn...@Arnold.c omwrote:
<R.Ra...@gmail. comwrote in message

news:3e******** *************** ***********@t1g 2000pra.googleg roups.com...
Hi,
I have a simple (?) question for you all experts.
I have a button that performs a query on my SQL and fill a datagrid on
the form
The code:
Dim sconn As New SqlConnection()
sconn.Connectio nString = "Data Source=(my.Serv er;Initial
Catalog=MyDB;Pe rsist Security Info=True;User ID=sa;Password= Mypass"
Dim filterresults As New SqlDataAdapter( "Select * from
contacts ", sconn)
Dim contactsresult As New DataSet("result ")
If Not IsNothing(filte rresults) Then
filterresults.F ill(contactsres ult)
filterresults.D ispose()
End If
Me.ContactsData GridView.DataSo urce = contactsresult. Tables(0)

The code works, and I get my results.

My next step would be taking two variables from my code and use them
on the query IE: (which btw I collect from two combo boxes on the same
form)
Select * from contacts WHERE CITY=VARIABLE AND TYPE=VARIABLE"

I lack the knowladge ƒ¼ could anyone help me out here?
Code sample would be GREATLY appreciated

Dim var1 as string
Dim var2 as string
dim sqlstr as string

var1 = "hello"
var2 = "to me"

sqlstr = "Select * from contacts WHERE CITY = " &var1 &" AND TYPE = " &var2

SqlDataAdapter( strsql, sconn)

if the data you needed was numeric, then you do this.

dim var1 as int
dim var2 as int

var1 = 9
var2 = 10

sqlstr = "Select * from contacts WHERE CITY CODE = " &var1.ToSrting( ) &" AND
TYPE = " &var2.ToString( )
Hi Mr.arnold and thanks for the reply!
it gives me a syntex error on the sqlstr, it's just wont use the
vars...
and it's text i query not numeric.

any suggestions?
Jan 1 '08 #3

<R.*****@gmail. comwrote in message
news:71******** *************** ***********@q77 g2000hsh.google groups.com...
On Jan 1, 2:49 pm, "Mr. Arnold" <MR. Arn...@Arnold.c omwrote:
<R.Ra...@gmail. comwrote in message

news:3e******** *************** ***********@t1g 2000pra.googleg roups.com...
<snipped>
Hi Mr.arnold and thanks for the reply!
it gives me a syntex error on the sqlstr, it's just wont use the
vars...
and it's text i query not numeric.

You can use the ToString() for the string data too.

any suggestions?
----------------
What you need to do is put a brake point on the line right after the build
of the strsql variable.

You then need to use the Quick Watch, copy the text of the string data that
was created for the SQL statement. You can right-click the variable to get
to Quick Watch.

If you have SQL Server on the machine and it is SQL Server 2000, then you
will start SQL Server Query Analyzer and past the SQL text into the pane,
highlight and execute it.

Or if it is SQL 2005 that you have, then you use the SQL Server Management
Studio, New Query, and past the text in the pane and highlight and execute
it.

Let SQL Server tell you what's wrong with the statement by using one of the
solutions above..

Jan 1 '08 #4

<R.*****@gmail. comwrote in message
news:71******** *************** ***********@q77 g2000hsh.google groups.com...
On Jan 1, 2:49 pm, "Mr. Arnold" <MR. Arn...@Arnold.c omwrote:
<R.Ra...@gmail. comwrote in message
any suggestions?

Oh, you might have to do this that is put quotes around the variables, since
it's string data.

sqlstr = "Select * from contacts WHERE CITY = " &"'" &var1 &"'" &" AND TYPE
= " &"'" &var2 &"'"
Jan 1 '08 #5
On Jan 1, 4:23 pm, "Mr. Arnold" <MR. Arn...@Arnold.c omwrote:
<R.Ra...@gmail. comwrote in message

news:71******** *************** ***********@q77 g2000hsh.google groups.com...
On Jan 1, 2:49 pm, "Mr. Arnold" <MR. Arn...@Arnold.c omwrote:
<R.Ra...@gmail. comwrote in message

any suggestions?

Oh, you might have to do this that is put quotes around the variables, since
it's string data.

sqlstr = "Select * from contacts WHERE CITY = " &"'" &var1 &"'" &" AND TYPE
= " &"'" &var2 &"'"
Hey Arnold,
this time the string you gave me worked!
only now i get a different error which is my fault since I forgot to
say..

the second var, returns a text and symbol, for example (only - and + )
X-
X+
So the error I get now is:
Unclosed quotation mark after the character string ''.
An expression of non-boolean type specified in a context where a
condition is expected, near ''.

I know the string work..because I edited the string and it worked with
no error:
sqlstr = "Select * from contacts where city = " & "'" & var1 & "'"

any suggestions?
Jan 1 '08 #6

<R.*****@gmail. comkirjoitti viestissä
news:24******** *************** ***********@w56 g2000hsf.google groups.com...
I know the string work..because I edited the string and it worked with
no error:
sqlstr = "Select * from contacts where city = " & "'" & var1 & "'"

any suggestions?
Try this:

sqlstr = "Select * from contacts WHERE CITY = '" & var1 _
& "' AND TYPE='" & var2 & "';"

I have to warn you that this kind of query is very dangerous because users
can include '-characters to the query and make SQL injections to your
database.

-Teemu
Jan 1 '08 #7

<R.*****@gmail. comwrote in message
news:24******** *************** ***********@w56 g2000hsf.google groups.com...
On Jan 1, 4:23 pm, "Mr. Arnold" <MR. Arn...@Arnold.c omwrote:
><R.Ra...@gmail .comwrote in message

news:71******* *************** ************@q7 7g2000hsh.googl egroups.com...
On Jan 1, 2:49 pm, "Mr. Arnold" <MR. Arn...@Arnold.c omwrote:
<R.Ra...@gmail. comwrote in message

any suggestions?

Oh, you might have to do this that is put quotes around the variables,
since
it's string data.

sqlstr = "Select * from contacts WHERE CITY = " &"'" &var1 &"'" &" AND
TYPE
= " &"'" &var2 &"'"

Hey Arnold,
this time the string you gave me worked!
only now i get a different error which is my fault since I forgot to
say..

the second var, returns a text and symbol, for example (only - and + )
X-
X+
So the error I get now is:
Unclosed quotation mark after the character string ''.
An expression of non-boolean type specified in a context where a
condition is expected, near ''.

I know the string work..because I edited the string and it worked with
no error:
sqlstr = "Select * from contacts where city = " & "'" & var1 & "'"

any suggestions?
I think you have to get a closing quote in there at the end of the string.
This link may help you. You should next look into Stored Procedure and
passing parms/variables to the Stored Procedure and executing it, when you
become more comfortable in what your doing.

http://www.code-magazine.com/Article...uickid=0211121
Take the error message and past it into Google. I am sure you'll see a
solution to your problem.
>Unclosed quotation mark after the character string ''.
An expression of non-boolean type specified in a context where a
condition is expected, near ''.
Jan 1 '08 #8
Rafii,

First try to use the right names for the right things. By instance, don't
talke about a datagrid while you use a datagridview in your code. Those are
in fact two complete different kind of grids.

To review your code (including your question)
>>Dim sconn As New SqlConnection()
sconn.Connecti onString = "Data Source=(my.Serv er;Initial
Catalog=MyDB; Persist Security Info=True;User ID=sa;Password= Mypass"
>>Dim filterresults As New SqlDataAdapter( "Select * from contacts ", sconn)
Try to keep the name, this is not a filterresult, this is a construction of
a DataAdapter.

This can be including your where clause

Dim da As New SqlDataAdapter( "Select * from contacts WHERE CITY=@VARIABLE1
AND TYPE=@VARIABLE2 ", sconn)

I have let it, however it is never right to use a dataname as "Type", I
would in your place give that in your database and in your code another
name.
>>Dim contactsresult As New DataSet("result ")
If Not IsNothing(filte rresults) Then
The DataAdapter is never nothing, you have constructed it above therefore
this if is complete without any sence. Therefore you can remove it.

For selection in a select string it is for more than one reason good to use
parameters. It makes at least your code more visible and easy to handle.

da.SelectComman d.Parameters.Cl ear()
'The code above is in fact only needed all second times, however it does not
bother to place it in that instead an if or whatever more costly instruction
than the one above.

da.SelectComman d.Parameters.Ad d(New SqlParameter("@ Variable1",
TheCityField))
da.SelectComman d.Parameters.Ad d(New SqlParameter("@ Variable2",
TheTypeField))
>>filterresults .Fill(contactsr esult)
this one I have changed in
da.Fill(contact result) 'filterresult is in my idea a confusing answer it is
a result of the fill (at SQL side the name is ResultSet
>>filterresults .Dispose()
This dispose does nothing, the dispose is there because it is inherrited
from components, but that does not mean that you should use it.
>>End If
The End If above can go of course too away because of the removing of the if

Me.ContactsData GridView.DataSo urce = contactsresult. Tables(0)

It would be better to set all this code inside a Try and Catch block,
however that would make it in my idea to confusing to tell it direct.

Cor

Jan 1 '08 #9
On Tue, 1 Jan 2008 04:23:40 -0800 (PST), R.*****@gmail.c om wrote:
>Hi,
I have a simple (?) question for you all experts.
I have a button that performs a query on my SQL and fill a datagrid on
the form
The code:
Dim sconn As New SqlConnection()
sconn.Connectio nString = "Data Source=(my.Serv er;Initial
Catalog=MyDB;P ersist Security Info=True;User ID=sa;Password= Mypass"
Dim filterresults As New SqlDataAdapter( "Select * from
contacts ", sconn)
Dim contactsresult As New DataSet("result ")
If Not IsNothing(filte rresults) Then
filterresults.F ill(contactsres ult)
filterresults.D ispose()
End If
Me.ContactsData GridView.DataSo urce = contactsresult. Tables(0)

The code works, and I get my results.

My next step would be taking two variables from my code and use them
on the query IE: (which btw I collect from two combo boxes on the same
form)
Select * from contacts WHERE CITY=VARIABLE AND TYPE=VARIABLE"

I lack the knowladge ?? could anyone help me out here?
Code sample would be GREATLY appreciated
Use Parameters to supply the values. Cor has given you some code to
use.

Parameters do two thing for you over just putting the values you need
in the Select statement. First they format the value - no need to add
quotes around text, or put dates into whatever format the database
needs. Second they prevent SQL injection, which malicious users can
use to make arbitrary changes to your database.
Jan 1 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
11777
by: shank | last post by:
Per a previous suggestion, I'm trying to use a parametized query in Access 2002. The query functions properly in Access. Now I'm trying to call it from ASP. I'm using code I found at http://www.xefteri.com/articles/apr302002/default.aspx and trying to adjust for my needs. I'm getting this error. The query is there and functioning. It appears that I'm not connecting. Can I get some more insight? thanks! ------------------------------...
11
5416
by: Eugenio | last post by:
Excuse me in advance fo my little English. I've got this stored procedure **************************************************************************** ********** declare @Azienda as varchar(3), @Utente as varchar(20), @DataDa as datetime, @DataA as datetime, @AreaDa as varchar(3), @AreaA as varchar(3),
3
5395
by: Harvey | last post by:
Hi, I try to write an asp query form that lets client search any text-string and display all pages in my web server that contain the text. I have IIS 6.0 on a server 2003. The MSDN site says there is a sample file called Ixtrasp.asp, but I could not find it in my system although I installed indexing service. I followed the steps in MSDN site to create a basic .asp query form (too long to post it here), but it always displays: No...
2
18702
by: Dom | last post by:
I need to run a query based on a query in Access. The second query has a number of conditions which all work well, but there is one more contition I need to set to make it run properly. the first query returns a number of data items, consisting, among other fields, of a Company_ID and a Rating_Date. For most companies, the latest value of Rating_Date is equal to a value in a seperate table (tblVariables) which logs the last time a...
6
29944
by: Martin Lacoste | last post by:
Ok, before I headbutt the computer... don't know why when I add criteria in a query, I get an 'invalid procedure call'. I also don't know why after searching the help in access, the various access newsgroups, the access support centre, I can seem to find no similar situation. I am not using any references, or VBA at all in the first place. I am trying to set up a simple (or so I thought) query to work with the text of two tables. ...
0
3032
by: totierne | last post by:
comp.databases.ms-access, I want to know how to use Oracle views with session variables in Access. The parameterised views in access, are migrated to views with per session variables. The open questions: How to display a resultset
2
2015
by: comp.lang.php | last post by:
I am trying to replace within the HTML string $html the following: With Where I'm replacing "action=move_image" with "action=<?= $_REQUEST ?>"
3
2239
accessbunnie
by: accessbunnie | last post by:
Hello Access Users! I am a bit of an Access novice and am currently creating a database and have come up against a huge (for me!) road block. I do not write in Access code and instead, tend to just use design view and wizards to create my databases. I created a form using a query I created composed of two different tables with the same unique identifier. All things went fine while I dragged my variables from the field list to the...
0
1449
by: Jim Kennedy | last post by:
If you are firing that many queries you better be using bind variables and parsing the query once and rebinding, and executing many times and NOT closing the cursor. Doing that will help you immensely lower CPU usage. You are sending the queries sychronsly and the type of queries you are sending are not suited for doing parallel queries on (" single row from the a table and uses the primary key in its WHERE predicate"). Parallel queries...
4
4591
by: zion4ever | last post by:
Hello good people, Please bear with me as this is my first post and I am relative new to ASP. I do have VB6 experience. I have a form which enables users within our company to do an intranet reservation of available resources (laptops, beamers, etc). The MySql database queries are already in place, as is the ASP administration panel. The frontend that users will see however, still needs some work. I'm really close, but since I'm no...
0
9704
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10562
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10303
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10070
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9132
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7608
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6845
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5639
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4282
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.