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();
}
}
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"]);
I want to create code where if for example the dropdown list is = to linemen then his monthly salary is = 6000 and I want this to be put into monthly salary column in my database.
Here is the code - with this code I get error in monthlysalary parameters saying
use of unassigned local variable total
Code:
float total;
if (Designation.SelectedValue == "Linemen")
{
total = 4000;
}
if (Designation.SelectedValue == "Manager")
{
total = 6000;
}
if (Designation.SelectedValue == "Boss")
{
total = 8000;
}
string emp = datapayemp.SelectedRow.Cells[1].Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ConnectionString);
string command = "INSERT INTO PAYROLL(RegEmpID, MonthlySalary) VALUES (#RegEmpID, #MonthlySalary)";
SqlCommand cmd = new SqlCommand(command, con);
cmd.Parameters.AddWithValue("#RegEmpID", emp);
cmd.Parameters.AddWithValue("#MonthlySalary",total);
try
{
con.Open();
cmd.ExecuteNonQuery();
}
finally
{
con.Close();
}
Well, the problem is: you're not initializing total to any value - and if the Designation.SelectedValue is neither Linemen, Manager nor Boss, then there's never any value assigned to total.
You need to give that total an initial value, just in case none of the if clauses match:
float total = 0.0;
Also: float is notorious for rounding errors etc. - so if you're dealing with money values, I would strongly recommend to use the decimal datatype instead. Same goes for the SQL Server database table: don't use FLOAT or REAL - use DECIMAL(p,s) instead
public int AuthenticatedUserAge(String User_name)
{
string sql = "SELECT UserName,Age FROM tblDataProg WHERE (UserName ='" + User_name + "')";
ds = GetDataSet(sql);
int help = int.Parse(ds.Tables[0].Rows[0]["Age"].ToString());
return help;
}
I can't figure why this line doesn't convert the age to type int and return a value:
int help = int.Parse(ds.Tables[0].Rows[0]["Age"].ToString());
Completely offtopic to the question, but I think it's worth mentioning. Please don't create your SQL statements by concatenating strings. This creates SQL Injection attack possibility. Instead consider SqlParameter class and compose your WHERE predicates using such parameters.
Here you get nice example (look especially at convenient AddWithValue method).
Thanks!
Test your assumptions more. You are assuming GetDataSet is returning a row but it possibly isn't: -
int help = 0;
if (ds.Tables[0].Rows.Count == 0)
{
throw new ApplicationException("no rows were returned, here is an error to deal with");
}
else if (ds.Tables[0].Rows[0]["Age"] == System.DbNull.Value)
{
throw new ApplicationException("a row was found but Age is null, here is an error to deal with");
}
else
{
help = int.Parse(ds.Tables[0].Rows[0]["Age"].ToString());
}
try
int help;
int.TryParse(Convert.ToString(ds.Tables[0].Rows[0]["Age"]),out help);
and see the code in debug mode
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"]);
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.