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...
Related
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.
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);
I have a button which adds products to the invoice, I want it to delete products off the database as well, how can I edit this query so it deletes from the database?
I think my error is because of the way I am converting cmbQuantity.Text, can someone help me with a fix?
SqlCommand inventorycontrol = new SqlCommand("Update Product SET quantityAvailable=quantityAvailabe - '" + Convert.ToInt32(cmbQuantity.Text) + "' WHERE productName='" + cmbProdName.Text + "'", con);
Without the error message, it's hard to guess.
But at first sight, you have a typo here : quantityAvailable=quantityAvailabe - should be quantityAvailable=quantityAvailab**l**e -.
Moreover, you must not quote the integer part, so '" + quantityToRemove + "' becomes " + quantityToRemove + ". But the best is to use parametrization, which will simplify your code. See Why do we always prefer using parameters in SQL statements?
Try to separate access to your UI and building your SQL:
int quantityToRemove = Convert.ToInt32(cmbQuantity.Text);
string productName = cmbProdName.Text;
string sqlUpdate = #"UPDATE Product
SET quantityAvailable = quantityAvailable - #quantityToRemove
WHERE productName= #productName";
SqlCommand inventorycontrol = new SqlCommand(sqlUpdate, con);
inventorycontrol .Parameters.AddWithValue("quantityToRemove", quantityToRemove);
inventorycontrol .Parameters.AddWithValue("productName", productName);
In the question you have not specify the error, but there may be chances of getting error in your code. that i will clarify you.
When it failed to convert the cmbQuantity.Text to int, you need not to pass an integer within double quotes :- Here my suggested answer will help you to handle this error by showing error message if the quantity is invalid.
The query you are using opens a wide range to SQL Injection. I suggest you to use parameterized query to avoid injection, As a whole you can use like the following:
int quantity;
if (int.TryParse(cmbQuantity.Text, out quantity))
{
SqlCommand inventorycontrol = new SqlCommand("Update Product SET quantityAvailable=quantityAvailabe - #Quantity WHERE productName=#prodName", con);
inventorycontrol.Parameters.AddWithValue("#Quantity",quantity);
inventorycontrol.Parameters.AddWithValue("#prodName", cmbProdName.Text);
//Execue command here
}
else
{
// show message invalid quantity
}
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?
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 8 years ago.
Improve this question
i'm making GUI for a database (school project) and I have following problem - when i try to assign resul from select statement to variable i have strange error:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near ')'.
this is my code:
string sql2 = "SELECT * FROM Car WHERE Make = '#CarID' AND Model = '#CarID2');";
SqlCommand cmd3 = new SqlCommand(sql2, sqlconn);
cmd3.Parameters.AddWithValue("#CarID", model_cbo);
cmd3.Parameters.AddWithValue("#CarID2", make_cbo);
string CarID = cmd3.ExecuteScalar().ToString();
I've looking for the solution for a long time, but haven't found anything, so please help
This is my code for connection with DB:
public CarSpec()
{
InitializeComponent();
connectDB();
this.conn = new OleDbConnection("PROVIDER=SQLOLEDB;Data Source=HENIU;Initial Catalog=ServiceStation; Integrated Security=SSPI;");
conn.Open();
}
public void connectDB()
{
sqlconn = new SqlConnection(#"Data Source=HENIU; Initial Catalog=ServiceStation; Integrated Security=TRUE;");
sqlconn.Open();
da = new SqlDataAdapter();
}
There are three problems in your code:
There is a parenthesys not needed at the end of the WHERE clause
The parameters should be free from the single quotes. (Otherwise the will be treated as string literals)
The ExecuteScalar returns just a the first column of the first row.
You cannot be certain that this will be the carID.
Use instead
string sql2 = "SELECT * FROM Car WHERE Make = #CarID AND Model = #CarID2";
SqlCommand cmd3 = new SqlCommand(sql2, sqlconn);
cmd3.Parameters.AddWithValue("#CarID", model_cbo);
cmd3.Parameters.AddWithValue("#CarID2", make_cbo);
SqlDataReader reader = cmd3.ExecuteReader()
if(reader.Read())
{
int carID = Convert.ToInt32(reader["CarID"]);
}
Here I am assuming that a carID is a number and not a string (as it should be). However, if it is a string then you could change the line to
string carID = reader["CarID"].ToString();