how to get exact record using datareader - query-string

Can you please correct this code so that i can get particular companyName corresponding to the seekerID when i select the particular seekerID ... Pls its urgent.
while (reader.Read())
{
if (lblseekerID.Text != Request.QueryString["seekerID"])
{
//if it is a text box
txtAdminCompany.Text = "wrong";
}
else
{
//txtAdminCompany.Text = reader.["companyName"].ToString();
txtAdminCompany.Text=reader.IsDBNull(reader.GetOrdinal("companyName"))? null: reader["companyName"].ToString();
}
}

Just use
reader["companyName"]
instead.
Also, without seeing the db query that precedes your code, I suspect your SQL query may be the root of the problem. You should be doing something like:
cmd.CommandText = "SELECT * FROM myTable WHERE seekerID = " + seekID.ToString(); // cmd = SqlCommand object
Hope this helps.

Related

Can SQLite return the id when inserting data?

I'm using sqlite3.exe to execute queries against my DB, using the following code.
public static string QueryDB(string query)
{
string output = System.String.Empty;
string error = System.String.Empty;
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = "C:\\sqlite\\sqlite3.exe";
startInfo.Arguments = "test.db " + query;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardOutput = true;
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
try
{
using(System.Diagnostics.Process sqlite3 = System.Diagnostics.Process.Start(startInfo))
{
output = sqlite3.StandardOutput.ReadToEnd();
error = sqlite3.StandardError.ReadToEnd();
sqlite3.WaitForExit();
}
}
catch (System.Exception ex)
{
System.Console.WriteLine(ex.ToString());
return null;
}
return output;
}
I'm inserting data into a table, and I'd like it to return the id of the inserted data. Is there a way to get SQLite to do this?
For example, my query might look like this "INSERT INTO mytable (some_values) VALUES ('some value');". After this query is run, I'd like output to contain the rowid of the inserted data. Is there any way to do this (a command line switch, etc.)?
A possible workaround, is to run two commands against the DB. First insert the data, then get the last inserted row id. In which case, the query would look like this "\"INSERT INTO mytable (some_values) VALUES ('some value'); SELECT last_insert_rowid();\""
You should not use max(id) or similar function in DB.
In this specific case it can work, under the condition that you use ONE connection and ONE thread to write data to DB.
In case of multiple connections you can get wrong answer.
From version SQLite 3.35.0 it supports returning close in the insert statement (SQLite Returning Close)
create table test (
id integer not null primary key autoincrement,
val text
);
insert into table test(val) values (val) returning id;
Would you consider this:
select max(id) from your_table_name;
or embedded function last_insert_rowid()?

Firebird insert...returning asp.net

I'm using Firebird 2.5 and asp.net (4.5).
I'm trying to find out how to use insert ... returning, or some equivalent.
Using fbDataReader, it executes the insert OK, but I can't find anyway of accessing a returned value. Using fbDataReader.GetName(0) seems to work ok, returning the variable name in the "returning" clause. This even applies to a max() in a subselect:
..... returning (select max(userid) as newid from users)
returns the text "newid".
I can't find where, or whether, the value is available.
Using a fbDataAdaptor to fill a DataTable, the insert works OK, but data table seems empty.
Does anyone know whether this is possible, and if so, how it's done?
Thanks
EDIT
Code supplied :
strConn = ....
dbConn = New FirebirdSql.Data.FirebirdClient.FbConnection(strConn)
dbConn.Open()
MySQL = "insert into users (Firstname, Lastname) VALUES (#fname,#lname) returning userid"
FbC = New FirebirdSql.Data.FirebirdClient.FbCommand(MySQL, dbConn)
FbC.Parameters.Add("fname", FirebirdSql.Data.FirebirdClient.FbDbType.Text).Value = "Pete"
FbC.Parameters.Add("lname", FirebirdSql.Data.FirebirdClient.FbDbType.Text).Value = "Davis"
FbDataReader = FbC.ExecuteReader()
FbDataReader.Read()
TextBox1.Text = FbDataReader.GetName(0)
'TextBox1.Text = str(FbDataReader.GetInt64())
'TextBox1.Text = FbDataReader.GetString(0)
TextBox1.Text = FbDataReader.GetValue(0)
According to this thread INSERT ... RETURNING ... behaves like output parameters for the Firebird .NET provider. So you will need to add an output parameter.
So something like the code below should work:
FbParameter outParam = new FbParam("userid", FbDbType.Integer)
{
Direction = ParameterDirection.Output
};
FbC.Parameters.Add(outParam);
FbC.ExecuteNonQuery();
int? userId = outParam.Value as int?;

DropDownList value into Linq query where clause

I am facing following problem. I want a search field with a DropDowList next to it, where user can pick an item for which he wants to search. I have to make it with this LINQ code not just a SQL query.
Here's my code:
var Metadata = from m in db.Metadatas
join mm in db.Multimedias
on m.multimediaID equals mm.multimediaID
where (m. { Here would i have the selected value from the dropdownlist. } .ToString().Contains(textboxvalue) ||
mm. { Here would i have the selected value from the dropdownlist. } .ToString().Contains(textboxvalue))
&& mm.filetype.ToString().Contains(radiobuttonvalue)
I want to put something like: "Dropdownlist.selectedvalue" into the area { Here would i have the selected value from the dropdownlist. }
I hope you guys understand my idea and problem.
I am not sure why you are doing join on in your linq statement. That is not necessary if you Linq already knows about the relationship between the objects because there is a foreign key relationship setup in the database.
What you can do is this:
var Metedata = db.Metadatas;
switch(Dropdownlist.selectedvalue)
{
case "one":
Metadata = Metadata.Where(m => m.{selected value field}.Contains(textboxvalue));
break;
case "two":
Metadata = Metadata.Where(m => m.{selected value field}.Contains(textboxvalue));
break;
//More use cases
}
I am not sure what you will be selecting out of the list when you are done, but if it involves related objects (e.g. Multimedias) then you might want to look into DataLoadOptions (LinqToSQL) or .Include() (EntityFrameworks).
Just change your sql query:
if(supportgrp.SelectedItem.Text == "All")
sql ="SELECT * FROM QlyData where Date >='" + txtstartdate.Text + "' and Date<='" + txtenddate.Text + "'";
else
sql ="SELECT * FROM QlyData where Date >='" + txtstartdate.Text + "' and Date<='" + txtenddate.Text + "' and suppgrp = '" + supportgrp.Text + "'";

Convert Linq to SQL

I have researched on the net and most result are converting from sql to linq and seldom have linq to sql.
this is the code which I want to convert to SQL :
using (CommerceEntities db = new CommerceEntities())
{
try
{
var query = (from ProductOrders in db.OrderDetails
join SelectedProducts in db.Products on ProductOrders.ProductID
equals SelectedProducts.ProductID
group ProductOrders by new
{
ProductId = SelectedProducts.ProductID,
ModelName = SelectedProducts.ModelName
} into grp
select new
{
ModelName = grp.Key.ModelName,
ProductId = grp.Key.ProductId,
Quantity = grp.Sum(o => o.Quantity)
} into orderdgrp where orderdgrp.Quantity > 0
orderby orderdgrp.Quantity descending select orderdgrp).Take(5);
RepeaterItemsList.DataSource = query;
RepeaterItemsList.DataBind();
}
catch (Exception exp)
{
throw new Exception("ERROR: Unable to Load Popular Items - " +
exp.Message.ToString(), exp);
}
}
You can attempt to run the LINQ statement in LinqPad. For examples on how to use LinqPad, check the answer here.
It has a tab to show the generated SQL statement.
Here's an article on logging in LINQ to SQL. It lets you specify a TextWriter to which to send the query.
Basically, you can write something like this:
db.Log = new System.IO.StreamWriter("linq-to-sql.log") { AutoFlush = true };
... where db is your data context.
In SQL you'd write something like this (although the produced code will look a lot different, since it is auto-generated):
SELECT TOP 5 Products.ModelName, Products.ProductID, SUM(OrderDetails.Quantity) qty
FROM OrderDetails
INNER JOIN Products ON OrderDetails.ProductID = Products.ProductID
GROUP BY Products.ProductID, Products.ModelName
HAVING qty > 0
ORDER BY qty DESC

Strange result with

When i run this as my first commend i get an exception an error near "last_insert_rowid". This is referring to the last last_insert_rowid();. If i set the curser to the line command.CommandText = and run it again it is fine.
What gives? The last_insert_rowid seems to be working properly why doesnt the last_insert_rowid after the 2nd insert work.
I tried moving last_insert_rowid() to after the execute and i still get an error. What gives?
using (var trans = connection.BeginTransaction())
{
command.CommandText =
"INSERT INTO link_list(link, status, hash_type, hash_id) " +
"VALUES(#link, #status, #hash_type, #hash_id);" +
"INSERT INTO active_dl(linkId, orderNo) " +
"VALUES(last_insert_rowid(), (SELECT COUNT(*) FROM active_dl)); last_insert_rowid();";
command.Parameters.Add("#link", System.Data.DbType.String).Value = link;
command.Parameters.Add("#status", System.Data.DbType.Int32).Value = SiteBase.Status.none;
command.Parameters.Add("#hash_type", System.Data.DbType.Int32).Value = 0;
command.Parameters.Add("#hash_id", System.Data.DbType.Int32).Value = 0;
int rowid = command.ExecuteNonQuery();
trans.Commit();
}
Why is the last last_insert_rowid() there? After the second insert you call last_insert_rowid with no select or anything to identify what you want to do with it.
You would have to put a select in front of it to retrieve the value wouldn't you?
You're trying to execute 2 sql commands in the one statement. You'll need to split the 2 statements up into 2 calls and return the inserted id from the first statement.
An alternative suggestion is a stored procedure but I don't think sqlite supports these.

Resources