ExecuteReader() Object cant be converted [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 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);

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.

Where is the sql syntax error? [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
it returns that I made a syntax error in my SQL statement cant find where, I used this syntax earlier and it worked... could you tell me where it is please ?
public static void addKc(KeyCeremony kc)
{
string ka = kc.ka;
string kc1 = kc.kc1;
string kc3 = kc.kc3;
string family = kc.family;
string so = kc.so;
string it = kc.it;
string desc = kc.desc;
using (OleDbConnection conn = new OleDbConnection(connecString))
{
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "INSERT INTO KC(Family, Kc1, Kc3, Ka, So, It, Desc) VALUES(#Family, #Kc1, #Kc3, #Ka, #So, #It, #Desc)";
cmd.Connection = conn;
conn.Open();
cmd.Parameters.AddWithValue("#Family", family);
cmd.Parameters.AddWithValue("#Kc1", kc1);
cmd.Parameters.AddWithValue("#Kc3", kc3);
cmd.Parameters.AddWithValue("#Ka", ka);
cmd.Parameters.AddWithValue("#So", so);
cmd.Parameters.AddWithValue("#It", it);
cmd.Parameters.AddWithValue("#Desc", desc);
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Insertion OK");
}
catch (Exception)
{
throw;
}
conn.Close();
}
}
}
hope you will find it faster than me
Desc is a keyword. Change to this: [Desc].
All Keywords in SQL:
https://www.drupal.org/docs/develop/coding-standards/list-of-sql-reserved-words

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

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

Missing Rows Property in SqlDataReader [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 years ago.
Improve this question
public bool ValidateUser(string uName)
{
SqlCommand cmd = new SqlCommand();
if (connection == null)
{
connection = connectToDB();
}
cmd.Connection = connection;
cmd.CommandText = "Select * from Users where UserName='" + uName + "'";
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.Rows.Count > 0)
{
return true;
}
else
{
return false;
}
I wrote the code in my data access layer but it was giving error on rows to count the columns.
Error:
'System.Data.SqlClient.SqlDataReader' does not contain a definition for 'Rows' and no extension method 'Rows' accepting a first argument of type 'System.Data.SqlClient.SqlDataReader' could be found (are you missing a using directive or an assembly reference?)
Use HasRows instead because SqlDataReader doesn't have a property call Rows.
if (dr.HasRows)
{
return true;
}
However, if you want the count instead you may load it into a datatable
DataTable dt = new DataTable();
dt.Load(dr);
int num = dt.Rows.Count;
SqlDataReader does not have a Rows Property.
Perhaps consider the HasRows property of SqlDataReader
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.hasrows.aspx
There is no Rows property in an SqlDataReader.
But your code has many problems.
I would change your code in this way:
public bool ValidateUser(string uName)
{
using(SqlConnection cn = connectToDB())
using(SqlCommand cmd = new SqlCommand("Select count(*) from Users where UserName=#name", cn))
{
cmd.Parameters.AddWithValue("#name", uName);
return (Convert.ToInt32(cmd.ExecuteScalar()) > 0)
}
}
The connection object is no more global and it is destroyed in
closing of the using statement.
No need to use a DataReader just to find out if the user exists or
not
Using a parameterized query to avoid SQL Injection on the input data
Avoid a global connection object. There is the connection pooling infrastructure that removes any performance problem and you are safe from excessive resource usage.
The SqlDataReader is a good choice when you need to retrieve sequentially a lot of records, but to get just the information if the user exists or not the best approach is through the ExecuteScalar method and an appropriate sql.
The parameterized query is a must for every serious database work. It will pass the work to format your input to the framework and you don't risk an Sql Injection

Categories