C#, trouble with SQLreader/command - c#

I have some trouble with the SqlDataReader:
public string GetVareNavn(string streg)
{
string navn = "";
SqlConnection myCon = DBcon.getInstance().conn();
string query =
"SELECT Navn FROM Vare WHERE Stregkode = ) Values('" + streg + "')";
myCon.Open();
SqlCommand com = new SqlCommand(query, myCon);
Console.WriteLine("navn: "+navn);
SqlDataReader dr = com.ExecuteReader();
if (dr.Read())
{
navn = dr.GetString(1);
}
myCon.Close();
return navn;
}
It throws an exception at com.ExecutiveReader(); and the exception is:
Incorrect syntax near ')'.
I don't know why this one doesn't work right now, because I've used it in another project.

Your query looks like it was copied from something that used to be an INSERT statement; you don't need the VALUES... clause at the end of the statement. Try changing your query to:
string query =
"SELECT Navn FROM Vare WHERE Stregkode = #streg";
Then modify this code to use the parameter:
SqlCommand com = new SqlCommand(query, myCon);
com.Parameters.AddWithValue("#streg", streg);

It doesn't work because your SQL is broken:
SELECT Navn FROM Vare WHERE Stregkode = ) Values('" + streg + "')"
What did you expect that WHERE clause to do, and what values are you trying to use? It looks like you've got a broken copy/paste from an update command.
Additionally, you shouldn't put values into your SQL like that anyway - you should use parameterized queries to avoid SQL injection attacks (and to avoid formatting issues etc).

Ya, surely it will give. Why you put the Values in your select query? which is wrong syntax, Try Now.
string query = "SELECT Navn FROM Vare WHERE Stregkode = '" + streg + "'";

Related

Get value instead of whole query

I want to get the value of the Encrypted password into a string variable. but I am getting the whole query.
Here is my code:-
string strpassword = "select sys.get_enc_val ('" + txtpassword.Text + "', 'F20FA982B4C2C675') from dual";
Response.Write(strpassword);
In strpassword i get the whole query.
But in Toad the result is as
F52377D5FFB1A47F
how to get that in oracle?
When you write
string strpassword = "select sys.get_enc_val ('" + txtpassword.Text + "', 'F20FA982B4C2C675') from dual";
Response.Write(strpassword);
Then you are simply displaying the string value as you are not executing the SQL which is present inside the string.
What you are looking for is the result of the SQL which is present inside the string. To get the result of the SQL stored inside the string you need to execute it.
You can try like this:
string queryString = "select sys.get_enc_val ('" + txtpassword.Text + "', 'F20FA982B4C2C675') from dual";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
try
{
while (reader.Read())
{
Console.WriteLine(String.Format("{0}",reader[0]));
}
}
finally
{
reader.Close();
}
}
As commented above, your query is prone to SQL Injection. A better way is to use paramterized query to get rid of it. Something like
string sql = "select sys.get_enc_val (#myvar) from dual";
SqlConnection connection = new SqlConnection(/* connection info */);
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("myvar", txtpassword.Text);

How to display numeric value selected from MS Access in the MessageBox()?

Why does my code show the message
Data type mismatch in criteria expression.
My code:
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string cq = "select sum(Fine) from studentbook where S_ID=" + textSID.Text + "";
command.CommandText = cq;
int a = Convert.ToInt32(command.ExecuteReader());
connection.Close();
MessageBox.Show(a.ToString());
Change code like this:
where S_ID = '" + textSID.Text + "'
Also use command.ExecuteScalar() instead of command.ExecuteReader():
int a = Convert.ToInt32(command.ExecuteScalar());
You should always use parameterized queries by the way. This kind of string concatenations are open for SQL Injection.

Paramaterized Query With SQL Data Reader C#

I know that non parameterized queries are frowned upon because of SQL injection. Well, I have a lot of queries in my application that are susceptible to SQL injection. I just can't seem to wrap my head around doing it with SqlDataReader. I am able to do it with ExecuteNonQuery just not SQLDataReader.
Can someone give me some pointers and or examples of the best way to do this, the query is executing and returning exactly what it should, I just want to make it as secure as possible....
Code:
string myQuery = "Select [shoeSize] AS 'Shoe Size', [shoeBrand] AS 'Shoe Brand' FROM [myTable] "
+ "WHERE [customerName] = '" + customer + "' AND " + "[customerPin] = '" + customerID + "'";
sqlCmd = new SqlCommand(myQuery, conn);
sqlCmd.Connection.Open();
SqlDataReader rdr2 = sqlCmd.ExecuteReader();
if (rdr2.HasRows)
{
rdr2.Read();
shoeSize= rdr2["Shoe Size"].ToString();
shoeBrand= rdr2["Shoe Brand"].ToString();
}
conn.close();
There you go
string myQuery = "Select [shoeSize] AS 'Shoe Size', [shoeBrand] AS 'Shoe Brand' FROM [myTable] "
+ "WHERE [customerName] = #customerName AND [customerPin] = #customerID"
sqlCmd = new SqlCommand(myQuery, conn);
sqlCmd.Connection.Open();
sqlCmd.Parameters.AddWithValue("#customerName", customerName);
sqlCmd.Parameters.AddWithValue("#customerID", customerID");
--rest stays the same as before
Whereas #customerName and #customerID are now your parameters. So even if the customer's name should be something like "Bigler, Fabian' DROP TABLE [myTable]" it will not work. It completely removes the possibility of "evil" input changing the meaning of your query.
Non-parameterized queries are not simply 'frowned upon'. It can be disastrous for you, your company and - of course - your customer.
Like this:
string myQuery = "Select [shoeSize] AS 'Shoe Size', [shoeBrand] AS 'Shoe Brand' FROM [myTable] "
+ "WHERE [customerName] = #customerName AND [customerPin] = #customerPin";
sqlCmd = new SqlCommand(myQuery, conn);
sqlCmd.Connection.Open();
sqlCmd.Parameters.Add("#customerName", SqlDbType.NVarChar, 50).Value = customer;
sqlCmd.Parameters.Add("#customerPin", SqlDbType.NVarChar, 20).Value = customerID;
SqlDataReader rdr2 = sqlCmd.ExecuteReader();
if (rdr2.HasRows)
{
rdr2.Read();
shoeSize = rdr2["Shoe Size"].ToString();
shoeBrand = rdr2["Shoe Brand"].ToString();
}
conn.close();

Incorrect syntax near ' '

This is the page behind code where it have error
if (Session["username"] != null)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["registerCS"].ConnectionString;
string sql1 = "Select pemgrp from Profile where userID = '" + Session["username"].ToString() + "'";
string sql = "Select studname from Profile where pemgrp = '" + sql1 + "'";
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
DataTable dt = new DataTable();
cmd.CommandText = sql;
cmd.Connection = con;
//open connection and execute command
con.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
lb_classmates.Text = dr[0].ToString();
}
}
However, when i run, it give me this error :
Incorrect syntax near the keyword 'where'.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Incorrect
syntax near the keyword 'where'.
As you are using sub-query therefore this
string sql = "Select studname from Profile where pemgrp = '" + sql1 + "'";
should be
string sql = "Select studname from Profile where pemgrp in (" + sql1+ ")";
and you should be using Parametereized queries to avoid SQL injection.
I think It should be
string sql = "Select studname from Profile where pemgrp in (" + sql1+ ")";
instead of
string sql = "Select studname from Profile where pemgrp = '" + sql1 + "'";
I would strongly recommend you to use parametereized queries
No One's answer is of course right.
If you want to use a subquery in a query, you should use IN (Transact-SQL)
Determines whether a specified value matches any value in a subquery
or a list.
test_expression [ NOT ] IN
( subquery | expression [ ,...n ]
)
Also you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also consider to use using to dispose your SqlConnection.
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["registerCS"].ConnectionString))
{
connection.Open();
string sql1 = "Select pemgrp from Profile where userID = #username";
string sql = "Select studname from Profile where pemgrp IN (" + sql1 + ")";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("#username", Session["username"].ToString());
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//
}
}
You should use parameterized query something llike this
string sql = "Select studname from Profile where pemgrp = #p1";
and to pass parameter
command.Parameters.AddWithValue("#p1",sql1);

How to make a filtration by a parameter in CommandText in C#?

I would like to fill a ComboBox but I want to sort data by one parameter called “id_group”.
I wrote a code but it does not work.
In this line happens an exception which says “incorrect syntax” :
SqlDataReader sd = sc.ExecuteReader();
This is all my code:
int id_group=5;
SqlConnection conn = new SqlConnection();
SqlCommand sc = conn.CreateCommand();
sc.CommandText = "SELECT STUDENT FROM FACULTY WHERE ID_GROUP '" + id_group + "'";
conn.Open();
SqlDataReader sd = sc.ExecuteReader(); //this happens exception - "incorrect syntax"
while (sd.Read())
{
string graduate = (string)sd["STUDENT"];
Student_comboBox.Items.Add(graduate);
}
conn.Close();
How to make it work?
Is there other ways to filter data by a parameter?
actually you are missing = on your query, so this should looked like this,
sc.CommandText = "SELECT STUDENT FROM FACULTY WHERE ID_GROUP = '" +
id_group + "'";
but please do parameterize it to avoid SQL Injection
sc.CommandText = "SELECT STUDENT FROM FACULTY WHERE ID_GROUP = #groupID";
sc.Parameters.AddWithValue("#groupID", id_group);
SOURCE
AddWithValue
Add (recommended to use)

Categories