SqlDataReader Column Ordinals - asp.net

Suppose I am calling a query "SELECT name, city, country FROM People". Once I execute my SqlDataReader do columns come in the same order as in my sql query?
In other words can I rely that the following code will always work correctly:
SqlConnection connection = new SqlConnection(MyConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "SELECT [name], [city], [country] WHERE [id] = #id";
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader(System.Data.CommandBehavior.SingleRow);
if (reader.Read())
{
// Read values.
name = reader[0].ToString();
city = reader[1].ToString();
country = reader[2].ToString();
}
}
catch (Exception)
{
throw;
}
finally
{
connection.Close();
}
Also how much performance do I lose if I use column names instead of ordinals (reader["name"])?
Are there any official microsoft documents describing the behavior of column ordering in SqlDataReader?

Yes they do but you can also use SqlDataReader.GetName(ordinal) and SqlDataReader.GetOrdinal(name).
As for performance, I think it's probably extremely insignificant compared to the overhead of say, retrieving the next row of data.

I totally agree with Josh - the positions of the fields are indeed such as you specify them in your SQL query text.
BUT: I would still prefer to use the column names, since it's more robust. E.g. what if you need to add a field to your SQL query?
command.CommandText = "SELECT [name], [jobtitle], [city], [country] WHERE [id] = #id";
Now suddenly you have to rewrite all your code to change the positions....
What I normally do outside the loop that enumerates through all the rows returned by the data reader is determine the positions of each field I'm interested in:
int namePosition = reader.GetOrdinal("name");
int cityPosition = reader.GetOrdinal("city");
and then I use these positions inside my loop handling the data to get quick access to the individual fields. That way you determine the positions only once, but you're using positions in your looping over the data - the best of both worlds! :-)
Marc

This example is the most maintainable and easiest to read:
int? quantity = reader.Get<int?>("Quantity");
Guid token = reader.Get<Guid>("Token");
It relies on the following extension method I created. It performs DB null checks, provides an informative error message when field is not found, and does not break when columns are re-aligned.
internal static T Get<T>(this SqlDataReader reader, string fieldName)
{
int ordinal;
try
{
ordinal = reader.GetOrdinal(fieldName);
}
catch (IndexOutOfRangeException)
{
throw new IndexOutOfRangeException(string.Format("Field name '{0}' not found.", fieldName));
}
return !reader.IsDBNull(ordinal) ? (T)reader.GetValue(ordinal) : default(T);
}

Related

Convert date in SQLite?

I created an scheduler application with SQL server and now i want to make another one using SQLite. I have a convert query in SQL and it does not work in SQLite. Can anyone help?
try
{
ObservableCollection<Classes.EventClass> listEvents = new ObservableCollection<EventClass>();
SQLiteConnection conn = new SQLiteConnection(#"Data Source=Scheduler.db;Version=3;");
string query= "Select * from Sche_Event where CONVERT(DATE,Event_TimeFrom) = CONVERT(DATE,'" +d.ToString("yyyy-MM-dd HH:mm:ss") + "') ORDER BY Event_TimeFrom ASC";
SQLiteCommand command= new SQLiteCommand(query, conn);
conn.Open();
SQLiteDataReader dr = command.ExecuteReader();
while (dr.Read())
{
EventClass dog = new EventClass();
dog.DogID = dr.GetInt32(0);
dog.DogName = dr.GetString(1);
dog.DogText = dr.GetString(2);
dog.DogPriority = dr.GetInt32(3);
dog.DogTimeFrom = dr.GetDateTime(4);
dog.DogTimeTo = dr.GetDateTime(5);
dog.KliID = dr.GetInt32(6);
listEvents .Add(dog);
}
return listEvents ;
}
catch (Exception)
{
return null;
}
I expect that my code goes to While() and read the information about the Event but all it does it goes to Catch() and returns nothing.
The query in SQL works just fine but i dont not work with SQLite :(
Of course the statement doesn't work in SQLite, because convert() is not a known function there. But if you're lucky you don't even need it, depending on the format in which the timestamp is stored in your SQLite table. As you didn't provide any sample data nor described what you actually want to do, you could either read the SQLite doc about date and time functions or rephrase your question to "How do I do X in SQLite?".

Cannot execute mysql store procedure with out parameter in asp.net

I have this store procedure with out parameter
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `usp_count_rows`(OUT total int)
BEGIN
SELECT COUNT(*)
FROM address_book.persons;
END
I want to use it in asp.net page. I write this code behind:
string commandText = "usp_count_rows";
MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["mySqlString"].ConnectionString);
MySqlCommand cmd = null;
try
{
cmd = new MySqlCommand(commandText, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("total", MySqlDbType.Int32);
cmd.Parameters["total"].Direction = ParameterDirection.Output;
conn.Open();
cmd.ExecuteNonQuery();
int total = (int)cmd.Parameters["?total"].Value;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Clone();
}
and i got this error message
Specified cast is not valid.
fot the line
int total = (int)cmd.Parameters["?total"].Value;
What should I do to make the code work. And another thing I want ot use the result in aspx page. Something like this: Total number of rows: (result from store procedure). Do you have some suggestions?
This is happening because your SP doesn't return any parameters, just result of the query. And for a stored procedure like this you do not need any parameters - even output ones, so redefine your SP simple as
CREATE DEFINER=`root`#`localhost` PROCEDURE `usp_count_rows`
BEGIN
SELECT COUNT(*)
FROM address_book.persons;
END
Then in you C# get rid of lines (remove them completely):
cmd.Parameters.Add("total", MySqlDbType.Int32);
cmd.Parameters["total"].Direction = ParameterDirection.Output;
and replace these lines:
cmd.ExecuteNonQuery();
int total = (int)cmd.Parameters["?total"].Value;
with this one line:
int total = Convert.ToInt32(cmd.ExecuteScalar());
ExecuteScalar method executes your SP/Query and returns first column of first row of that query (in your case it will be the only column and the only row with the Count(*)).
Oh by the way in your Finally block it should be conn.Close() not conn.Clone(), but I think it's simple a type.
As for displaying results on the ASPX page - there're multiple ways depending on where and how you want to display it. For example you can add a Label control to your page and execute something like:
Label1.Text = "Total number of rows: " + total.ToString();

What is wrong with the following query?

I have a table containing name, surname and email. I want to retrieve them from the table and so i write:
if (LoginAs.SelectedValue == "Administrator")
{
string result;
string query = "Select * from AdminTable where ID='"+ idBox.Text +"'";
cmd1 = new SqlCommand(query, con);
result = Convert.ToString(cmd1.ExecuteScalar());
Response.Redirect("Admin.aspx");
//Admin user = new Admin(idBox.Text, "Active", mail, firstName, LastName, passwordBox.Text);
}
The problem is, it only returns the name field of the specified row even though i wrote "Select *". What is wrong here?
ExecuteScalar returns just the first column of the first row, and ignores the rest.
So you should use ExecuteReader method. An example from MSDN:
using (SqlConnection connection = new SqlConnection(
connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0]));
}
}
Note that the while (reader.Read()) checks whether your query returned (more) results and positions the cursor on the next record, that you can then read. This example prints the first column's value.
The using statement makes sure the connection is closed after use, whatever happens.
Also, don't build your query directly with input from the user (such as the value of a TextBox), use parameters instead to prevent SQL injection attacks.
You must try ExecuteReader() instead of using ExecuteScalar()
ExecuteScaler is used in situation where we have to read a single value.eg:
select count(*) from tablename.
while
ExecuteReader is used for any result set with multiple rows/columns
(e.g., SELECT * from TableName)
Sample code:
string myQuery="Select * from AdminTable where ID=#myid";
SqlCommand cmd=new SqlCommand(myQuery,conn);
cmd.Parameters.AddWithValue("#myid", value);
conn.Open();
SqlDataReader dreader;
dreader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (dreader.Read())
{
string Value1= dreader["COl1"].ToString();
string Value2= dreader["COl2"].ToString();
}
dreader.Close();
Always use parameterized Query
You may try cmd1.ExecuteReader() instead.

Compare value of a string to Database value

I have to compare a value in a string array to that of a particular column in a database. How do i do this ?
public void setvisibility(string user_ID)
{
SqlDataReader reader = null;
SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ctd_prrity_dbConnectionSting"].ConnectionString);
connection.Open();\
SqlCommand cmd = new SqlCommand("Select * from Admins );
I need to compare the value of user_ID to the only column in the Admins table !
Here's how you can do it:
using( SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ctd_prrity_dbConnectionSting"].ConnectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand("Select 1 from Admins where User_ID=#userid",connection );
cmd.Parameters.AddWithValue("#userid",user_ID);
SqlDataReader reader= cmd.ExecuteReader();
if(reader.HasRows)
{
//user id found
}
}
This method uses a parametrized queries, which are safer than the option given in the answer by Tony since his is prone to SQL Injection attacks.
BTW: you mention "string array" in your question, yet your code only shows a single string as parameter. What did you mean by that?
sqlcommand("SELECT * FROM Admins WHERE column = " & user_ID );
That should work. What that does is it returns the value in the column if it is the same as the user_ID. Basically, if your query returns a value you have a match, if not then you don't.

System.Data.SqlClient.SqlException: Invalid column name

Trying to do a recordset, I just want one column of data, but this code is giving me an error.. I'm an ASP.NET newb, can anyone help?:
System.Data.SqlClient.SqlException: Invalid column name
'CustomerName'.
using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
{
con.Open();
using (IDataReader dr = DB.GetRS("select CustomerName from Customer where CustomerID=" + Customer.CustomerID, con))
{
string CustomerName = "CustomerName";
}
}
String EncCustomerName = Encrypt(CustomerName.Replace(".", "").Replace("-", ""),"1");
Question #2: How do I bind the database content to the CustomerName string? It seems like its only returning "CustomerName" as the value for CustomerName string.. I would like it to return the database data for CustomerName string.. Help?
Suggested to use a ExecuteScalar, so i modified the request to this
using (var con = new SqlConnection(DB.GetDBConn()))
using (var cmdContrib = new SqlCommand("SELECT CustomerName FROM Customer WHERE CustomerID=" + ThisCustomer.CustomerID, con))
{
con.Open();
string CustomerName = cmdContrib.ExecuteScalar();
}
And i Get this error:
"string CustomerName = cmdCust.ExecuteScalar();"
CS0266: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?)
To answer your second question:
// Set it here so you can access it outside the scope of the using statement
string CustomerName = "";
using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
{
con.Open();
using (IDataReader dr = DB.GetRS("select CustomerName from Customer where CustomerID=" + Customer.CustomerID, con))
{
while (dr.Read())
CustomerName = dr["CustomerName"].ToString();
}
}
}
If you're sure you'll only get one CustomerName result, using a DataReader is a bit of an overkill.
SqlCommand.ExecuteScalar Example
string CustomerName = "";
using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
{
SqlCommand cmd = new SqlCommand("SELECT CustomerName FROM Customer WHERE CustomerID = " + Customer.CustomerID, con);
cmd.CommandType = CommandType.Text;
con.Open();
CustomerName = Convert.ToString(cmd.ExecuteScalar());
}
SqlCommand.ExecuteScalar Method
Additional Info
ExecuteScalar returns an object, so you'll need to convert the returned value to the proper type (in this case, string).
Also, you should declare your CustomerName value outside of the using blocks (as I did in my example) - otherwise it will be scoped to the using blocks and not available outside of them.
It means that either CustomerName or CustomerID is not a valid column within your database. Check your table again.
Make sure you are trying to connect correct database.
See CustomerName column should be in Customer table. check spelling also
First, debug and check the value of:
DB.GetDBConn()
You will verify that you are going to the same in Studio as you are in the program.
I think it is the spelling somewhere between the db and your code.
Once you get past the error, you need to fix this:
{
string CustomerName = "CustomerName";
}
You are not accessing the reader, try some kind of tutorial for that stuff.
Try doing a select * from customer where ... and put a breakpoint on your using datareader statement. Then use quick-watch on the datareader object to investigate the columns exposed in the recordset.
Or you could run the select statement on your db of choice to ensure that the column name is the same.
I agree with Madhur above, your column name is not spelled correctly. Or you are not connecting to the correct db.
Hope this helps

Resources