Missing Rows Property in SqlDataReader [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
public bool ValidateUser(string uName)
{
SqlCommand cmd = new SqlCommand();
if (connection == null)
{
connection = connectToDB();
}
cmd.Connection = connection;
cmd.CommandText = "Select * from Users where UserName='" + uName + "'";
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.Rows.Count > 0)
{
return true;
}
else
{
return false;
}
I wrote the code in my data access layer but it was giving error on rows to count the columns.
Error:
'System.Data.SqlClient.SqlDataReader' does not contain a definition for 'Rows' and no extension method 'Rows' accepting a first argument of type 'System.Data.SqlClient.SqlDataReader' could be found (are you missing a using directive or an assembly reference?)

Use HasRows instead because SqlDataReader doesn't have a property call Rows.
if (dr.HasRows)
{
return true;
}
However, if you want the count instead you may load it into a datatable
DataTable dt = new DataTable();
dt.Load(dr);
int num = dt.Rows.Count;

SqlDataReader does not have a Rows Property.
Perhaps consider the HasRows property of SqlDataReader
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.hasrows.aspx

There is no Rows property in an SqlDataReader.
But your code has many problems.
I would change your code in this way:
public bool ValidateUser(string uName)
{
using(SqlConnection cn = connectToDB())
using(SqlCommand cmd = new SqlCommand("Select count(*) from Users where UserName=#name", cn))
{
cmd.Parameters.AddWithValue("#name", uName);
return (Convert.ToInt32(cmd.ExecuteScalar()) > 0)
}
}
The connection object is no more global and it is destroyed in
closing of the using statement.
No need to use a DataReader just to find out if the user exists or
not
Using a parameterized query to avoid SQL Injection on the input data
Avoid a global connection object. There is the connection pooling infrastructure that removes any performance problem and you are safe from excessive resource usage.
The SqlDataReader is a good choice when you need to retrieve sequentially a lot of records, but to get just the information if the user exists or not the best approach is through the ExecuteScalar method and an appropriate sql.
The parameterized query is a must for every serious database work. It will pass the work to format your input to the framework and you don't risk an Sql Injection

Related

'Incorrect syntax near '2'.' [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Im trying to retrieve no of rows from sql based user input & display in gridview
Please help!
Int32 text = Convert.ToInt32(this.Txtusers.Text);
con.Open();
cmd = new SqlCommand("select TOP '" + text + "' * from Avaya_Id where LOB = '" + DDLOB.SelectedItem.Value + "' and Status = 'Unassigned'", con);
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
con.Close();
Here is how it should be written.
int text;
if(int.TryParse(this.Txtusers.Text, out text)
{
using(var con = new SqlConnection(connectionString)
{
using(var cmd = new SqlCommand("select TOP (#top) * from Avaya_Id where LOB = #LOB and Status = 'Unassigned'", con))
{
cmd.Parameters.Add("#top", SqlDbType.Int).Value = text;
cmd.Parameters.Add("#LOB", SqlDbType.Int).Value = DDLOB.SelectedItem.Value;
con.Open();
using(var rdr = cmd.ExecuteReader())
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
}
}
}
Points of interest:
Using parameters to avoid the risk of Sql Injection.
Changed Convert.ToInt32 to int.TryParse. Never trust user input.
Use the using statement for every instance that implements the IDisposable interface.
Please note that using top x without an order by clause means you get x arbitrary records from the database - since database tables are unordered by nature and the only way to ensure the order of the rows returned from a select statement is to use the order by clause.
Please note I've guessed that the second parameter is an int, if it's not, change the data type.

ExecuteReader() Object cant be converted [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have set up a mySql database on a server, and now i want to reach it in order for me to make a webservice. Firstly i just want to test if i can grab an entity from my query in my method (OneEntity), and put it into my list.
public IEnumerable<Person> Get()
{
return new List<Person> {
new Person{ ID = 0, First = OneEntity(), Last ="Example"}
};
}
public string OneEntity()
{
MySql.Data.MySqlClient.MySqlConnection mySqlConnection;
MySql.Data.MySqlClient.MySqlCommand cmd;
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["MySql"].ToString();
mySqlConnection = new MySql.Data.MySqlClient.MySqlConnection(connString);
cmd = new MySql.Data.MySqlClient.MySqlCommand();
cmd.CommandText = "SELECT 'name' FROM 'CustomerDb' WHERE 'id' = 0";
cmd.CommandType = CommandType.Text;
cmd.Connection = mySqlConnection;
mySqlConnection.Open();
SqlDataReader reader = cmd.ExecuteReader();
mySqlConnection.Close();
return reader;
}
I am not very experienced in c# and are therefore not sure if im doing it correct. However in my cmd.ExecuteReader() (Object i guess it is?!??!) i get that it
cannot implicitly convert type 'MySql.Data.MySqlDataReader' to
'System.Data.SqlClient.SqlDataReader'
What am i doing wrong here?? obviously my return is not correct either, as i specified my method to be 'string'.. but even though i type in a string, the error doesn't dissapear?
you shoud use MySqlDataReader not SqlDataReader
MySqlDataReader Reader = cmd.ExecuteReader();
code should return string not the reader in your case.
To return the first item use this return reader.GetString(0);

C# How to get DataTable value [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I still new to C# and just have 3 months plus of learning process. I would like to seeking advice on how to extract data value from my DataTable I have create for validation checking.
private void checker
{
string sqlSelect2 = "SELECT a.AccNo, a.CompanyName , a.CreditLimit, FROM Debtor a JOIN";
}
which i have named TableCehecker, i do not need to put it to gridview, just for checking purposes.
In the private void process how can I extract dataTable TableCehecker and the value?
Thank you,
Brian
You need to follow the Docs from MSDN:
SqlConnection sqlConnection1 = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand();
SqlDataReader reader;
cmd.CommandText = "SELECT * FROM Customers";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
DataTable dt = new DataTable();
dt.Load(reader);
sqlConnection1.Close();
You can then check whatever you want of data inside the DataTable either by querying or by looping through the rows and checking the column values.
Based on your comments, to extract values from single row:
DataRow drow = dt.Rows[0];
string value = drow.Field<string>("CompanyName");

Alert message when certain limit has been made [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am creating a form for alerting the user that the stock for this item in the database is getting the limit or passed right through the limit.
this is my code for checking the quantity of a certain stock
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "select * from tbl_BloodChemistry where Glucose = "+123+" ";
reader = cmd.ExecuteReader();
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Critical!");
}
conn.Close();
It's not actually the answer, but you have no reason to retrieve all data to collect count of rows. Use SQL COUNT and ExecuteScalar() for this.
Also, it's important to use command Parameters to your query. Don't ever build a query in your way! The input variable, Glucose, is typically retrieved from a TextBox control on either a Windows form or a Web Page. Anything placed into that TextBox control will be put into inputCity and added to your SQL string. This situation invites a hacker to replace that string with something malicious. In the worst case, you could give full control of your computer away.
Instead of dynamically building a string, as shown in the bad example above, use parameters. Anything placed into a parameter will be treated as field data, not part of the SQL statement, which makes your application much more secure.
Using parameterized queries is a three step process:
Construct the SqlCommand command string with parameters.
Declare a SqlParameter object, assigning values as appropriate.
Assign the SqlParameter object to the SqlCommand object's Parameters property.
var glucoseFilterValue = "123";
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "select count(*) from tbl_BloodChemistry where Glucose = #Glucose";
cmd.Parameters.AddWithValue("#Glucose", glucoseFilterValue);
var count = (int) cmd.ExecuteScalar();
if (count == 1)
{
MessageBox.Show("Critical!");
}
conn.Close();
Then you'll make your code more clean and prevent extra loading to your communication channel.

delete data on SQL table based on datatable input [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
This method below goes into a table and deletes all of the table. But in the datatable "table" below in the first column there are dates which i would like to be deleted from the database. how would i go about doing this
Datatable table = new DataTable()
string sqlConnectionString =
"Server = 100.720.8.196; Database = testDat; User Id = sa; Password = ";
// Copy the DataTable to SQL Server
using (SqlConnection conn = new SqlConnection(sqlConnectionString))
{
string deleteSting =
"delete from dbo.testTable where clientId=1212";
conn.Open();
using (SqlCommand cmd = new SqlCommand(deleteSting, conn))
{
cmd.ExecuteNonQuery();
}
conn.Close();
}
I'm just guessing here, you probably mean to make the date column empty. If that's the case then you use UPDATE, like:
string updateString =
"UPDATE dbo.testTable SET datecol = #datecol where clientId=#clientID";
conn.Open();
using (SqlCommand cmd = new SqlCommand(updateString, conn))
{
cmd.Parameters.Add("#datecol", SqlDbType.Date).Value = DbNull.Value;
cmd.Parameters.Add("#clientID", SqlDbType.Int).Value = 1212;
cmd.ExecuteNonQuery();
}
conn.Close();
Well, there are a few options. You could loop through your table and create a string containing your dates in a comma separated list. With that, you can create a SQL Statement like delete from table where dateCol in (date1, date2, date3, etc...)
Or you could just loop through your data table, and do one delete per loop iteration. Either way will work.
However you decide to proceed, make sure to use parameters instead of string concatenation to prevent issues like SQL Injections:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters.aspx

Categories