I have the following code (query abbreviated):
string q_sel = #"SELECT c.editedBy, c.*
FROM wf.chan c
WHERE date(editedTime) >= current_date - ? AND editedBy = '?') c2
ORDER BY editedTime";
if (myConnection.State != ConnectionState.Open)
OpenDb();
myCommand = new OdbcCommand(q_sel, myConnection);
myCommand.Parameters.AddWithValue("#0", Request.QueryString["days"]);
myCommand.Parameters.AddWithValue("#1", Request.QueryString["user"]);
OdbcDataReader myReader = myCommand.ExecuteReader();
The query works if I manually replace the ? with const values, but with Parameters.AddWithValue it does not, any idea why?
The AddWithValue assumes (sometime making errors) the datatype of the parameter from the value passed as its second argument. So your line
myCommand.Parameters.AddWithValue("#0", Request.QueryString["days"]);
pass a string for the first parameter, not a number as it seems you are expecting.
I will try to change that line in
myCommand.Parameters.AddWithValue("#0", Convert.ToInt32(Request.QueryString["days"]));
Consider also to use a specific Parameter created by your code where you can set the DataType and the Size
OdbcParameter p = new OdbcParameter("#0", OdbcType.Int)
p.Value = Convert.ToInt32(Request.QueryString["days"]))
myCommand.Parameters.Add(p);
or even better a one-liner like
myCommand.Parameters.Add("#0", OdbcType.Int).Value = Convert.ToInt32(Request.QueryString["days"]);
Related
I was just wondering if it's possible to return a single row using Npgsql in a .Net Core Script.
I've been doing with the Read Method like bellow
NpgsqlCommand command = new NpgsqlCommand (
" select col01, col02, col03 from table ",
dbconnection
);
var result = command.ExecuteReader();
while(result.Read()) {
var varCol01 = result["col01"];
var varCol02 = result["col02"];
}
Which seems a bit excessive for a single row because I would have to exit the while manually.
Each time you call NpgsqlDataReader.Read, you're reading an additional row - so your code sample doesn't seem to be a good fit for a single row scenario...
If you know you're only getting a single row, why not do something along the lines of:
var reader = command.ExecuteReader();
reader.Read(); // You can do a Debug.Assert to make sure the result of this is true
var (col1, col2) = (result["col01"], result["col02"]);
am new to all of this, but a fast learning curve is underway.
I have been searching round, but cannot piece together what I need.
I am using Lumenworks CsvReader to reader the data from a csv file - so far so good, and I am seeing data. Next I need to pass this data into SQLite.
Where I am stuck is trying to pass that information into my INSERT statement in a loop, so hoping someone here can help me?
I know the error lies in my loop, (and I know the format may be wrong), but I cannot figure this out. Thankyou for any help in advance.
here is my code so far:
command.CommandText = #"CREATE TABLE [Test] ([Code] VARCHAR(50) PRIMARY KEY NOT NULL , [Description] VARCHAR(100),[RRP] NUMERIC DEFAULT (null) ,[Points] NUMERIC, [Buy] NUMERIC DEFAULT (null) )";
command.ExecuteNonQuery();
string insertText = "INSERT INTO [Test] ([Code],[Description],[RRP],[Points],[Buy]) VALUES(#Code,#Description,#RRP,#Points,#Buy)";
SQLiteTransaction trans = conn.BeginTransaction();
command.Transaction = trans;
command.CommandText = insertText;
using (CsvReader csv = new CsvReader(new StreamReader(#"C:\Data.csv"), true))
{
int fieldCount = csv.FieldCount;
string[] headers = csv.GetFieldHeaders();
while (csv.ReadNextRecord())
{
for (int i = 0; i < fieldCount; i++)
command.Parameters.AddWithValue("#Code", csv[i]);
command.Parameters.AddWithValue("#Description", csv[i]);
command.Parameters.AddWithValue("#RRP", csv[i]);
command.Parameters.AddWithValue("#Points", csv[i]);
command.Parameters.AddWithValue("#Buy", csv[i]);
command.ExecuteNonQuery();
}
}
Im writing SSAS MDX queries involving more than 2 axis' to retrieve a value. Using ADOMD.NET, I can get the returned cellset and determine the value by using
lblTotalGrossSales.Text = CellSet.Cells(0).Value
Is there a way I can get the CellSet's Cell(0) Value in my MDX query, instead of relying on the data returning to ADOMD.NET?
thanks!
Edit 1: - Based on Daryl's comment, here's some elaboration on what Im doing. My current query is using several axis', which is:
SELECT {[Term Date].[Date Calcs].[MTD]} ON 0,
{[Sale Date].[YQMD].[DAY].&[20121115]} ON 1,
{[Customer].[ID].[All].[A612Q4-35]} ON 2,
{[Measures].[Loss]} ON 3
FROM OUR_CUBE
If I run that query in Management Studio, I am told Results cannot be displayed for cellsets with more than two axes - which makes sense since.. you know.. there's more than 2 axes. However, if I use ADOMD.NET to run this query in-line, and read the returning value into an ADOMD.NET cellset, I can check the value at cell "0", giving me my value... which as I understand it (im a total noob at cubes) is the value sitting where all these values intersect.
So to answer your question Daryl, what I'd love to have is the ability to have the value here returned to me, not have to read in a cell set into the calling application. Why you may ask? Well.. ultimately I'd love to have one query that performs several multi-axis queries to return the values. Again.. Im VERY new to cubes and MDX, so it's possible Im going at this all wrong (Im a .NET developer by trade).
Simplify your query to return two axis;
SELECT {[Measures].[Loss]} ON 0, {[Term Date].[Date Calcs].[MTD] * [Sale Date].[YQMD].[DAY].&[20121115] * [Customer].[ID].[All].[A612Q4-35]} ON 1 FROM OUR_CUBE
and then try the following to access the cellset;
string connectionString = "Data Source=localhost;Catalog=AdventureWorksDW2012";
//Create a new string builder to store the results
System.Text.StringBuilder result = new System.Text.StringBuilder();
AdomdConnection conn = new AdomdConnection(connectionString);
//Connect to the local serverusing (AdomdConnection conn = new AdomdConnection("Data Source=localhost;"))
{
conn.Open();
//Create a command, using this connection
AdomdCommand cmd = conn.CreateCommand();
cmd.CommandText = #"SELECT { [Measures].[Unit Price] } ON COLUMNS , {[Product].[Color].[Color].MEMBERS-[Product].[Color].[]} * [Product].[Model Name].[Model Name]ON ROWS FROM [Adventure Works] ;";
//Execute the query, returning a cellset
CellSet cs = cmd.ExecuteCellSet();
//Output the column captions from the first axis//Note that this procedure assumes a single member exists per column.
result.Append("\t\t\t");
TupleCollection tuplesOnColumns = cs.Axes[0].Set.Tuples;
foreach (Microsoft.AnalysisServices.AdomdClient.Tuple column in tuplesOnColumns)
{
result.Append(column.Members[0].Caption + "\t");
}
result.AppendLine();
//Output the row captions from the second axis and cell data//Note that this procedure assumes a two-dimensional cellset
TupleCollection tuplesOnRows = cs.Axes[1].Set.Tuples;
for (int row = 0; row < tuplesOnRows.Count; row++)
{
for (int members = 0; members < tuplesOnRows[row].Members.Count; members++ )
{
result.Append(tuplesOnRows[row].Members[members].Caption + "\t");
}
for (int col = 0; col < tuplesOnColumns.Count; col++)
{
result.Append(cs.Cells[col, row].FormattedValue + "\t");
}
result.AppendLine();
}
conn.Close();
TextBox1.Text = result.ToString();
} // using connection
Source : Retrieving Data Using the CellSet
This is fine upto select on columns and on Rows. It will be helpful analyze how to traverse sub select queries from main query.
I have a oracle stored procedure which will return a value. I need to get the OUTPUT value in my C# program. I need to know how we can get the OUTPUT parameter using the OracleCommands AddWithValue method.
The way i have written now is:
OracleCommand Ocmd = new OracleCommand(_StoredProcedure, OraCon);
Ocmd.CommandType = CommandType.StoredProcedure;
Ocmd.Parameters.AddWithValue("Filed1", "Value1");
Ocmd.Parameters.AddWithValue("OUTPUTParam","").Direction = ParameterDirection.Output;
OraCon.Open();
int RecivedDetID = Ocmd.ExecuteNonQuery();
OraCon.Close();
return Ocmd.Parameters[_OutParam].Value.ToString();
I know the OUTPUTPARAm how i have called is wrong. How can i achieve it using the
AddWithValue method of the OracleCommand. I dont want to use the OracleCommands Add method where we need to specify the Type also.
Make sure you set the SIZE property on the parameter before executing. With output parameters in Oracle, the specified size acts as a buffer. If the buffer isn't set, it is 0 so you don't get the value from the database.
var param = Ocmd.Parameters.AddWithValue("OUTPUTParam","").Direction = ParameterDirection.Output;
param.Size = 255;
The rest is good!
This feels like a completely basic question, but, for the life of me, I can't seem to work out an elegant solution.
Basically, I am doing a LINQ query creating a new object from the query. In the new object, I want to generate a auto-incremented number to allow me to keep a selection order for later use (named Iter in my example).
Here is my current solution that does what I need:
Dim query2 = From x As DictionaryEntry In MasterCalendarInstance _
Order By x.Key _
Select New With {.CalendarId = x.Key, .Iter = 0}
For i = 0 To query2.Count - 1
query2(i).Iter = i
Next
Is there a way to do this within the context of the LINQ query (so that I don't have to loop the collection after the query)?
Pardon me for doing this in C# not sure exactly the syntax in VB.NET:
MasterCalendarInstance
.OrderBy(x => x.Key)
.Select((x, ixc) => new { CalendarId = x.Key, Iter = ixc });
I don't know if this is possible in VB, but in C# one uses a closure:
int count = 0
var res = from x in MasterCalendarInstance
order by x.Key
select new {
CalendarId = x.Key,
Iter = count++
};
The above solutions could be summed up in VB.NET like this :
MasterCalendarInstance _
.OrderBy(Function (x) x.Key) _
.Select(Function (x, ixc) New With { .CalendarId = x.Key,
.Iter = ixc })
I ran into this post while trying to solve a similar problem with a List(of String).
I'm posting my workaround in hopes that it may be adopted to resolve your issue, but more for anyone else who runs into this issue with a List(Of T).
Dim list As New List(Of String)
list.Add("Test1")
list.Add("Test2")
list.Add("Test3")
Dim var = list.Select(Function(s) New With {.Name = s, .RecordID = list.IndexOf(s)})
Hope this helps!