how to compare oledb datareader with a textbox data? - c#

i want to compare oledb datareader data with a textbox data something like this cod.
i have textbox named textbox7 ... the datareader have more than one mobile_no
OleDbCommand ol_com = new OleDbCommand();
OleDbDataReader reader;
ol_com.CommandText = "select [mobile_no] from student_info";
reader = ol_com.ExecuteReader();
if (reader.Equals(textbox7.text))
{
up_st_lbl2.Text = "error";
}
else
{
//do something
}
any one can help me please?

You are trying to compare the actual OleDbDataReader object with the TextBox string value, which will obviously not return true ever. You need to compare the column value of your query with the text box. You might also consider putting a WHERE clause in your sql to filter out unnecessary rows. Please read this article to get a basic understanding of how to perform data access with MS Access - http://msdn.microsoft.com/en-us/library/ms971485.aspx
if ((string) reader["[mobile_no]") == textbox7.Text)
{
// error
{

Related

How to put IF condition while reading SQL Server query data in C#

Dears,
I'm designing a report in C# using windows form linked to SQL Server table. The result of the query is usually GP% numbers like : 30% or 40% and so on. These numbers are string by the way. I want to put the SQL Server result "30% for example in the array in c#. if no problem with the number it will be added simply like this :
conn.Open();
SqlCommand cmd43 = new SqlCommand(Product1ProfitPercentQuery, conn);
SqlDataReader rd43 = cmd43.ExecuteReader();
while (rd43.Read())
{
string Product1= rd43.GetString(0);
Products.Add(Product1);
}
rd43.Close();
conn.Close();
/But the problem is that some times the query's result is Null. The array will not accept to put Null result. I want to put a condition in the array reader as the following but its't working :/
conn.Open();
SqlCommand cmd43 = new SqlCommand(Product1ProfitPercentQuery, conn);
SqlDataReader rd43 = cmd43.ExecuteReader();
while (rd43.Read())
{
string Product1= rd43.GetString(0);
if (Product1=="Null")
{
Products.Add("0");
}
else if (Product1!= "Null")
{
Products.Add(Product1);
}
}
rd43.Close();
conn.Close();
How can i write this condition please. Thanks in advance.
You can use the HasRows property of the SqlDataReader to see if the recordest was populated or null, and you could wrap your while loop within it.
conn.Open();
SqlCommand cmd43 = new SqlCommand(Product1ProfitPercentQuery, conn);
SqlDataReader rd43 = cmd43.ExecuteReader();
if (rd43.HasRows) {
while (rd43.Read())
{
string Product1= rd43.GetString(0);
Products.Add(Product1);
}
}
rd43.Close();
conn.Close();
You need to check SqlDataReader.IsDBNull(0) in your if statement like below:
if (rd43.IsDBNull(0))
{
Products.Add("0");
}
else
{
Products.Add(rd43.GetString(0));
}
More information about it you can find here
If the column is null, the reader will return a SQL DBNull value, not a string representation of null. Try something like this:
string Product1= rd43.GetString(0);
if(rd43.IsDBNull(Product1))
{
Products.Add("0");
}
else
{
Products.Add(Product1);
}

SqlDataReader - correct syntax, must I hardcode column number?

I have a database named testDB, which contains table Versions, which contains a column [Release Date] with datetime format.
Now, I want to read it in my C# Windows Service:
protected void SqlConnect()
{
SqlCommand comSql;
DateTime relDate;
SqlDataReader myReader = null;
using (SqlConnection myConnection = new SqlConnection(_server +
_username +
_password +
"Trusted_Connection=yes;" +
"database=testDB; " +
"connection timeout=30"))
{
try
{
myConnection.Open();
comSql = new SqlCommand("select [Release Date] from dbo.Version",
myConnection);
myReader = comSql.ExecuteReader();
while (myReader.Read())
{
//Here's my problem, explained below
}
}
catch
{
}
finally
{
if (myReader != null) myReader.Close();
}
}
}
Now, I want to assign the value stored in that column to relDate variable. However
relDate = myReader.GetDateTime();
requires GetDateTime to have column number passed there (if I understand this right). But I already selected column in my comSql. Is this the correct way to deal with this problem, ie. just putting the column number in the code?
EDIT: Ok judging by the answers I might word this question wrong or something.
I know that I must pass the column index to GetDateTime(). I ask if there's a way to do that without hardcoding it like GetDateTime(0).
You can use GetOrdinal method on the data reader to get ordinal of the column from its string name. In that way, you won't have to hardcode the column index.
GetOrdinal is also useful when you're reading data from the data reader in a loop. You can initialize the index variable before the loop starts and then use it in every iteration of the loop.

c# - MySQL connector universal SELECT query method for mutliple tables

I'm trying to write a method that returns a list with every row that a select query returns. But anything I can find on this is based on a single table.
This is what I'm trying:
public List<string> Select(string querystring)
{
string query = "SELECT " + querystring;
List<string> results = new List<string>();
if (this.OpenConnection())
{
MySqlCommand cmd = new MySqlCommand(query, connection);
MySqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
// in here I don't want a to "hard code" every column
results.Add( "returned data" );
}
dataReader.Close();
this.CloseConnection();
return results;
}
else
{
return results;
}
}
Is this possible? Do I need to make a new method for every table?
Or should I maybe return a list of objects instead of strings?
I'm really having a brainfart here so any help is appreciated.
As I stated from my comment:
I'm not sure what you're trying to do exactly... it looks like you're hoping to put a rows and columns (your data set) into just rows (your list of string). How are you planning on using this data? It will not be very useable trying to use it in the manner it looks like you're attempting. You can reference your data readers columns by index, but again I'm not clear on what you're hoping to accomplish.
You can however do it by doing something like this:
while (reader.Read())
{
// for loop with a maximum iteration of the number of columns in the reader.
for (int i=0;i<reader.FieldCount;i++)
{
results.Add(reader[i].ToString());
}
}
but again, I don't think this will get you data in a useable manner.
I would recommend you to look into Dapper.NET or EF6 or nHibernate.

Fetch data from MySql to C# application

I have a MySql table from which I fetch data to my C# application. Randomly some data are inserted in this table form another source. I want to fetch those data continuously in my C# application. My DB connection and select query are following :
string connection = "Server=localhost;Database=intel;Uid=root;Pwd=";
MySqlConnection dbcon = new MySqlConnection(connection);
MySqlCommand selectData;
dbcon.Open();
selectData = dbcon.CreateCommand();
selectData.CommandText = "SELECT user_id, user_name,user_type FROM win_user ORDER BY user_id ASC ";
MySqlDataReader rdr = selectData.ExecuteReader();
I want to execute my select query unit it get any data.
if
Get data = null
execute my select query again
else
Get data = data
execute my next code
I think it can be happen with while loop, but I dont know how ? Can any onk help me ?
What you want to do sounds odd but, to answer the question as asked, you can use a loop like so:
MySqlDataReader rdr = selectData.ExecuteReader();
// Check whether the result set is empty.
while (!rdr.HasRows)
{
rdr.Close();
// Pause before trying again if appropriate.
rdr = selectData.ExecuteReader();
}
while (rdr.Read())
{
// Read data here.
}
use this
If(rdr.HasRows)
{
rdr.Read();
// do your logic
}
rdr.Close();
use rdr.Read() only when you have some data in datareader object.
if you simply want to read values without checking null than use this
while (rdr.Read())
{
// do logic
}
rdr.Close();
this loop runs as many times as no of rows exist in your select query result.

How to save a table(DataTable) into a single cell in a database?

Is it possible to save a DataTable into SQL database in one cell of type binary for example and read it back again into a DataTable?
I would create, if possible, a xml field inside the sql database and save the datatable as xml
XML Support in Microsoft SQL Server 2005
and
C# and Vb.net example for XML data type tips in SQL Server 2005
should help you
another example took from here
protected bool LoadXml(SqlConnection cn, XmlDocument doc)
{
//Reading the xml from the database
string sql = #"SELECT Id, XmlField FROM TABLE_WITH_XML_FIELD WHERE Id = #Id";
SqlCommand cm = new SqlCommand(sql, cn);
cm.Parameters.Add(new SqlParameter("#Id",1));
using (SqlDataReader dr = cm.ExecuteReader())
{
if (dr.Read())
{
SqlXml MyXml= dr.GetSqlXml(dr.GetOrdinal("XmlField"));
doc.LoadXml( MyXml.Value);
return true;
}
else
{
return false;
}
}
}
why on earth would you want to?
If this is an operation you are going to do more than once, just save it out to a new sql table and read from the table into your DataTable later.
It just breaks normalization rules- the value in the cell is not atomic.
I break that rule myself all the time, but still, it's important to understand alternative approaches.
You could have a related table to store their answers instead of storing all their answer values in a single cell.
Regarding your comment below, you can still do it with a related table. Just use a three-column table: tableID, fieldID, value. Each tableID can have its own set of fieldIDs. The trade-off is with the value datatype- it needs to be a string, which means you don't get the advantages of date or numeric data type enforcement on your back end.

Categories