SqlCommand - conversion from varchar to int - c#

Hello I have got this code :
SqlCommand sc2 = new SqlCommand("SELECT ... WHERE akce=" + zakce.Text, spojeni);
spojeni.Open();
object vysledek2 = sc2.ExecuteScalar(); // This is the exception line
I'm receving following Exception:
System.Data.SqlClient.SqlException (0x80131904)Conversion failed when
converting the varchar value '137000-01' to data type int.
On the exception line when I set the breakpoint on vysledek2 is null and then the exception occurs.

Never. Ever. Concatenate. Input.
SqlCommand sc2 = new SqlCommand("SELECT SUM(ISNULL(payments,0)) AS sumpaymentsFROM clientpayments WHERE akce=#acke", spojeni);
sc2.Parameters.AddWithValue("acke", zakce.Text);
Also - commands, connections, etc are all IDisposable - you should use using around each of them.

const string sqlSelect = #"SELECT ... WHERE akce=#akce";
using (spojeni = new SqlConnection(connectionString))
using(var command = new SqlCommand(sqlSelect,spojeni))
{
command.Parameters.AddWithValue("#akce", zakce.Text);
command.Connection.Open();
object vysledek2 = command.ExecuteScalar();
}

Firstly, try changing
SqlCommand sc2 = new SqlCommand("SELECT SUM(ISNULL(payments,0)) AS sumpaymentsFROM clientpayments WHERE akce=" + zakce.Text, spojeni);
to something like
SqlCommand sc2 = new SqlCommand("SELECT SUM(ISNULL(payments,0)) AS sumpaymentsFROM clientpayments WHERE akce='" + zakce.Text + "'", spojeni);
Secondly, have a look at what SQL Injection is and how to use parametereized queries.

Related

Adding a Where Clause to a OleDbCommand

I am trying to add a where clause to the following line of code.
the reason for this is because i get the datatable from a dropdown combobox. now i want to filter that table on user name, so that only the user can see their records.
i need help on how to write the where clause into this code.
if you need any more information i will gladding add it.
thank you for any help.
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From ", comboBox1.Text), con);
After Comments
i added the sql injection protection.
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From
#Companydetails where Research_ID = #Researcher_ID"), con);
cmd.Parameters.AddWithValue("#Companydetails", comboBox1.Text);
cmd.Parameters.AddWithValue("#Researcher_ID", usernumber_lab.Text);
but now it is giving me a error saying:
Additional information: Syntax error in query. Incomplete query clause.
is there something else i need to add to finnish this query off?
I would do it as follows;
string query = "Select * from MyTable Where username = #username";
using (OleDbCommand cmd = new OleDbCommand(query, con))
{
cmd.Parameters.Add("#username", OleDbType.VarChar).Value = comboBox1.Text;
}
This way the object will dispose automatically and also you'll be safe from Sql Injection
Please try this
string sql = String.format("Select * From {0} where id = {1}", comboBox1.Text, id);
OleDbCommand cmd = new OleDbCommand(sql,con);
You can just make your sql statement longer:
OleDbCommand cmd = new OleDbCommand(String.Concat("Select * From table Where something = something", comboBox1.Text), con);
You don't have to work with multiline or anything. This is only needed in some database managers, but not in a c# sql statement.
If you would like
OleDbCommand cmd = new OleDbCommand(String.Format("Select * From {0} WHERE username='{1}'", comboBox1.Text,username.Text), con);
You can try the below code
OleDbCommand cmd = new OleDbCommand(string.Format(
"SELECT * FROM {0} WHERE Username = '{1}'",
comboBox1.Text, userName), con);

How to update records in SQL Server database through asp.net?

I'm writing this code in asp.net but still it's not updating record in a SQL Server database:
SqlCommand cmd4 = new SqlCommand("Select * from roomdetail", conn);
SqlDataReader dr = cmd4.ExecuteReader();
while (dr.Read())
SqlCommand cmd3 = new SqlCommand("update [roomdetail] set [rid]=' " +count+1 + " ' where rid = 0 AND roomtype='"+typeRadioButtonList1.SelectedItem.ToString()+ "' ", conn);
Proper way to use ado.net:
var newId = count + 1;
var roomType = typeRadioButtonList1.SelectedItem.ToString();
using (var connection = new SqlConnection("your db connection string here"))
{
var query = "UPDATE [roomdetail] SET [rid] = #rid WHERE [rid] = 0 AND roomtype = #roomType";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("#rid", newId);
command.Parameters.AddWithValue("#roomType", roomType);
try
{
command.Connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
//handle exception
}
}
You are Missing ExecuteNonQuery Method Write Below code
SqlCommand cmd4 = new SqlCommand("Select * from roomdetail", conn);
SqlDataReader dr = cmd4.ExecuteReader();
while (dr.Read())
SqlCommand cmd3 = new SqlCommand("update [roomdetail] set [rid]=' " +count+1 + " ' where rid = 0 AND roomtype='"+typeRadioButtonList1.SelectedItem.ToString()+ "' ", conn);
cmd3.executeNonQuery();
Assuming the connection is already opened, in your while loop you are missing the following statement:
cmd3.ExecuteNonQuery();
You have to execute the command in order for the database to be updated.

Sql Exception related to DataSet in asp.net

I want to get values of a id specified row in my "Service Fees" table. When I try to execute following code an exception, which says "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 'a34'."
Is it about Dataset object?
PS: The id is; ee83089d-4a34-46e0-be6c-b8b506f31a8e
if (Request.QueryString["MyId"] != null)
{
isUpdate = true;
var id = Request.QueryString["MyId"].ToString();
SqlCommand cmd2 = new SqlCommand("SELECT * FROM ServiceFees WHERE Id=" + id, connection);
SqlDataAdapter adapter2 = new SqlDataAdapter(cmd2);
DataSet ds = new DataSet();
adapter2.Fill(ds);
sf1.name = ds.Tables[0].Rows[0][1].ToString();
}
Enclose your id in single quote, it should look like :
SqlCommand cmd2 = new SqlCommand("SELECT * FROM ServiceFees WHERE Id='" + id +"'", connection);
Id is GUID and it should be enclosed within single quotes.
SqlCommand cmd2 = new SqlCommand("SELECT * FROM ServiceFees WHERE Id= #id", connection);
cmd2.Parameters.Add(new SqlParameter("id",id));
to avoid sql injection.
Beware of SQL Injection
Dont pass parameters in single quotes,Double quotes
Always use SqlParameter Class
As your Parameter is String You need to Pass it As string DataType
string Id="ee83089d-4a34-46e0-be6c-b8b506f31a8e";
SqlParameter para1=new SqlParameter("#Id",SqlDbType.Varchar,500);
para1.Value=Id;
SqlCommand cmd2 = new SqlCommand("SELECT * FROM ServiceFees WHERE Id=#Id" , connection);
cmd2.Parameters.Add(para1);
SqlDataAdapter adapter2 = new SqlDataAdapter(cmd2);
You're passing the id unquoted to SQL.
As a result it's probably trying to calculate the result of ee83089d-4a34-46e0-be6c-b8b506f31a8e.
You probably want:
SqlCommand cmd2 = new SqlCommand("SELECT * FROM ServiceFees WHERE Id='" +
id + "'", connection);
Or some other SQL call which isn't vulnerable to injection attacks.

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)

assign the variable with MySql

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

Categories