how to assign select result to variable c# [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 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();

Related

What is the reason for my SqlException: Incorrect syntax near '='? [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 1 year ago.
Improve this question
This is my code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "data source = LAPTOP-ULT25NKH; database = college;integrated security = True";
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select * from teacher where tID = " + textBox1.Text + "";
DataSet DS = new DataSet();
SqlDataAdapter DA = new SqlDataAdapter(cmd);
DA.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];
}
but I get this exception:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Incorrect syntax near '='."
Ensure you are properly santizing inputs and using prepared statements; to start down the line for you, try:
cmd.CommandText = "SELECT * FROM teacher WHERE tID = #tID;"
SqlParameter idParam = new SqlParameter("#tID", SqlDbType.NVarChar , 0);
idParam.Value = textBox1.Text;
cmd.Parameters.Add(idParam);
cmd.Prepare();
There are lot of issues in your existing code, I’m mentioning few points brlow.
Please move the connection string to some config file, it’s easy to maintain there.
When you have DataAdapter you don’t need to explicitly open the connection, it does that for you internally.
Please avoid * in select query, mention the columns with alias and use parameterized query to pass the parameters. Or your can write stored procedure and call it. So that I if I’m future you need to modify query, there will be no code change.
If you need to open the connection, please close it or your can use using.
You can add breakpoint and see the value of your query and if you copy this query value and run in sql server directly . This is one way to find the error in the query.

'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.

ExecuteReader() Object cant be converted [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 have set up a mySql database on a server, and now i want to reach it in order for me to make a webservice. Firstly i just want to test if i can grab an entity from my query in my method (OneEntity), and put it into my list.
public IEnumerable<Person> Get()
{
return new List<Person> {
new Person{ ID = 0, First = OneEntity(), Last ="Example"}
};
}
public string OneEntity()
{
MySql.Data.MySqlClient.MySqlConnection mySqlConnection;
MySql.Data.MySqlClient.MySqlCommand cmd;
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["MySql"].ToString();
mySqlConnection = new MySql.Data.MySqlClient.MySqlConnection(connString);
cmd = new MySql.Data.MySqlClient.MySqlCommand();
cmd.CommandText = "SELECT 'name' FROM 'CustomerDb' WHERE 'id' = 0";
cmd.CommandType = CommandType.Text;
cmd.Connection = mySqlConnection;
mySqlConnection.Open();
SqlDataReader reader = cmd.ExecuteReader();
mySqlConnection.Close();
return reader;
}
I am not very experienced in c# and are therefore not sure if im doing it correct. However in my cmd.ExecuteReader() (Object i guess it is?!??!) i get that it
cannot implicitly convert type 'MySql.Data.MySqlDataReader' to
'System.Data.SqlClient.SqlDataReader'
What am i doing wrong here?? obviously my return is not correct either, as i specified my method to be 'string'.. but even though i type in a string, the error doesn't dissapear?
you shoud use MySqlDataReader not SqlDataReader
MySqlDataReader Reader = cmd.ExecuteReader();
code should return string not the reader in your case.
To return the first item use this return reader.GetString(0);

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);

c# to Access INSERT INTO query not working [closed]

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

Categories