I am trying to minus value in database column from textbox I got error an expression of non-boolean type specified in a context where condition is expected
cn.Open();
SqlCommand command = new SqlCommand();
command.Connection = cn;
command.CommandText = "select * from class where quanitity - '"+Convert.ToInt32(textBox10.Text)+"'";
command.ExecuteNonQuery();
cn.Close();
You are not minus value to column.you want like this
command.CommandText = "update class set quanitity = quanitity - "+Convert.ToInt32(textBox10.Text) ;
This will definitely work
command.CommandText = string.Format("update class set quanitity= quanitity - {0}",Convert.ToInt32(textBox10.Text));
You need a value to compare your two numbers to. You are subtracting your TextBox10 value from quantity, but what result set do you want to see after subtracting the value? There needs to be a comparison somewhere to the right of your WHERE.
command.CommandText = "select (quantity - "+Convert.ToInt32(textBox10.Text)+") from class ;
I suspect you SQL Injection alert..Do not Concatenate string it's wide open for sql injection alert.So use parameterized query
command.CommandText = "select * from class where quanitity -#txtbox10";
command.Parameters.AddWithValue("#txtbox10", Convert.ToInt32(textBox10.Text));
command.ExecuteNonQuery();
Related
I have a SqlDataReader, which needs to read certain values out of my database. The SqlCommand which selects these values looks like this:
SqlCommand myCommand = new SqlCommand("SELECT * FROM dbo.Confronting_Value", valueConnection);
Each entry in the database consists of "Attacker", "Defender" and "Value". All 3 contain integer values.
For example
Attacker: "665", Defender: "443", Value: "3".
There may be multiple entries where the "Attacker" has the value "665".
Now, SELECT WHERE Attacker = 665 would be simple, but I have a variable Black.ID. I want to select all entries where the Attacker has the same value as Black.ID. How do I do that?
Not sure if I understand you correctly - but just adding a parameter to the query might work:
SqlCommand myCommand = new SqlCommand(#"SELECT *
FROM dbo.Confronting_Value
WHERE Attacker = #Value", valueConnection);
// add parameter and set its value to "Black.ID"
myCommand.Parameters.Add("#Value", SqlDbType.Int).Value = Black.ID;
and then from here on, run the code you already have. This will select all rows where Attacker has the same value as your Black.ID value.
Sorry, what is Black.ID? A variable in your code? A column of another table in the database?
In the first case add a Where clause to your command like this:
"SELECT * from dbo.Confronting_Value WHERE Attacker=" + Black.ID
or better
SqlCommand myCommand = new SqlCommand("SELECT * FROM dbo.Confronting_Value WHERE Attacker = #param1", valueConnection);
myCommand.Parameters.Add("#param1", SqlDbType.Int);
myCommand.Parameters["#param1"].Value = Black.ID;
Hope this can help you.
I need to bind parameters on ODBC query from C#. This is the sample code, but VS tells me that there's one parameter missing.
OdbcCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM user WHERE id = #id";
cmd.Parameters.Add("#id", OdbcType.Int).Value = 4;
OdbcDataReader reader = cmd.ExecuteReader();
What is the syntax for binding values on ODBC?
Odbc cannot use named parameters. This means that the command string uses placeholders for every parameter and this placeholder is a single question mark, not the parameter name.
OdbcCommand.Parameters
Then you need to add the parameters in the collection in the same order in which they appear in the command string
OdbcCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM [user] WHERE id = ?";
cmd.Parameters.Add("#id", OdbcType.Int).Value = 4;
OdbcDataReader reader = cmd.ExecuteReader();
You have also another problem, the USER word is a reserved keyword per MS Access Database and if you want to use that as field name or table name then it is required to enclose every reference with square brackets. I strongly suggest, if it is possible, to change that table name because you will be hit by this problem very often.
use "?" in place of # if you are using ODBC.
Try to do as follows:
OdbcCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM user WHERE id = ?";
cmd.Parameters.Add("#id", OdbcType.Int).Value = 4;
OdbcDataReader reader = cmd.ExecuteReader();
To use ODBC parameterized LIKE carry out as follows, i.e. you do not use the typical single quotes or even put the % in the CommandText (Furthermore I think perhaps the %? has a special meaning for Oracle? :
OdbcCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT * FROM [user] WHERE name LIKE ?";
cmd.Parameters.AddWithValue("#fieldName", OdbcType.NVarChar).Value = "%" + nameFilter + "%";
I need to retrieve a value from a field in database. I have the used following code. but the value checkOrderId (which I need) shows the SQL string instead of the value from database. I don't know why it is doing so. Could somebody help me please?
string connectionString = "Data Source = xxyyzz;Initial Catalog = xyz; Integrated Security = True";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
string tableName = "[GIS].[SecondaryTraffic].[PotentialBackHauls]";
string checkOrderId = "Select TOP 1 OrderID From" + tableName + "ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
//cmd.ExecuteNonQuery();
OpenPop.Pop3.Pop3Client popConn = new OpenPop.Pop3.Pop3Client();
if (orderIdentity == checkOrderId)
{
popConn.DeleteMessage(messageNumber);
}
connection.Close();
I am new and dont have reputation to answer my question immediately. With everybody's help, i got this one solved...Great help, thanx everybody...following is my code.
string connectionString = "Data Source = EAEDEV;Initial Catalog = GIS; Integrated Security = True";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string tableName = "[GIS].[SecondaryTraffic].[PotentialBackHauls]";
string checkOrderId = "Select TOP 1 OrderID From " + tableName + " ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
string valueReturned = (string)cmd.ExecuteScalar();
OpenPop.Pop3.Pop3Client popConn = new OpenPop.Pop3.Pop3Client();
if (orderIdentity == valueReturned)
{
popConn.DeleteMessage(messageNumber);
}
connection.Close();
}
You need to execute the query and check the results, here you are just comparing a string with the query SQL.
Please see here
http://www.csharp-station.com/Tutorial/AdoDotNet/lesson03
for a tutorial.
Your expectation of the result being set into checkOrderId is incorrect. In this instance checkOrderId is just the query to execute and not the actual result.
You need to read the value back from executing the command:
using (var connection = new SqlConnection(connectionString))
using (var comm = new SqlCommand("Select TOP 1 OrderID From [GIS].[SecondaryTraffic].[PotentialBackHauls] ORDER BY InsertDate DESC", connection))
{
connection.Open();
object result = comm.ExecuteScalar(); // This is the key bit you were missing.
if (result != null)
{
// You can cast result to something useful
int orderId = (int)result;
}
} // Both comm and connection will have Dispose called on them here, no need to Close manually.
ExecuteScalar returns the value in the first cell (ie, column 1 row 1) as an object that you can cast to a better type (depending on what type it was in the result-set schema).
If you need to read multiple values, you need to look at ExecuteReader.
There are also other ways of doing this using output parameters, but that would pollute the point of the answer.
You can add space to your query
"Select TOP 1 OrderID From " + tableName + " ORDER BY InsertDate DESC";
Nota : I suggest you to use AddWithValue method with your parameter
string checkOrderId = "Select TOP 1 OrderID From #tableName ORDER BY InsertDate DESC";
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
cmd.Parameters.AddWithValue("#tableName", tableName );
Link : http://msdn.microsoft.com/fr-fr/library/system.data.sqlclient.sqlparametercollection.addwithvalue.aspx
You don't actually run your command anywhere. Instead of the commented-out cmd.ExecuteNonQuery, you should look into the ExecuteScalar method, which allows you to read back a single result value from a query - which is what your query returns.
Add
int i = (Int32) cmd.ExecuteScalar();
right after
SqlCommand cmd = new SqlCommand(checkOrderId, connection);
then the variable i will contain the order id
No, this is not correct. You are comparing the variable orderId to your query string. I doubt that's what you want to do. I imagine you'd be better off calling cmd.ExecuteScalar() to retrieve the actual OrderID value. As noted by other answers, your query string is missing a space. But most importantly, it is bad practice to construct SQL queries in code. Although I can't see a security issue with this code, if you continue to use this method you will probably write code that is vulnerable to SQL injection. I recommend you learn to either use parameters or LINQ to build your queries.
i am trying to retrieve latest data from my database table.
i am using max(columnName) but not having result to my liking.
i keep getting column name instead of any value
please help me out in this...
the code for retrieving max value is like this
dbConnection dbCon = new dbConnection();
con = dbCon.doConnection();
SqlCommand cmd = new SqlCommand();
String query = "select max(studentNo) from studentInfo;";
cmd.Connection = con;
cmd.CommandText = query;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
String x=reader["studentNo"].ToString();
}
here the studentNo is the column name whose value i need to extract and it is of int type
while printing the string x on my application i get studentNo instead of the value.
now i am short of clue to solve the prob because i can't find anything wrong with the code.
do help me in this one
The problem is in the way you are accessing the value, you can change two things here. Either access the reader by index or name the column appropriately in the query.
select max(studentNo) as StudentNo from studentInfo;
Your query outputs one row and one column of data, so you might consider using ExecuteScalar() instead of ExecuteReader():
dbConnection dbCon = new dbConnection();
con = dbCon.doConnection();
SqlCommand cmd = new SqlCommand();
String query = "select max(studentNo) from studentInfo;";
cmd.Connection = con;
cmd.CommandText = query;
String x = cmd.ExecuteScalar().ToString();
You need to give alias to your select after applying aggregate function
i.e. select max(studentNo) as NO from studentInfo
and while reading it
String x=reader["NO"].ToString();
First you need to set the correct alias do the column:
select max(studentNo) as 'studentNo' from studentInfo;
And second, you may want to assign a database to the table:
select max(studentNo) as studentNo from databaseName..studentInfo;
Greetings all,
I have a question. I am trying to build a parametrized query to get me the number of rows from a table in Oracle. Rather simple. However I am an Oracle newbie..
I know in SQL Server you can do something like:
Select #outputVariable = count(*) from sometable where name = #SomeOtherVariable
and then you can set up an Output parameter in the System.Data.SqlClient to get the #outputVariable.
Thinking that one should be able to do this in Oracle as well, I have the following query
Select count(*) into :theCount from sometable where name = :SomeValue
I set up my oracle parameters (using System.Data.OracleClient - yes I know it will be deprecated in .Net 4 - but that's what I am working with for now) as follows
IDbCommand command = new OracleCommand();
command.CommandText = "Select count(*) into :theCount from sometable where name = :SomeValue";
command.CommandType = CommandType.Text;
OracleParameter parameterTheCount = new OracleParameter(":theCount", OracleType.Number);
parameterTheCount .Direction = ParameterDirection.Output;
command.Parameters.Add(parameterTheCount );
OracleParameter parameterSomeValue = new OracleParameter(":SomeValue", OracleType.VarChar, 40);
parameterSomeValue .Direction = ParameterDirection.Input;
parameterSomeValue .Value = "TheValueToLookFor";
command.Parameters.Add(parameterSomeValue );
command.Connection = myconnectionObject;
command.ExecuteNonQuery();
int theCount = (int)parameterTheCount.Value;
At which point I was hoping the count would be in the parameter parameterTheCount that I could readily access.
I keep getting the error ora-01036 which http://ora-01036.ora-code.com tells me to check my binding in the sql statement. Am I messing something up in the SQL statement? Am I missing something simple elsewhere?
I could just use command.ExecuteScaler() as I am only getting one item, and am probably going to end up using that, but at this point, curiosity has got the better of me. What if I had two parameters I wanted back from my query (ie: select max(ColA), min(ColB) into :max, :min.....)
Thanks..
Some versions of the ADO does not need the colon : configuring OracleParameter.
Instead of:
new OracleParameter(":theCount", OracleType.Number);
try
new OracleParameter("theCount", OracleType.Number);
Anyway, I think you have to use the ExecuteScalar() function of the IDbCommand and avoiding use of into (which I'm not sure it's valid on this context). I mean:
IDbCommand command = new OracleCommand();
command.CommandText = "Select count(*) from sometable where name = :SomeValue";
command.CommandType = CommandType.Text;
OracleParameter parameterSomeValue = new OracleParameter("SomeValue", OracleType.VarChar, 40);
parameterSomeValue .Direction = ParameterDirection.Input;
parameterSomeValue .Value = "TheValueToLookFor";
command.Parameters.Add(parameterSomeValue );
command.Connection = myconnectionObject;
int theCount = (int)command.ExecuteScalar();
Disclaimer: The code have not been compiled, and may be have any little error.
Update: If you take a look on the Oracle SELECT syntax, you will see that The SELECT INTO sentence is not recognized. But it's valid in PLSQL syntax as you can see here. You can try one of the following to see if it works (not tested):
command.CommandText = "begin Select count(*) into :someCount from sometable where name = :SomeValue; end;";
I think the problem is that you have a trailing space in the parameter name for parameterTheCount.
Edit
Now remove the colons from the parameter names in the constructor to OracleParameter.