assign the variable with MySql - c#

I want to assign my variable [vPrenom_id_obtenu] by the value that I get in my MySql DB ...
With the following code, I receive an error message :
does not contain a definition for 'ExecuteScalar' ....
string vFistNam_id_get;
string connDataBaseStr = "server=myserver;user=####;database=myDataBase;port=3306;password=dsdfsdfsdf123;";
string sqlDataBaseSelect = "SELECT column_fistname_id FROM table_identy WHERE column_famillyname='" + vFamillyName + "'";
MySqlConnection connDataBase = new MySqlConnection(connDataBaseStr);
connDataBase.Open();
vFistNam_id_get = (string)connDataBase.ExecuteScalar();
connDataBase.Close();
How can I retrieve the value that is in "column_fistname_id"?
The type of two columns of my table
Le type de deux colonnes de ma table [column_fistname_id] and [column_famillyname] is «text'.

ExecuteScalar is a method to call on an instance of a MySqlCommand not of a MySqlConnection
The right way to go is:
using(MySqlConnection connDataBase = new MySqlConnection(connDataBaseStr))
{
connDataBase.Open();
MySqlCommand cmd = new MySqlCommand(sqlDataBaseSelect, connDataBase);
vFistNam_id_get = (string)cmd.ExecuteScalar();
}
However your code is wrong for another reason.
this sql string
string sqlDataBaseSelect = "SELECT column_fistname_id FROM table_identy " +
"WHERE column_famillyname='" + vFamillyName + "'";
leads the way to SqlInjection
You should rewrite it in this way
string sqlDataBaseSelect = "SELECT column_fistname_id FROM table_identy " +
"WHERE column_famillyname=?family";
and then before calling ExecuteScalar add a Parameter to the command
cmd.Parameters.AddWithValue("?family", vFamillyName);
And as added value you don't have to worry about datatype delimiter (single quote in this case)

You need to use MySqlCommand to use ExecuteScalar. You're also missing the SQL in your source code, i.e. select * from something, or a stored proc name.
public static int GetNumRows(String OrchardName)
{
// Create Connection
MySqlConnection con = new MySqlConnection(_connectionString);
// Create Command
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = con;
cmd.CommandText = "SELECT COUNT(*) FROM orchards WHERE OrchardName = #OrchardName";
cmd.Parameters.Add("#OrchardName", OrchardName);
// Return Count
con.Open();
Int32 NumRows = (Int32)cmd.ExecuteScalar();
return NumRows;
}

Example:
MySqlConnection connDataBase = new MySqlConnection(connDataBaseStr);
connDataBase.Open();
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT column_fistname_id FROM table_identy WHERE column_famillyname='" + vFamillyName + "'";
MySqlDataReader reader = command.ExecuteReader();
string vFistNam_id_get = null;
while (reader.Read())
{
vFistNam_id_get = (int)reader["column_fistname_id"];
}

You're using the ADO.NET types wrong. The easiest thing to do would be to use the MySqlHelper static methods, like this:
string vFistNam_id_get = (string)
MySqlHelper.ExecuteScalar(dbConnString, "select `col1` from `table1`");

Related

System.Data.SqlClient.SqlException: 'Incorrect syntax near '='.' on Datatable and object

I've looked at a lot of similar questions on this site and elsewhere but none of them have helped me.
I'm trying to make a database connection with a query but I get the error
System.Data.SqlClient.SqlException: 'Incorrect syntax near '='.'
on 2 different lines of code. I've tried to use spaces in the query around the = but that doesn't help.
Code 1 is:
string connectieString = dbConnection();
SqlConnection connection = new SqlConnection(connectieString);
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#attackCategory", SqlDbType.NChar).Value = attackCategory;
select.Parameters.Add("#taughtOn", SqlDbType.NVarChar).Value = taughtOn;
select.CommandText = "SELECT ID, Name FROM attackCategory = #attackCategory WHERE TaughtOn = #taughtOn";
using (SqlDataAdapter sda = new SqlDataAdapter(select.CommandText, connection))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
The exception is thrown on the sda.Fill(dt); line of code. This code works if no parameters are used in the query:
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn ='" + taughtOn + "'";
And code 2 is:
string connectieString = dbConnection();
SqlConnection connection = new SqlConnection(connectieString);
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#attackCategory", SqlDbType.NVarChar).Value = attackCategory;
select.Parameters.Add("#ID", SqlDbType.Int).Value = id;
select.CommandText = "SELECT Name FROM attackCategory = #attackCategory WHERE ID = #ID";
connection.Open();
object name = select.ExecuteScalar();
connection.Close();
return name;
The exception fires on the object name = select.ExecuteScalar(); line of code. This code works if 1 parameter is used in the query:
select.Parameters.Add("#ID", SqlDbType.Int).Value = id;
select.CommandText = "SELECT Inhabitants FROM Planet WHERE ID=#ID";
You cannot provide table name has parameter, parameter applies in where clause with columns value.
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn ='" + taughtOn + "'";
but, we need to simplify to use parameter in this query.
SqlCommand select = new SqlCommand();
select.Connection = connection;
select.Parameters.Add("#taughtOn", SqlDbType.VarChar,50).Value = taughtOn;
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn =#taughtOn";
select.CommandText = cmd;
In the above tsql query, string concatenation applies and table name is included in the string, which will work.
Edit:-
I get it why you the sqlDataAdapter is not Recognizing the parameter.
Reason is you have not provided it. Yes, That's right you have provided the CommandText and not the Command Object which is of select variable.
I have corrected your code.
select.Parameters.Add("#taughtOn", SqlDbType.VarChar, 50).Value = taughtOn;
string cmd = #"select ID, Name from " + attackCategory + " where TaughtOn =#taughtOn";
select.CommandText = cmd;
select.Connection = new SqlConnection("provide your sql string");
using (SqlDataAdapter sda = new SqlDataAdapter(select))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Hope this helps !!
You can't bind object names like that. For object names, you'll have to resort to some sort of string concatenation. E.g.:
select.Parameters.Add("#taughtOn", SqlDbType.NVarChar).Value = taughtOn;
select.CommandText = "SELECT ID, Name FROM " + attackCategory + " WHERE TaughtOn=#taughtOn";
Note:
This is an over-simplified solution that does nothing to mitigate the risk of SQL-Injection attacks. You'll need to sanitize attackCategory before using it like this.

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.

How to show SQL query result in a Textbox?

I have the following code:
dbConnection cn = new dbConnection();
SqlCommand cmd = new SqlCommand();
protected void dropdown_student_SelectedIndexChanged(object sender, EventArgs e)
{
string StudentGUID = dropdown_student.SelectedValue;
cn.con.Open();
cn.cmd.Connection = cn.con;
cn.cmd.CommandText = "select SUM(Marks) AS 'Total' from Marksheet where StudentGUID = " + StudentGUID + " ";
dr = cn.cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
textbox_total.Text = dr["Total"].ToString();
}
cn.con.Close();
}
}
I want to show the total marks value in the textbox but it does not work. Can anyone point me in the right direction?
Try something like this:
// define your query upfront - using a PARAMETER!
string query = "SELECT SUM(Marks) FROM dbo.Marksheet WHERE StudentGUID = #StudentID;";
// put the SqlConnection and SqlCommand into using blocks
using (dbConnection cn = new dbConnection())
using (SqlCommand cmd = new SqlCommand(query, cn))
{
// define the parameter value
cmd.Parameters.Add("#StudentID", SqlDbType.UniqueIdentifier).Value = dropdown_student.SelectedValue;
cn.Open();
// use ExecuteScalar if you fetch one row, one column exactly
object result = cmd.ExecuteScalar();
cn.Close();
if(result != null)
{
int value = (int)result;
textbox_total.Text = value.ToString();
}
}
You SQL query is wrong. Try like below:
string query = string.Format("SELECT SUM(Marks) FROM dbo.Marksheet WHERE StudentGUID = '{0}';", StudentID);
Always try to follow this kind of standard practice and you will never fail.
Try putting single Quote around the GUID variable in SQL query.
cn.cmd.CommandText = "select SUM(Marks) AS 'Total' from Marksheet where StudentGUID = '" + StudentGUID + " '";

C# mysql parameterized query

I have this peace of code where I need to retrieve data from Mysql. If I use parameterized query it does not take actual parameter value instead it takes parameter name as value.
Error: #choise must be defined
MySqlConnection connection = new MySqlConnection("");
MySqlDataAdapter mySqlDataAdapter;
DataSet DS;
private string columnValue = xxx;
private string Choise = yyy;
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM table2 WHERE " + columnValue + " = #choise";
command.Parameters.Add(new MySqlParameter("#choise", Choise));
DS = new DataSet();
connection.Open();
mySqlDataAdapter = new MySqlDataAdapter(command.CommandText, connection);
mySqlDataAdapter.Fill(DS);
connection.Close();
when I run this i get query like:
SELECT * FROM table2 WHERE xxx = #choise
instead of
SELECT * FROM table2 WHERE xxx = yyy.
Where is the problem?
I have tried:
command.Parameters.Add(new MySqlParameter("#choise", Choise));
command.Parameters.AddWithValue("#choise", Choise);
It works fine when I'm using actual variables instead of parameters.
I think you need to run Prepare() on the command before adding parameters:
command.CommandText = "select * from table2 where " + columnValue + " = #choise";
command.Prepare();
command.Parameters.AddWithValue("#choise", Choise);
Try this instead:
command.CommandText = "SELECT * FROM `table2` WHERE `" + columnValue + "` = #choise";
command.Parameters.AddWithValue("#choise", Choise);

how to return int value from select query in function?

I need to retrieve Ticket_Id from tbl_Ticket to pass into body section of sending email function..
Is the below code correct?
every times i get Ticket_Id 1..
public int select_TicketId(){
string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString.ToString();
SqlConnection sqlCon = new SqlConnection(strConn);
string getId = ("select Ticket_Id from tbl_Ticket where Client_EmailAdd='" + objNewTic_BAL.email + "' ");
sqlCon.Open();
SqlCommand cmd1 = new SqlCommand(getId, sqlCon);
int i=cmd1.ExecuteNonQuery();
return i;
}
You are searching for ExecuteScalar which returns the first value.
using System.Configuration;
//
public int select_TicketId()
{
string strConn = ConfigurationManager.ConnectionStrings["conString"].ConnectionString.ToString();
SqlConnection sqlCon = new SqlConnection(strConn);
string getId = ("select TOP 1 Ticket_Id from tbl_Ticket where Client_EmailAdd='" + objNewTic_BAL.email + "' ");
sqlCon.Open();
SqlCommand cmd1 = new SqlCommand(getId, sqlCon);
return Convert.ToInt32(cmd1.ExecuteScalar());
}
Also use CommandProperties to set the where statement for better security, like below:
public int select_TicketId()
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
int result = -1;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = "select TOP 1 Ticket_Id from tbl_Ticket where Client_EmailAdd=#email";
command.Parameters.Add("#email", SqlDbType.Text).Value = objNewTic_BAL.email;
result = Convert.ToInt32(command.ExecuteScalar());
}
return result;
}
You should call int i=(int)cmd1.ExecuteScalar(); method
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
You're calling ExecuteNonQuery. But it's a query. This should have rung some warning bells :)
Try ExecuteScalar instead, and cast the result to int...
return (int) cmd1.ExecuteScalar();
Note that you should use using statements for the command and connection as well, so that both are closed appropriately.
And (I hadn't spotted this before) you should definitely use parameterized SQL instead of including a value directly into your SQL. Otherwise you're open to SQL Injection attacks...
So something like:
private const string FetchTicketIdSql =
"select Ticket_Id from tbl_Ticket where Client_EmailAdd = #Email";
public int FetchTicketId()
{
// No need for ToString call...
string connectionString =
ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(connection, FetchTicketIdSql))
{
command.Parameters.Add("#Email", SqlDbType.NVarChar).Value =
bjNewTic_BAL.email;
return (int) command.ExecuteScalar();
}
}
}
You should consider what you want to happen if there isn't exactly one result though...
Hiral,
ExecuteNonQuery in
int i=cmd1.ExecuteNonQuery();
will return number of records that satisfy your query. In this case it is 1 (or 0 if there are no emails)
Try using ExecuteReader instead.

Categories