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.
Related
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>
}
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.
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.
I have the next code:
private int bla(out int itemsMin, out int purchase)
{
string ID = (Request.QueryString["Ttrsid"] ?? "0").ToString();
{
SqlConnection connection = new SqlConnection("Data Source=*****;Initial Catalog=****;User ID=****;Password=*****;Integrated Security=False;");
string commandtext = "SELECT Min FROM myItems WHERE itemId=#ID";
SqlCommand command = new SqlCommand(commandtext, connection);
connection.Open();
command.Parameters.AddWithValue("#ID", ID); //Adds the ID we got before to the SQL command
itemsMin = (int)command.ExecuteScalar();
string commandtext2 = "SELECT COUNT (*) FROM purchase";
SqlCommand command2 = new SqlCommand(commandtext2, connection);
purchase = (int)command2.ExecuteScalar();
}
return 0;
}
The code is for two labels that i use - one to get the minimum number (itemsMin), and the other is for the count of the purchase.
I'm using the querystring to get the values by the itemid that the user watching on him now.. (from the address bar (for example: items.aspx?Ttrsid=5 so i want to see the minimum number of the Ttrsid = 5).
Everything works fine. when i'm on the Ttrsid = 1 , Ttrsid = 2 - i get what i want, but when i'm enterd to the Ttrsid = 3 and so on - that's give me the error:
System.NullReferenceException
To the line:
itemsMin = (int)command.ExecuteScalar();
.. and it's not null.. the item have all the required fields like Ttrsid = 2 .... so what wrong here?
The next code is the use of the command above:
int i, p; // variable need not be initialized
Console.WriteLine(bla(out i, out p));
if (i < p)
{
haha.Visible = true;
}
else
{
haha2.Visible = true;
}
Console.WriteLine(i);
Console.WriteLine(p);
i = itemsMin , p = purchase .
I'm guessing there is no matching row in the db, so no rows returned. Sanity-check the result from ExecuteScalar - in particular, check it for null before casting to int. It is also possible that the column contains a null, but maybe I'd expect DBNull.Value for that.
Also - use using on all the IDisposable objects here; the connection and command in particular.
I assume below pasted variable is a int type variable
purchase = (int)
Hence you may not be able to convert null values to an integer so try it changing the sql command as below
SELECT isNull(COUNT (*),0) FROM purchase
#Marc I'm really sorry about it
Don't you want to specify a column name next to the min statement? As below
SELECT Min(columnName) FROM myItems WHERE itemId=#ID ?