Creating Generic MySQL SELECT Statement in C# - c#

There are a few similar questions, but none of them seem to answer my problem.
In my application I use lots of different SELECT queries and I don't want to write a method for every one, so I'm trying to create a generic one that I can just pass the specific parameters in.
This is the specific example that I'm trying to modify:
SELECT Statement
This is my attempt at generalising it:
Generic SELECT Statement
I have considered trying to split up columns string by the comma delimiter, using list or arrays, but I can't work out how to solve this issue. The specific bit that I want help with is the line with the error ("cannot convert from 'System.Collections.Generic.List' to 'int'"), but I don't know enough about data readers to fix it...
Any help would be greatly appreciated.

I have a doubt, why do you need to pass columnNames as array of List<string>.
array is not needed what I feel. Try passing just the List or array of string and let me know if it worked...

Related

How to generate dynamic multi-dimensional list or array and insert data accordingly based on a dynamic SQL Server table in c#?

I want to create a dynamic 2-dimensional array (or any other structure) based on a dynamic database table in C# or T-SQL, which means the data source (which is a database table) is dynamic too.
EDIT:
Table structure:
For example:
If User1 meets the condition of Admin and Group1, it will be inserted into (Admin, Group1). And the users are constantly added in with different user type and group. So, every cellular can have as many as users.
And the problem is I don't know how many user types and groups there are, because new user types and new groups are added constantly too.
For now, I think I need to parse every data to find if it meets the existing conditions. If yes, insert it into the specific condition; if not, create a new condition and insert data into it.
But I don't have any idea about how to implement it? Do you have any ideas or algorithms?
Thanks very much for any suggestion or information.
I've solved this statically with Tuple, but not dynamically. I think I should re-fresh my tuple list periodically. But at least, it works now!
Any suggestions are welcome! Thanks!

The variable name '#' has already been declared

Part of our solution is a page that displays company-specific information using an ASP Gridview. Our method of constructing the SQL that feeds the Gridview is by using C# to build a custom SELECT statement based on a series of user inputs.
Once the user applies their filters through a button click, C# loops through all of their selections (check boxes and text boxes) and then propagates those selections to a separate method which constructs a WHERE clause to append to a simple SELECT statement. We use a Table-Valued Function in the FROM statement, and the only input parameter is from the Querystring and this does not change throughout the process.
Once the query has been assembled using C#, we apply this query to the SqlDataSource as the Select Command. However, we have recently discovered a very bizarre SQL error that we haven’t seen before:
Errors :
"The variable name '#' has already been declared.
Variable names must be unique within a query batch or stored procedure."
We aren’t declaring any variables in our SQL. As stated above, the only input parameter comes from the Querystring, and we access this parameter using both QueryStringParameters in the ASP:SqlDataSource on the ASP side and “int.Parse(Request.QueryString["id"]).ToString()” on the C# side while constructing the SQL query.
After researching this error, I have yet to find an instance where the variable declaration is empty. Most people are getting errors similar to this when they have declared a variable such as '#email' or '#address' twice. We have no double declarations, and the fact that the variable in the error is not defined is causing a massive headache.
Has anyone seen anything like this before or have any suggestions on how to further debug?
I'll post some code if need be, but we are mostly interested to see if anyone has seen an error like this before.
Code:
string MainQueryStr = ResultsPages.SearchString(SearchVariables(), Request,
ProjectsSqlds, 0, "SELECT DISTINCT dbo.{0}.* FROM dbo.{0}(" + int.Parse(Request.QueryString["id"]).ToString() + ")",
"getXyzById", "AbcId");
StringBuilder SearchQueryStr = new StringBuilder();
SearchQueryStr.Append(MainQueryStr);
SearchQueryStr.Append(" ORDER BY AbcName");
ProjectsSqlds.SelectCommand = SearchQueryStr.ToString();
The search string function is a 500 line method that we can't post right now. It is used all over our solution and works as it should. It stitches together strings to create the query.
This is how the SearchString function appends the parameters:
l.Add(ResultsPages.NewSearchQueryString(ABCFiltersTxBx, SearchQueryStringVariableType.String,
"{1}.AbcID IN (" + ABCFiltersTxBx.Text + ")"));
Where the ABCFiltersTxBx is parsed into a comma separated string.
I should chime in as the supervisor in question here:
OK, so we figured out what was happening.
What we didn't realize was that the SQLDataSource was taking our appended WHERE clauses and using them as SelectParameters. Each parameter we wanted to add to the query that would ultimately feed the SQLDS was then being added as a SelectParameter without us realizing it, and because we hadn't made any explicit parameter declarations, the parameters were added with just "" as the name, leading to the error of "'#' has already been declared".
The most embarrassing part of this whole thing is that our API has already accounted for Parameter Names, but we had unwittingly excluded this part. Thank you all very much for reading and attempting to help. We thoroughly appreciate you taking your time to help us brainstorm our solution over here.
So I suppose the take-home of this whole error is in 2 parts:
Know your API. When you realize that you screwed it up on your own, graciously thank those that took the time to help you here on StackOverflow (or wherever you seek help), as their time is valuable as well.
"'#' is already declared" would indicate that you have parameters being declared without a name, so when debugging, look through the SQLDS you are using and find any parameters that haven't been explicitly named.
Again, thank you to all who read and offered to help. It's greatly appreciated.

What is the best way to get values from a ColdFusion QueryBean with C#

I am having to call a ColdFusion web service which returns a QueryBean. Which returns a set of complex arrays that have the values I am looking for. When I make the call I get all the data in the arrays that I am expecting but now I am trying to get to the data and it keeps telling me that I am missing something or I can't use indexing with an object.
I created a web reference called DAM_Search in VS2010 and I call it with this command;
DAM_Folder.folderService obj_Folder = new DAM_Folder.folderService();
DAM_Folder.QueryBean qBean = bj_Folder.getfolder("1-Key", str_Folder_ID);
What I get back is qBean which contains 4 arrays in it, with the first two arrays are
qBean.columnList[10]
qBean.columnListField[10]
and contain the names of the fields that are used in the data rows. Next it has
qBean.data[4]
qBean.dataField[4]
This is where the data is returned. In the example above the qBean in returning 4 rows of data. The data is in an array with the values of the columns named in the columnList[10].
I figure that since a picture is worth a 1000 words, this might help.
(source: sapp-family.com)
What I am trying to do now is get the data from the internal array of qBean.data[0][0]. In the Immediate Window when I try ? qBean.data[0] it returns the correct array of values.
I have tried the following
? qBean.data[0][0]
"Cannot apply indexing with [] to an expression of type 'object'"
? qBean.data[0].[0]
Identifier expected
? qBean.data[0,0]
Wrong number of indices inside []; expected 1
So, my fellow Stackoverflow users, what do I need to do for getting the values of this object? I figure it's something simple and I am just over thinking it, but it is just driving me up a wall right now.
I would try qBean.data[0][0].toSting()
Ok, So I got side tracked and did not go back and update the original question with a work around. Sorry about that...
My solution to the issue is to cast the qBean.Data[0] as an IEnumerable object. I then run it through a foreach loop which feeds the data into an array that I can pass back to the calling function. For example;
string[] FileData = new string[0];
foreach (var var_Value in (IEnumerable)qBean.data[0])
{
Array.Resize<string>(ref FileData, FileData.Length + 1);
FileData[FileData.Length-1] = var_Value.ToString();
}
Now that I know this works, I am going to pull a count from the other array in the QueryBean and set the FileData[] size before I start the foreach so I don't have to copy the array 21 times with the Array.Resize<>. While at the moment the data I am working with is small, I never know what it's going to be in the future.
Tim

How to add parameter for postgres enum types in C#

Hi currently have the problem, that I want to insert values in a postgres database where the table contains self defined types like.
CREATE TYPE TestEnum AS ENUM ('Value1','Value2');
When I try to add a parameter in C# I always get an error because of the wrong NpgsqlDbType. So my question is what NpgsqlDbType to use for such self defined Types.
var parameter = new NpgsqlParameter(":p1", NpgsqlDbType.????)
{
Value = "Value1",
Direction = ParameterDirection.Input
}
Thanks for your help. I'm really going mad because of this problem.
After all, I found a solution that solves the problem, although it's not the real solution.
I now add a NpgsqlDbType.Varchar parameter and add a CAST(:p1 as "TestEnum") to the SQL
e.g.
INSERT INTO tableName (Col) VALUES ( CAST(:p1 as "TestEnum") )
It works for me, although I do not think that this is a very nice solution due to the cast.
If someone will find a better solution in future, please drop me a line. ;)
According to PostgreSQL 8.4.4 Documentation: 8.7. Enumerated Types:
An enum value occupies four bytes on disk.
That suggests that they are internally stored as a 32-bit integer. It uses the system catalog pg_enum to map from integers to the names and back.
Unfortunately, the documentation for NpgsqlDbType does not elucidate the meaning of each of those enum values, but my guess would be that NpgsqlDbType.Integer is likely to refer to a 32-bit integer.
However, I must confess that I am guessing here. It is also possible that NpgsqlParameter expects a type that represents the data you send to the DB with the query, which is clearly a string, so if NpgsqlDbType.Integer doesn’t work, my next guess would be NpgsqlDbType.Varchar.

Using a ref cursor as input type with ODP.NET

I'm trying to use a RefCursor as an input parameter on an Oracle stored procedure. The idea is to select a group of records, feed them into the stored procedure and then the SP loops over the input RefCursor, doing some operations to its records. No, I can't select the records inside the SP and thus avoid having to use the RefCursor as an input type.
I've found an example on how to do this on (this here would be the link, but it seems I cannot use them yet) Oracle's documentation, but it uses a simple SELECT to populate the input RefCursor; and therein lies the rub: I've got to populate it from code.
You see, in code I have this:
[OracleDataParameter("P_INPUT", OracleDbType.RefCursor, ParameterDirection.Input)]
private List<MiObject> cursor;
And, I've tried populating cursor with a List<T>, a DataTable, even an plain array of MyObject, and nothing works. When I try running my tests I get an error:
"Invalid Parameter Linking"
Maybe not the exact wording, as I'm translating from Spanish, but that's the message
Any ideas?
I'm also in contact with Mark Williams, the author of the article I've tried to link on my post, and he has kinly responded like this:
"
It is no problem to send me email; however, I think I will disappoint you with my answer on this one.
Unfortunately you can't do what you are trying to do (create a refcursor from the client like that).
A couple of problems with that are that a refcursor refers to memory owned by Oracle on the server and Oracle has no concept of client items like a DataTable or a .NET List, etc.
Do you have any other options available other than using a refcursor?
"
So basically I'm screwed, and this question is closed. Thanks for reading and/or trying to help, you all.
From memory, isn't there an OracleCursor class somewhere in the ODP.NET library that works?
Look at this sample for refcursor as input to pl/sql from oracle technet.
The clou is that the input refcursor object must be created by oracle themself. You cannot convert a list or anything else to refcursor.

Categories