How to spot an empty access field with data reader C# - c#

I'm trying to create a method that returns a string from my db that fulfills my conditions.
The first condition is working.
But, the second condition is that part of entry in access is empty, at least one field.
This is my code:
OleDbCommand datacommand = new OleDbCommand();
datacommand.Connection = dataConnection;
datacommand.CommandText = "SELECT numNumber, numLocation " +
"FROM tblNumbers " +
"ORDER BY numID ";
OleDbDataReader dataReader = datacommand.ExecuteReader();
while (dataReader.Read())
{
if (MatchServiceLetters(dataReader.GetString(0))) // && dataReader.GetInt32(1) == null?/)
}
return dataReader.GetString(0);
If the int field is empty, the comparison to null isn't working. so how can I know if it is empty?

From MSDN:
No conversions are performed; therefore, the data retrieved must already be a 32-bit signed integer.
Call IsDBNull to look for null values before calling this method.
So you would use:
if(!dataReader.IsDBNull(1))
{
return dataReader.GetInt32(1);
}
else
{
return 0; // or better yet, make your method return Nullable<int>
}

Related

Object cannot be cast from DBNull to other types in C#

I wrote this code :
MySqlCommand command1 = new MySqlCommand("SELECT SUM(standard_one) FROM `challenge` WHERE (SELECT DAYOFWEEK(date)=1) AND challenge_id = #challenge_id and username = #username", db.getConnection());
command1.Parameters.Add("#challenge_id", MySqlDbType.Int32).Value = comboBox1.SelectedItem;
command1.Parameters.Add("#username", MySqlDbType.VarChar).Value = globals.username;
the problem is some times this command returns null.
how can I check if the command will return null? and if so it returns 0?
if the command will return null? and if so it returns 0?
Make the SQL:
SELECT COALESCE(SUM(standard_one), 0) ...
Bear in mind that you then won't be able to tell the difference between "there were no values that matched the where clause" and "the sum of all values that matched was 0".. If that's important, you'll either need to coalesce to a different value that would never occur in the sum, like -2_147_483_648 or persist with what you have and check for null on the C# side
var x = command1.ExecuteScalar();
if(x == null || x.GetType() == typeof(System.DBNull))
...
else
..cast to int etc..

IF condition check inside USING method and SqlConnection

I am trying to run data validation, execute some code and pass data from one SQL query to another.
My current code looks like the below:
public string SelectUniqueKeyNumber()
{
string newList = string.Join(Environment.NewLine, listOfSkus).ToString();
string key_id;
string sqlConnectionString = #"someConnectionString";
using (SqlConnection connection = new SqlConnection(sqlConnectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("select top 1 KEY_NUMBER from MyTable where QTY_ON_HAND > 0 " + newList + " order by NEWID()", connection);
SqlDataReader readerKey = command.ExecuteReader();
readerKey.Read();
key_id = String.Format(readerKey[0].ToString());
}
SelectSkuNumber(key_id);
return key_id;
}
What I am trying to do is to check if my readerKey.Read() is not returning null value. If it does then stop the process, otherwise continue. I've tried it in the way as shown below:
public string SelectUniqueKeyNumber()
{
string newList = string.Join(Environment.NewLine, listOfSkus).ToString();
string key_id;
string sqlConnectionString = #"someConnectionString";
using (SqlConnection connection = new SqlConnection(sqlConnectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("select top 1 KEY_NUMBER from MyTable where QTY_ON_HAND > 0 " + newList + " order by NEWID()", connection);
SqlDataReader readerKey = command.ExecuteReader();
readerKey.Read();
if(readerkey.Read().ToString() == null)
{
//--- stop processing
}
else
{
key_id = String.Format(readerKey[0].ToString());
}
}
SelectSkuNumber(key_id); //---> Then ...(key_id) is not declared value
return key_id;
}
By doing so, I cannot access and pass data of SelectSkuNumber(key_id) due to: Use of unassigned local variable 'key_id'
Any ideas?
All you need do is assign something to key_id when you declare it, like:
string key_id = null; // not string key_id;
and later, after the using:
if (key_id != null)
{
SelectSkuNumber(key_id); //---> Then ...(key_id) is not declared value
}
return key_id;
The caller of the function should, of course, know what to do if a null is returned.
To avoid that particular problem, you can assign some value or nnull to key_id, eg. key_id = "";.
But you have some more problem there:
You are prone to SQL injection, you should use Parameters collection of SqlCommand class.
Are you sure you are concatenating your query correctly? Let's suppose
newList = {"some", "thing"};
Then your query would be:
select top 1 KEY_NUMBER
from MyTable where QTY_ON_HAND > 0
some
thing
order by NEWID()
Which is very, very incorrect to say the least.
if(readerkey.Read().ToString() == null) condition... Read returns bool, which is either true or false, it isn't reference type, so ToString() will never be null, thus the condition will always fail. If you want to check if there was NULL in database you should check:
if (readerKey.Read() && readerKey["KEY_NUMBER"] == DBNull.Value)
which first read row, then receives value of column in that row. It uses short-circuiting for the case, where no records are returned.
readerKey.Read(); is unnecessary before the if statement.

how to convert sqlcommand type to String type

I am trying to fetch value from the first row and first column. After fetching I need to convert that value to a string. Please help me with the conversion.
Here is my current code:
conn.ConnectionString = "Server=localhost;Database=MIN-MAK MRO;Trusted_Connection=true";
conn.Open();
SqlCommand command = new SqlCommand("SELECT Top 1 FirstName FROM HistoryReport ", conn);
Something like this -
string getValue = command.ExecuteScalar().ToString();
Note: If there are no rows .ExecuteScalar() will return null
The result from a query with a single result is returned as bare Object. To safely convert it to string, you need to first check it against both DBNull.Value and against null, before performing ToString() on it.
public static String SafeGetString(Object databaseResult)
{
if (databaseResult == DBNull.Value || databaseResult == null)
return null;
return databaseResult.ToString();
}

How to read nvarchar(x) into String when null values are allowed?

I have a SQL table with a column of type nvarchar(20) and want to read that column using SqlDataReader. Looks like the only way to do this is to use GetSqlChars() followed by ToSqlString():
String result = reader.GetSqlChars(index).ToSqlString().Value
the problem is that if the stored value happens to be null (and that's valid for my case) I get
[SqlNullValueException: Data is Null. This method or property cannot be called on Null values.]
System.Data.SqlTypes.SqlString.get_Value() +3212527
so I have to first check what the value returned by ToSqlString() returns in IsNull():
SqlString asSqlString = reader.GetSqlChars(index).ToSqlString();
String result = asSqlString.IsNull() ? null : asSqlString.Value;
which works but requires lots of extra code and looks really inelegant.
Is there a more elegant way to achieve the same effect?
Perhaps:
var value = reader.IsDBNull(index) ? null : reader.GetString(index);
Or even shorter:
var value = reader[index] as string;
You can use the GetValue() method:
// define your query
string query = "SELECT YourField FROM dbo.YourTable WHERE ID = 1";
using(SqlConnection conn = new SqlConnection("......"))
using(SqlCommand cmd = new SqlCommand(query, conn))
{
conn.Open();
using(SqlDataReader rdr = cmd.ExecuteReader())
{
if(rdr.Read())
{
string fieldValue = rdr.GetValue(2).ToString();
}
}
conn.Close();
}
GetString method is specifically coded to throw an exception if the database value is null. This is by design.
The docs for GetString state:
Call IsDBNull to check for null values before calling this method
On the other hand, if you use GetValue() and you end up with a DBNull object as your value, the DBNull.ToString method automatically returns String.Empty.

If Condition for Query with Empty Result

I have written this SQL query:
SqlCommand cmd2 = new SqlCommand();
cmd2.Connection = new SqlConnection(Class1.CnnStr);
cmd2.CommandText = "SELECT MAX(Code) FROM Table WHERE Number=#Number ";
cmd2.Connection.Open();
cmd2.Parameters.AddWithValue("#Number", Hidden_txt.Text);
cmd2.ExecuteNonQuery();
and I would like to add some if condition like:
if (cmd2.ExecuteScalar()=="Null")
{....}
How can I add an if condition for when my query does not have an answer?
Remove the call to cmd2.ExecuteNonQuery, then add something like this:
object maxCode = cmd2.ExecuteScalar();
if (maxCode == null)
{
// Null
}
else
{
// do something with maxCode, you probably want to cast - e.g. (int)maxCode
}
You can use a reader like this:
This assumes that the type of Code is integer, so change as necessary
SqlDataReader reader = cmd2.ExecuteReader;
int code = 0;
if (reader.Read) {
//whatever if it has a result
code = reader.GetInt32(0);
} else {
//Whatever if it finds nothing
}
According to MSDN:
If the first column of the first row in the result set is not found, a null reference (Nothing in Visual Basic) is returned. If the value in the database is null, the query returns DBNull.Value.
So, you could just write:
if (cmd2.ExecuteScalar() == null)
{....}
Alternatively, you could use ExecuteReader, then check whether returned reader HasRows.

Categories

Resources