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);
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 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...
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 7 years ago.
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.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I am trying to enter the value of a textbox in c# into a field in a database that I have in access. For some reason I keep getting the error saying:
'An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: Syntax error in INSERT INTO statement.'
Can't quite see what is wrong, this is the first time I have attempted to do this in a project so I am not too experienced with it. This is my code:
OleDbConnection connection = new OleDbConnection(CONNECTION STRING GOES HERE);
connection.Open();
string playerName = textBox[i].Text;
string query = "INSERT INTO (TotalPlayerName)(Player Name) VALUES(" + playerName + ")";
OleDbCommand command = new OleDbCommand(query, connection);
command.ExecuteNonQuery();
if it helps then the database is called 'Database' the table is called 'TotalPlayerName' and the field is called 'Player Name'
The correct code to do your task is
string cmdText = "INSERT INTO TotalPlayerName ([Player Name]) VALUES(?)";
using(OleDbConnection connection = new OleDbConnection(...))
using(OleDbCommand command = new OleDbCommand(cmdText, connection))
{
connection.Open();
command.Parameters.Add("#p1", OleDbType.VarWChar).Value = textBox[i].Text;
int result = command.ExecuteNonQuery();
if(result > 0)
MessageBox.Show("Record Inserted");
else
MessageBox.Show("Failure to insert");
}
This approach fixes three problems:
The connection and the command object should be disposed at the end
(see using statement)
Every value that you need to pass to the query should be passed as
parameter
If a field name (or table name) has embedded spaces you should enclose
it between square brackets
(The messages below the ExecuteNonQuery are there only as an example to check the return value of ExecuteNonQuery)
Remember also that if your table has more than this field and some of the other fields don't accept null values you should provide some value also for them.
For example
string cmdText = #"INSERT INTO TotalPlayerName ([Player Name], FieldB)
VALUES(?, ?)";
command.Parameters.Add("#p1", OleDbType.VarWChar).Value = textBox[i].Text;
command.Parameters.Add("#p2", OleDbType.VarWChar).Value = "ValueForFieldB";
Just remember to strictly follow the order of the ? when you add your parameter values
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();