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.
Related
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.
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();
}
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>
}
Query returns what I expected it to return now with is null instead of != null, but I am still stuck as to why I am getting the exception in my c# application which is my main problem, Thanks
I have a column called UserId in a table WT_Users when I run the query
'select UserId from WT_Users;'
It returns a list of usersIds 1,2,3,4 which is fine but when I run the query
'select UserId from WT_Users where UserId != null'
No values are returned even thought I know that there are values held within the column. I ran these queries because I was originally working on a c# application and when I ran a reader with the first query above i got an exception 'Object reference not set to an instance of an object' when i tried to pull the value from the reader, even thought I have a 'HasRows' check and 'while read' check that were satisfied
SqlCommand findContactID = new SqlCommand("select UserId from WT_Users", con);
con.Open();
SqlDataReader dr7 = findContactID.ExecuteReader();
if (dr7.HasRows)
{
while (dr7.Read())
{
userIDs.Add(Convert.ToString(dr7.GetInt32(0)));
}
}
In visual studio I can even see that the reader does contain the values I what under Results view.
I have spent too much time already trying to figure this out and its probably something obvious. Thanks
You should never use comparison operations with null. Use is null or is not null.
Whenever you use a comparison operator with null, it resolves to UNKNOWN, which is neither True nor False.
select UserId from WT_Users where UserId is not null
Try this:
private void Test2(SqlConnection con)
{
var userIDs = new List<String>();
using (var cmd = new SqlCommand("select UserId from WT_Users", con))
{
con.Open();
using (var r = cmd.ExecuteReader())
{
while (r.Read())
{
var o = r[0];
if ((o != null) && (o != DBNull.Value))
{
userIDs.Add(o.ToString());
}
}
}
}
}
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.