Where clause throws error [closed] - c#

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Why does this code throw an error?
using (MySqlConnection cn = new MySqlConnection(VarribleKeeper.MySQLConnectionString))
{
{
MySqlCommand Command = new MySqlCommand();
Command.Connection = cn;
Command.CommandText = "UPDATE TeleworksStats SET Ja= ('" + JaTak +
"') WHERE Brugernavn = " + VarribleKeeper.Brugernavn + "' AND Dato = " +
DateTime.Today.ToString("yyyy-MM-dd") + "";
cn.Open();
Command.ExecuteNonQuery();
//Ryd op
Command.Dispose();
cn.Close();
}
}

Rather than just forgetting ' for the value of Brugernavn column and both single quotes for Dato column, I think you have more things to keep in mind.
Use using statement to dispose your Command object as you did for your connection instead of calling Close or Dispose methods manually.
Use paramterized queries instead of string concatenation. This kind of codes are open for SQL Injection attacks.
Looks like you try to save your DateTime values with their string representations. Do not do that! If you wanna keep your DateTime values to your database, you need to pass them directly. Change your Dato column to DateTime type. Read: Bad habits to kick : choosing the wrong data type
using(var cn = new MySqlConnection(VarribleKeeper.MySQLConnectionString))
using(var Command = cn.CreateCommand())
{
Command.CommandText = #"UPDATE TeleworksStats SET Ja = #Ja
WHERE Brugernavn = #Brugernavn AND Dato = #Dato";
Command.Parameters.Add("#Ja", MySqlDbType.VarChar).Value = JaTak;
Command.Parameters.Add("#Ja", MySqlDbType.VarChar).Value = VarribleKeeper.Brugernavn;
Command.Parameters.Add("#Ja", MySqlDbType.DateTime).Value = DateTime.Today;
// I assumed your column types. You should write proper column types instead.
cn.Open();
Command.ExecuteNonQuery();
}

You missed one quote ' after Brugernavn = and Dato:
Brugernavn = "... '" + VarribleKeeper.Brugernavn + "' AND Dato = '" +
DateTime.Today.ToString("yyyy-MM-dd") + "'";
Also I strongly recommend that you always use parameterized queries to avoid SQL Injection like this:
Command.CommandText =
"UPDATE TeleworksStats SET Ja = #Ja WHERE Brugernavn = #Brugernavn and ...";
Command.Parameters.AddWithValue("#Ja", JaTak);
Command.Parameters.AddWithValue("#Brugernavn", VarribleKeeper.Brugernavn);
Although specify the type directly and use the Value property is more better than AddWithValue. Check this: Can we stop using AddWithValue() already?

Related

Deleting and updating tables in Microsoft SQL Server using C# [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
I am using the following code to add items to the table but I have troubles deleting or updating items in the table. I am trying commands like
delete from MyTable
values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "',)";
and the command is accepted but the item is not deleted.
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into MyTable values('" + textBox1.Text + "','" + textBox2.Text + "','" + textBox3.Text + "',)";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Item inserted");
It is a bit hard to find resources since google just shows, sql or mysql when I try to search for a solution.
Why would you expect an SQL command based on the INSERT keyword to delete a record?
using var con = new SqlConnection(" ... ");
using var cmd = con.CreateCommand();
cmd.CommandText = #"
DELETE
FROM MyTable
WHERE MyColumn= #SomeValue";
cmd.Parameters.Add("#SomeValue", SqlDbType.Int).Value = textBox1.Text;
con.Open();
cmd.ExecuteNonQuery();
// No need to call con.Close();. The using directive takes care of it.
Pay special attention to how I used a query parameter. The string concatenation technique in the question is NEVER okay, and is the easiest way I've seen to find out a year from now you were hacked six months ago.
To change (update) a record, you must write an UPDATE query:
using var con = new SqlConnection(" ... ");
using var cmd = con.CreateCommand();
cmd.CommandText = #"
UPDATE MyTable
Set SomeColumn = #SomeValue
WHERE SomeOtherColumn = #SomeOtherValue";
cmd.Parameters.Add("#SomeValue", SqlDbType.Int).Value = textBox2.Text;
cmd.Parameters.Add("#SomeOtherValue", SqlDbType.Int).Value = textBox1.Text;
con.Open();
cmd.ExecuteNonQuery();
// No need to call con.Close();. The using directive takes care of it.
The thing to understand about this is you do not delete or update a record by specifying all the fields in a VALUES() clause, as you would with an INSERT. Instead, you use a WHERE clause and only need to include enough for the conditional expressions to identify which row(s) you want to change or delete. An UPDATE statement will then further specify what to change via the SET clause.

'Incorrect syntax near '2'.' [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Im trying to retrieve no of rows from sql based user input & display in gridview
Please help!
Int32 text = Convert.ToInt32(this.Txtusers.Text);
con.Open();
cmd = new SqlCommand("select TOP '" + text + "' * from Avaya_Id where LOB = '" + DDLOB.SelectedItem.Value + "' and Status = 'Unassigned'", con);
SqlDataReader rdr = cmd.ExecuteReader();
GridView1.DataSource = rdr;
GridView1.DataBind();
con.Close();
Here is how it should be written.
int text;
if(int.TryParse(this.Txtusers.Text, out text)
{
using(var con = new SqlConnection(connectionString)
{
using(var cmd = new SqlCommand("select TOP (#top) * from Avaya_Id where LOB = #LOB and Status = 'Unassigned'", con))
{
cmd.Parameters.Add("#top", SqlDbType.Int).Value = text;
cmd.Parameters.Add("#LOB", SqlDbType.Int).Value = DDLOB.SelectedItem.Value;
con.Open();
using(var rdr = cmd.ExecuteReader())
{
GridView1.DataSource = rdr;
GridView1.DataBind();
}
}
}
}
Points of interest:
Using parameters to avoid the risk of Sql Injection.
Changed Convert.ToInt32 to int.TryParse. Never trust user input.
Use the using statement for every instance that implements the IDisposable interface.
Please note that using top x without an order by clause means you get x arbitrary records from the database - since database tables are unordered by nature and the only way to ensure the order of the rows returned from a select statement is to use the order by clause.
Please note I've guessed that the second parameter is an int, if it's not, change the data type.

System.IndexOutOfRangeException: 'counter' - beginner [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I've got a database that has two columns both are of type int.
One column is called "id" and the other "counter".
Im using an SQLDataReader to read from the database
int id = (int)reader3["id"];
int counter = (int)reader3["counter"];
The first variable "id" returns the id value of the column fine. But the second variable stops the execution with a System.IndexOutOfRangeException: 'counter' error.
I cant really debug this error as counter does not exist in the current context.
con.Open();
SqlCommand cmd2 = new SqlCommand("SELECT id FROM categoryData WHERE CONVERT(DATE,Date) = CONVERT(DATE,GETDATE(),103) AND category = '" +
categoryList[i] + "'", con);
cmd2.ExecuteNonQuery();
SqlDataReader reader3 = cmd2.ExecuteReader();
while (reader3.Read())
{
int id = (int)reader3["id"];
int counter = (int)reader3["counter"];
cmd2.Parameters.Clear();
con.Open();
cmd2 = new SqlCommand("UPDATE categoryData SET counter = counter+1 WHERE
id = " + id + "", con);
cmd2.ExecuteNonQuery();
dateLabel.Text = categoryBox.SelectedItem.ToString();
recordedLabel.Text = "Count is: " + counter;
break;
}
The error actually means the your select statement does not contain a column named counter in it from whatever table you are selecting the data.
So what you need to do is carefully check your query that it is returning a column named counter of type int.
The query associated with reader3 should be something like:
select id, counter from categoryData
where .......
UPDATE:
So from your updated questions it is quite clear now that you are not selecting counter column in your query which probably you missed when adding query, so it should be :
SqlCommand cmd2 = new SqlCommand("SELECT id,counter FROM categoryData WHERE
CONVERT(DATE,Date) = CONVERT(DATE,GETDATE(),103) AND category = '" +
categoryList[i] + "'", con);
Important Caution!
and one more thing that is important here is that do not do string concatenation in your queries, instead use Parameterized queries to be safe from SQL Injection.
Following would be the code to with Parameterized query :
SqlCommand cmd2 = new SqlCommand("SELECT id,couter FROM categoryData WHERE CONVERT(DATE,Date) = CONVERT(DATE,GETDATE(),103) AND category = #category",con);
cmd2.Parameters.AddWithValue("#category", categoryList[i]);
cmd2.ExecuteNonQuery();
Hope it helps!
Your problem is your query.
"SELECT id FROM categoryData ..." "counter" isn't one of your fields you're retrieving. It needs to say:
"SELECT id, counter FROM categoryData ..."
SELECT id, counter FROM categoryData WHERE...
EDIT: string concatenation in SqlQuery is not the best idea, this can be use to SqlInjection...

How to INSERT INTO access database with c# [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am trying to add data to my access database from winform using c#.
I keep getting a syntax error regarding my INSERT INTO statement and cannot see where I am going wrong.
Please can someone review my code and tell me where I am going wrong.
private void btnLog_Click(object sender, EventArgs e)
{
txtStatus.Text = "Open";
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\mwool\\Desktop\\Uni\\3rd Year\\SEM 1\\AP\\Assignment\\Staff.accdb";
string sql = "INSERT INTO Fault (faultType, Status, TechId, StaffId, Zone, Description) VALUES ('" + txtFaultType.Text + "', '" + txtStatus.Text + "', " + txtTechId.Text + "' , '" + txtStaffId.Text + "' , '" + txtZone.Text + "' , '" + txtDescription.Text + "')";
OleDbCommand add = new OleDbCommand();
add.CommandText = sql;
add.Connection = conn;
add.Connection.Open();
add.ExecuteNonQuery();
conn.Close();
}
You missed a single quote before txtTechId.Text. However you should always use parameterized queries to avoid SQL Injection.
string sql = "INSERT INTO Fault (faultType, Status, TechId, StaffId, Zone, Description) VALUES (#a,#b,#c,#d,#e,#f)";
add.Parameters.AddWithValue("#a", txtFaultType.Text);
add.Parameters.AddWithValue("#b", txtStatus.Text);
add.Parameters.AddWithValue("#c", txtTechId.Text);
add.Parameters.AddWithValue("#d", txtStaffId.Text);
add.Parameters.AddWithValue("#e", txtZone.Text);
add.Parameters.AddWithValue("#f", txtDescription.Text);
Always use parameterized queries. This prevents simple mistakes like forgetting a ' with a string but more importantly prevents sql injection attacks.
Also always wrap your database connections, commands, and any other Disposable objects in using blocks.
Your code refactored with using statements and parameterized inputs.
using (OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\mwool\\Desktop\\Uni\\3rd Year\\SEM 1\\AP\\Assignment\\Staff.accdb"))
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = string sql = "INSERT INTO Fault (faultType, Status, TechId, StaffId, Zone, [Description]) VALUES (?, ?, ?, ?, ?, ?)";
cmd.Parameters.Add(new OleDbParameter("#faultType", OleDbType.VarChar)).Value = txtFaultType.Text;
cmd.Parameters.Add(new OleDbParameter("#Status", OleDbType.VarChar)).Value = txtStatus.Text;
// this parameter is an example of passing an int instead of a string. Alwaysuse the correct types!
cmd.Parameters.Add(new OleDbParameter("#TechId", OleDbType.Int)).Value = int.Parse(txtTechId.Text);
cmd.Parameters.Add(new OleDbParameter("#StaffId", OleDbType.VarChar)).Value = txtStaffId.Text;
cmd.Parameters.Add(new OleDbParameter("#Zone", OleDbType.VarChar)).Value = txtZone.Text;
cmd.Parameters.Add(new OleDbParameter("#Description", OleDbType.VarChar)).Value = txtDescription.Text;
con.Open();
cmd.ExecuteNonQuery();
}
OleDbCommand does not support named parameters, see OleDbCommand.Parameters
Remarks
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used.
Also note that:
OleConnection and OleDbCommand are wrapped in using blocks so they are disposed/cleaned up even when an exception occurs.
Parameters are now used instead of hard coding the string values
Parameters use the correct data types
It might be that the use of Description is not allowed because it is a reserved word (see link). In that case surround it with [] (see update above).

Invalid column name 'e01' in SQL query [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
i have database contain column name Code data type nvarchar(50) i connected to my database by c# and created a SQL command as
string code = "e01";
SqlCommand command = new SqlCommand("select * from inv where code = " + code + ";", conn);
SqlDataReader reader = command.ExecuteReader();
i found an error says
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Invalid column name 'e01'.
and if i but number instead of e01 it work fine ..
your are missing quotes. Try this:
string code = "e01"
SqlCommand command = new SqlCommand("select * from inv where code = '" + code + "';", conn);
SqlDataReader reader = command.ExecuteReader();
Also, it's recomended use parameters instead concatenating values. This avoid sql injection attacks or sql errors if your code contains special characters, like quotes:
SqlCommand command = new SqlCommand("select * from inv where code = #pCode", conn);
command.Parameters.Add(new SqlParameter("#pCode", code));
SqlDataReader reader = command.ExecuteReader();
You forgot to put quotes around your column value, because e01 is a value and not a column it needs to be surrounded by single quotes.
SqlCommand command = new SqlCommand("select * from inv where code = '" + code + "';", conn);

Categories