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.
Related
I'm working on access database using C#, want an SQL statement to select all information based on a desired date. for example today.
"SELECT * from mytable where mytable.dates == DateTime.Today()";
If I understand the question right and you want to make a call to the SQL Server, you can use SQLCommand and parameters.
var sqlCommand = new SqlCommand();
sqlCommand.CommandText = "SELECT * from mytable where mytable.dates= #DateAdded";
sqlCommand.Parameters.AddWithValue("#DateAdded", DateTime.Today);
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();
Problem I have is when I run a SQL UPDATE on different fields, but the same WHERE criteria in my SQL statement one produces a change, and the other does not.
This produces no rows affected:
DateTime now = DateTime.Now;
OleDbCommand cmd = new OleDbCommand("UPDATE shifts SET end_log=#end_log WHERE profile_id=#profile_id;");
cmd.Parameters.AddWithValue("#profile_id", profileID); // profileID is a string
cmd.Parameters.AddWithValue("#end_log", now.ToString());
Whereas if I ran this, one row is affected:
OleDbCommand cmd = new OleDbCommand("UPDATE shifts SET closing=true WHERE profile_id=#profile_id;");
cmd.Parameters.AddWithValue("#profile_id", profileID);
My shifts table has the following fields:
profile_id - Short Text
end_log - Date/Time
closed - Yes/No
You can assume the tables hold the same data in both instances (this is automatically loaded and only contains one record).
Anyone spot any errors?
While using OLEDB provider order of parameters is important.
Instead of
OleDbCommand cmd = new OleDbCommand("UPDATE shifts SET end_log=#end_log WHERE profile_id=#profile_id;");
cmd.Parameters.AddWithValue("#profile_id", profileID); // profileID is a string
cmd.Parameters.AddWithValue("#end_log", now.ToString());
try
OleDbCommand cmd = new OleDbCommand("UPDATE shifts SET end_log=#end_log WHERE profile_id=#profile_id;");
cmd.Parameters.AddWithValue("#end_log", now.ToString());
cmd.Parameters.AddWithValue("#profile_id", profileID); // profileID is a string
Order in which parameters are added to Parameters collection should match order in which parameters appear in the query.
I have the following update query in C# using a JET OLEDB connection, connecting to a ms access DB file. The query fails to change the fields, it runs correctly but just 0 rows changed.
I think the problem is how parameters are processed and compared against the DB but have no idea how to fix it.
The "User" column is set as text. I have an insert statement that works perfectly set up in the same fashion with the parameters.
com.CommandText = "UPDATE [ExamMaster] SET [User] = (DLookup('LName', 'Users', 'ID' = '#correctUser') WHERE [User] = '#user'";
com.Parameters.AddWithValue("#correctUser", correctUser);
com.Parameters.AddWithValue("#user", userName);
If I do not use a parameter for the where clause and just insert it into the command string like so:
WHERE [User] = '"+userName+"'";</code>
it will update the DB just fine. What am I missing here?
UPDATE:
With or with single quotes makes no difference and rearranging the order of the parameters does not work either.
The order matters. I "think" in your query user is being called first before the correctUser due to the DLOOKUP function.
com.Parameters.AddWithValue("#user", userName);
com.Parameters.AddWithValue("#correctUser", correctUser);
You don't need to single quote parameters:
WHERE [User] = #user";
and I'll guess that the DLOOKUP doesn't need the single quotes either, just [brackets] if the field name has a space or is a reserved word (which [User] might be).
You will need to change that a bit, try:
OleDbConnection cn = new OleDbConnection(aconnectionstring);
cn.Open();
//testing
int correctUser = 1;
string userName = "1";
OleDbCommand com = new OleDbCommand();
com.Connection = cn;
//You cannot have a parameter in DLookUp
com.CommandText = "UPDATE [ExamMaster] SET [User] = " +
"DLookup('LName', 'Users', 'ID = " + correctUser + "') WHERE [User] = #user";
com.Parameters.AddWithValue("#user", userName);
//You must execute the query
com.ExecuteNonQuery();
How to check if my table is empty from C#?
I have something like:
public MySqlConnection con;
public MySqlCommand cmd;
con = new MySqlConnection(GetConnectionString());
con.Open();
cmd = new MySqlCommand("SELECT * FROM data;", con);
Or I don't need to call SELECT statement?
You can use COUNT(*) with no WHERE close and see if exactly how many rows exist with the result.
Or you can do a SELECT (id) FROM tablename with no WHERE clause and if no rows are returned then the table is empty.
I'll give you an example in C# good luck
public bool checkEmptyTable(){
try
{
MySql.Data.MySqlClient.MySqlCommand com = new MySql.Data.MySqlClient.MySqlCommand();
conn = new MySql.Data.MySqlClient.MySqlConnection("YOUR CONNECTION");
com.Connection = conn;
com.CommandText = "SELECT COUNT(*) from data";
int result = int.Parse(com.ExecuteScalar().ToString());
return result == 0; // if result equals zero, then the table is empty
}
finally
{
conn.Close();
}
}
If 'data' might be a big table you would be better with this (where pkdata is your primary key field)
SELECT COUNT(*) FROM data WHERE pkdata = (SELECT pkdata FROM data LIMIT 1);
This will run very quickly whether you have 0 rows in 'data' or millions of rows. Using SELECT with no WHERE or ORDER BY means it just pulls the first row available, LIMIT 1 stops it getting more than 1.
Maybe something to look for if you have a program that ran very quickly six months ago but now runs like a dog in treacle!
SELECT COUNT(*)
FROM table
WHERE `col_name` IS NOT NULL