473,394 Members | 1,718 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Retreiving from a database

147 100+
Hi

I have moved to c# from vbscript, and consequently from ASP.old to ASP.Net

A quick question about SQL in C#.

In VBscript, I could use the line

Expand|Select|Wrap|Line Numbers
  1. Select * from Cars where Model like '%" + Replace(var_TextSearchedFor,"'","''") + "%'
This would then insert the variable var_TextSearchedFor and look for that under the column Model.

I can't do this in C#. It is driving me crazy as this was one of the easier things in VBscript.

If I enter a normal fixed 'where' clause then it works fine. But if I try to swap it with a variable, it won't work.

My current line reads:

Expand|Select|Wrap|Line Numbers
  1. command = new SqlCommand("Select * from Cars where ModelNumber like '%" + Replace(var_TextSearchedFor, "'", "''") + "%'", connection);
I have tried removing the double quote marks (speech marks) but this still didn't help. I get so far and it tells me "System.Data.SqlClient.SqlException: Invalid column name 'var_TextSearchedFor'."

Also, should this type of question be posted here or in the SQL section? I am using SQL Server Management Studio Express.

Thanks

Dave
May 29 '08 #1
5 1019
Curtis Rutland
3,256 Expert 2GB
Use this:
Expand|Select|Wrap|Line Numbers
  1. command = String.Format("select * from Cars where ModelNumber like '%{0}%'",var_TextSearchedFor.Replace("'","''"));
  2.  
Assuming that var_TextSearchedFor is a String.

String.Format replaces "{0}" with the first parameter, "{1}" with the second parameter, and so forth. So {0} would become the value of var_TextSearchedFor.Replace("'","''")

In C#, the Replace method is a member of the String class, so you have to call it from the string you are using it on.
May 29 '08 #2
DaveRook
147 100+
Hi insertAlias

Sadly this doesn't seem to work for me. It throws out a compiler error message: CS0029: Cannot implicitly convert type 'string' to 'System.Data.SqlClient.SqlCommand'

Please find my entire source code incase I missed something.
Expand|Select|Wrap|Line Numbers
  1.  
  2. protected void Page_Load(object sender, EventArgs e)
  3. {
  4. string var_MountType = "%";
  5. if (Request.QueryString["t"]!="") 
  6. if (Request.QueryString["t"]!=null)
  7. {
  8. if (Request.QueryString["mt"] == "sm")
  9. {
  10. var_MountType = "Surface Mount";
  11. }
  12. if (Request.QueryString["mt"] == "th")
  13. {
  14. var_MountType = "Through Hole";
  15. }
  16.  
  17. }
  18. SqlConnection connection;
  19. SqlCommand command;
  20. SqlDataReader reader;
  21. string connectionString = ConfigurationManager.ConnectionStrings["1mmBoardToBoard"].ConnectionString;
  22. connection = new SqlConnection(connectionString);
  23. command = String.Format("Select * from tb_1mm where MountType like '%{0}'", var_MountType.Replace("'", "''"));
  24.  
  25.  
  26. try
  27. {
  28. connection.Open();
  29. reader = command.ExecuteReader();
  30. rpBoardToBoard.DataSource = reader;
  31. rpBoardToBoard.DataBind();
  32. reader.Close();
  33. }
  34. finally
  35. {
  36. connection.Close();
  37. }
  38. }
  39.  
  40. The line that starts command = string.format... used to be:
  41.  
  42. command = new SqlCommand("Select * from tb_1mm where MountType = 'Through Hole'", connection); 
  43.  
This worked so I know the connection works correctly. It's just making it read the querystring to assign a variable to allow the correct SQL to be run.

Any ideas what I have done wrong?

Dave
Jun 2 '08 #3
Curtis Rutland
3,256 Expert 2GB
Hi insertAlias

Sadly this doesn't seem to work for me. It throws out a compiler error message: CS0029: Cannot implicitly convert type 'string' to 'System.Data.SqlClient.SqlCommand'
Yeah, sorry about that. I should have told you to try this:
Expand|Select|Wrap|Line Numbers
  1. string sqlCommandStr = String.Format("select * from Cars where ModelNumber like '%{0}%'",var_TextSearchedFor.Replace("'","''"));
  2. command = new SqlCommand(sqlCommandStr);
  3.  
I forgot that command is a SqlCommand object and not just the command string.
Jun 2 '08 #4
DaveRook
147 100+
Hello insertAlias

Thank you for all your help. One thing was missing (this is for others who may have the same problem)

The final command needed to include the ,connection statement

eg,
Expand|Select|Wrap|Line Numbers
  1. command = new SqlCommand(sqlCommandString, connection);
Thank you for all your help. I really appreciate this.

Will this work if there is more than query required?

eg, can I use the code

Expand|Select|Wrap|Line Numbers
  1. string sqlCommandStr = String.Format("select * from Cars where ModelNumber like '%{0}%'",var_TextSearchedFor.Replace("'","''") + " and where Colour like '%{0}%'",var_TextColor.Replace("'","''"));
Dave
Jun 2 '08 #5
Curtis Rutland
3,256 Expert 2GB
Glad to hear that it is working. There are multiple constructors for SqlCommand; I was assuming that you were assigning the Connection value later.

As to the new question, no that won't work like that. You should look up String.Format(). It replaces the {0} with the first parameter after the string. Let me help you break down what is going on and what you want to do.

Expand|Select|Wrap|Line Numbers
  1. string tSearchedFor = var_TextSearchedFor.Replace("'","''");
  2. string tColor = var_TextColor.Replace("'","''");
  3. string sqlCommandStr = String.Format("select * from Cars where ModelNumber like '%{0}%' and where Colour like '%{1}%'", tSearchedFor, tColor);
  4.  
I separated out some of the pieces so you can really see what is happening. String.Format() is removing the {#} and replacing it with the parameters that follow: {0} is the first parameter after the string, {1} is the second, and so forth.

Also, please use code tags in your posts; it will make your code easier to read.

Will this work if there is more than query required?

eg, can I use the code

string sqlCommandStr = String.Format("select * from Cars where ModelNumber like '%{0}%'",var_TextSearchedFor.Replace("'","''") + " and where Colour like '%{0}%'",var_TextColor.Replace("'","''"));


Dave
Jun 2 '08 #6

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Guy Erez | last post by:
Hi, I'm running queries with MySql 4.0.17 that return thousands of records. Because I need to present them in GUI, I returieve the results in chunks using LIMIT, for example - get first 100,...
2
by: Renuka | last post by:
Hello, I have to retrive 2 columns from the database which have HTML characters like &lt; &gt; (the less than"<" and greater than sign ">")in their data. Is there any function in C# which can do...
1
by: Sam | last post by:
If you go to the Design View for any database table in MS Access, you will find three fields- 1. Field Name - e.g. "PointID" 2. Data Type - e.g. "Text" 3. Description - e.g. "ID of the...
2
by: Reddy | last post by:
Hi, Once after inserting a record into a table is there a more efficient way of retreiving the id(autonumber field) value in the following example. Using a SQL server database. con.Open() ...
2
by: SpoonfulofTactic | last post by:
I am building a Blog for my own person use, and I would like to be able to use unicode characters outside the range of the ascii set. However, when I use odbc to access table data, Access returns...
2
by: dave m | last post by:
Here's the scenerio: I have several (10 - 30) PCs that periodically need to get data (simple Y/N flag values) from a server in the same network. While all PCs run SQL Server, I don't want to...
0
by: yogeeswar | last post by:
HI ALL I AM USING DB2 8.1 AND I HAVE TWO TABLES PARENT TABLE 1)CODE IS PRIMARY KEY CODE CODE_DESC CATEGORY ----------- ----------------------------------------...
1
by: yucefrizk | last post by:
hello all, I'm trying to write a code to retreive data from a database to an excel file, I achieved my code and everything is going good by running it through unix, but when I create a webpage to...
1
by: hafizfarooq | last post by:
Hello all, I want to retrieve the SQL SERVER database structure to edit Data type or Field name etc. Please help me
7
pradeepjain
by: pradeepjain | last post by:
hii, i have stored the images from form to database in blob format.now i have a necessity to retrieve image from database and store it in a folder ..how to do this.. thanks, ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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...
0
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...

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.