SQL Values to integers - c#

I'm trying to compare values in a database that are updated every time a user logs in. When I execute a query with the given code nothing happens. However if I give it a value of say (where Attempt >10) it works where am I going wrong?
private void User_Tick(object sender, EventArgs e)
{
SqlConnection con13 = new SqlConnection("Data Source = *** ")
SqlDataAdapter SDA2 = new SqlDataAdapter("SELECT [User],[Login],[number1],[number2],[number3],[Alertcount] FROM Users.dbo.[Email] where [Alertcount] = 1 and [Alertcount] !=2", con13);
DataTable Users = new DataTable();
DataTable DATA2 = new DataTable();
SDA2.Fill(DATA2);
dataGridView2.DataSource = DATA2;
foreach (DataGridViewRow dr in dataGridView2.Rows)
{
string col2 = 1.Cells["User"].Value.ToString();
string col1 = 1.Cells["Login"].Value.ToString();
string col3 = 1.Cells["number1"].Value.ToString();
string col4 = 1.Cells["number2"].Value.ToString();
string col5 = 1.Cells["number3"].Value.ToString();
string col6 = 1.Cells["Alertcount"].Value.ToString();
var mine = Convert.ToInt32(col3);
var mine2 = Convert.ToInt32(col5);
SqlConnection CON2 = new SqlConnection("Data Source = ***")
CON2.Open();
SqlDataAdapter SDA = new SqlDataAdapter("SELECT [User],[Login],[Attempt] FROM User.dbo.Actions where [Attempt] > '"+mine+ "' and [Attempt] < '" + mine2 + "'", CON2);
DataTable DATA = new DataTable();
SDA.Fill(DATA);
dataGridView1.DataSource = DATA;
}
}

If column Attempt is an integer (as evident from the fact that Attempt < 10 runs), you need not pass comparison values to it in string. So your query should be like this:
SqlDataAdapter SDA = new SqlDataAdapter("SELECT [User],[Login],[Attempt] FROM User.dbo.Actions where [Attempt] > "+mine+ " and [Attempt] < " + mine2 , CON2);
I would suggest you to debug such errors in future by creating a query variable and then running the query in SQL manually to see what the error is. You could do something like this:
var query = "SELECT [User],[Login],[Attempt] FROM User.dbo.Actions where [Attempt] > "+mine+ " and [Attempt] < " + mine2 ;
SqlDataAdapter SDA = new SqlDataAdapter(query , CON2);

nothing happens - not enough information for correct answer. If actually nothing happens, then remove all try catch blocks you have around code and run application again. Then if something wrong you will get very useful information about what gone wrong in the form of Exception.
However, problem seems is that you passing wrong data to database query.
Always use SqlParameter for passing dynamic data to the query. SqlParameter have type which you can set to correspondent type of column you want operate on. Also SqlParameter will protect you from sql injection.
Use using for disposable objects when ever it possible (read "always")
var emailQuery =
#"SELECT [User] ,[Login] ,[number1] ,[number2] ,[number3] ,[Alertcount]
FROM Users.dbo.[Email]
WHERE [Alertcount] = 1
AND [Alertcount] !=2"; // Useless condition, because Alertcount already = 1
using(var connection2 = new SqlConnection("Data Source = *** "))
using(var adapter2 = new SqlDataAdapter(emailQuery, connection1))
{
var data2 = new DataTable();
adapter2.Fill(data2);
dataGridView2.DataSource = data2;
}
var actionsQuery =
#"SELECT [User] ,[Login] ,[Attempt]
FROM User.dbo.Actions
WHERE Attempt > #Mine AND Attempt < #Mine2";
foreach (var row in dataGridView2.Rows)
{
var mine = (int)row.Cells["number1"].Value; // it is already integer, just cast it
var mine2 = (int)row.Cells["number3"].Value;
using(var connection1 = new SqlConnection("Data Source = *** "))
using(var adapter1 = new SqlDataAdapter(actionsQuery, connection1))
{
var parameters = new[]
{
new SqlParameter
{
ParameterName = "#Mine",
SqlDbType = SqlDbType.Int,
Value = mine
},
new SqlParameter
{
ParameterName = "#Mine2",
SqlDbType = SqlDbType.Int,
Value = mine2
}
};
adapter1.SelectCommand.Parameters.AddRange(parameters);
var data1 = new DataTable();
adapter.Fill(data1);
dataGridView1.DataSource = data1
}
}

Related

From the database I am trying to display a single common name using label please guide me I am a beginner in C#

I am trying to make a feedback form where I want to show the name which is inserted n number of times.
My DataBase has for example 9 duplicate names as feedback was input for that same person 9 times and I want to display it on the result that common name.
Please help me out to complete the code/solution or Correct the code and get the result.
SQL QUERY IS RUNNING PROPERLY IT IS SELECTING THE SINGLE DATA FROM DATABASE BUT HOW TO SHOW THIS ON WEBPAGE
public void cal_F2name()
{
string oracledb = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP****))(****))(CONNECT_DATA =(SERVER = DEDICATED)(SID = ORCL));";
OracleConnection conn = new OracleConnection(oracledb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
OracleDataAdapter da1 = new OracleDataAdapter();
DataTable dt1 = new DataTable();
DataSet ds1 = new DataSet();
cmd.CommandText = "SELECT DISTINCT (F2NAME) FROM CMDC_FEEDBACK WHERE PRG_NAME ='" + cb_prg_name.SelectedValue + "'";
da1.SelectCommand = cmd;
da1.Fill(ds1);
name = Convert.ToString(ds1.Tables[0].Rows[0][0].ToString());
Label58.Text = String.Format("{0:0.00}",name);
conn.Close();
}
try using below code, i have made some change in sql query to get only single record as result.
public void cal_F2name()
{
string oracledb = "Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP****))(****))(CONNECT_DATA =(SERVER = DEDICATED)(SID = ORCL));";
OracleConnection conn = new OracleConnection(oracledb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
OracleDataAdapter da1 = new OracleDataAdapter();
DataTable dt1 = new DataTable();
DataSet ds1 = new DataSet();
cmd.CommandText = "SELECT max(DISTINCT (F2NAME)) FROM CMDC_FEEDBACK WHERE PRG_NAME ='" + cb_prg_name.SelectedValue + "' AND F2NAME<>'' AND F2NAME IS NOT NULL" ;
da1.SelectCommand = cmd;
da1.Fill(ds1);
name = Convert.ToString(ds1.Tables[0].Rows[0][0].ToString());
Label58.Text = String.Format("{0:0.00}",name);
conn.Close();
}
i have not check but it will work, if you result binding to lable is correct.

Retrieving a Row from a table causes invalid column name error

I am trying to delete a record in my database table. I am trying to delete it on the basis of a selected name in the dropdown list. When I debug my code there is not any record available in dataset and an exception "invalid column name" occurs, whereas if I run the same query in SQL Server, everything seems to be fine.
This is my code:
protected void SubCategory_Delete_Click(object sender, EventArgs e)
{
try
{
var conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\template_castle.mdf;Integrated Security=True");
var adpt = new SqlDataAdapter("Select * from tc_prod_subcategory where subcategory_name = ' ' "+ DropDownList2.SelectedItem.Value, conn);
var ds = new DataSet();
adpt.Fill(ds, "tc_prod_subcategory");
foreach (DataRow dr in ds.Tables["tc_prod_subcategory"].Rows)
{
dr.Delete();
}
SqlCommandBuilder build = new SqlCommandBuilder(adpt);
adpt.Update(ds, "tc_prod_subcategory");
Updatesubcategorygrid();
updatedelete_dropdown();
Lblsub_catdelete.Text = "Deleted Successfully";
}
catch(Exception ex)
{
Lblsub_catdelete.Text = ex.Message;
}
}
And this is the same query when I run it in SQL Server 2014; everything runs fine:
Select *
from tc_prod_subcategory
Where subcategory_name= 'Favicon'
The error is caused by the incorrect position of the apostophes in the where clause. It should be like:
"Select * from tc_prod_subcategory where subcategory_name = '" + DropDownList2.SelectedItem.Value + "'"
but that code is vulnerable to a SQL injection,so you should use parameters instead of concatenating strings.
var conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\template_castle.mdf;Integrated Security=True");
var adpt = new SqlDataAdapter("Select * from tc_prod_subcategory where subcategory_name = #subcategory_name", conn);
var ds = new DataSet();
adpt.SelectCommand.Parameters.AddWithValue("#subcategory_name", DropDownList2.SelectedItem.Value);
If you use c# version >= 6.0
you can use interpolation to concat strings in very handy and less error-prone way.
var adpt = new SqlDataAdapter($"Select * from tc_prod_subcategory where subcategory_name = '{DropDownList2.SelectedItem.Value}'", conn);

da=Fill(ds); error near '=' in asp.net

This code wants add selected items into the shopping cart for that I have got the itemname from requested.stringquery then I want to extract details of that item and put it into the table dt in gridview which will be displayed as my cart but it showing error where da=fill(ds).
if (!IsPostBack)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("sno");
dt.Columns.Add("itemname");
dt.Columns.Add("price");
dt.Columns.Add("image");
dt.Columns.Add("cost");
dt.Columns.Add("totalcost");
if (Request.QueryString["item_name"] != null)
{
if (Session["Buyitems"] == null)
{
dr = dt.NewRow();
SqlConnection scon = new SqlConnection(ConfigurationManager.ConnectionStrings["online food orderingConnectionString"].ConnectionString);
scon.Open();
String myquery = "select * from food_items where item_name=" + Request.QueryString["item_name"] ;
SqlCommand cmd = new SqlCommand(myquery,scon);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dr["sno"] = 1;
dr["itemname"] = ds.Tables[0].Rows[0]["item_name"].ToString();
dr["productimage"] = ds.Tables[0].Rows[0]["image"].ToString();
dr["price"] = ds.Tables[0].Rows[0]["price"].ToString();
dt.Rows.Add(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
Session["buyitems"] = dt;
}
Change
String myquery = "select * from food_items where item_name=" + Request.QueryString["item_name"] ;
SqlCommand cmd = new SqlCommand(myquery,scon);
to be:
String myquery = "select * from food_items where item_name=#item_name";
SqlCommand cmd = new SqlCommand(myquery, scon);
cmd.Parameters.AddWithValue("item_name", Request.QueryString["item_name"]);
Part of the problem is that appending strings to SQL statements is a very bad idea and leads to Sql Injection issues. Then you will have to consider what to do with strings that contain single and double quotes.
Using parameters like above will help avert the majority of problems you will encounter.

Having a little trouble with OleDataAdapter and getting a string result back

private string getPrinterPath()
{
string query1 = "SELECT printerPath FROM Printers WHERE printerFloor = '" + comboBoxFloor.SelectedItem.ToString() + "' AND printerNumber = " + textBoxPrinterNumber.Text.ToString();
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter();
da.SelectCommand = new OleDbCommand(query1, myDataConnection);
da.Fill(dt);
}
I am trying to get the String that is returned back from the execution of this query.
Can anyone please tell me how I can get the data from the DataAdapter?
I know I can
foreach (DataRow dr in dt.Rows)
{
Console.WriteLine(dr["printerPath"].ToString());
}
but i am expecting 1 item returned so I don't want to run it in an loop when it's unnecessary
If there is a better way, please let me know.
I am also confused about how to "Parameterize" my query so I am not passing values in directly
I usually use "ExecuteScalar" for something like that, which just returns the first result of the first row of a query.
As for parameters, you would pass parameters to the command.
It would look something like this:
string query1,
result;
query1 = "SELECT printerPath FROM Printers WHERE printerFloor = '?' AND printerNumber = ?";
using (OleDbConnection conn = new OleDbConnection(myDataConnection)) {
OleDbCommand cmd = new OleDbCommand(query1, conn);
cmd.Parameters.AddWithValue("PrinterFloor", comboBoxFloor.SelectedItem.ToString());
cmd.Parameters.AddWithValue("PrinterNum", textBoxPrinterNumber.Text.ToString());
conn.Open();
result = cmd.ExecuteScalar();
}

using local table variable in sql asp.net query code behind

Can I use a local DataTable with one column in sql query? And how?
List<int> k_p = null;
k_p = new List<int>();
k_p = (List<int>)Session["kosarica"];
DataTable spremljeno = new DataTable();
spremljeno.Columns.Add("id_k_p");
for(int i=0; i<k_p.Count; i++)
{
spremljeno.Rows.Add(k_p[i]);
}
String ConnString = "Data Source=BRACO-PC\\SQL1;Initial Catalog=DiplomskiSQL1SQL;Integrated Security=True;";
SqlConnection Conn = new SqlConnection(ConnString);
Conn.Open();
DataTable ukosarici = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("Select Proizvod.id_p, Proizvod.ime, TipProizvoda.tip, Proizvod.dimenzije, Proizvod.cijena FROM Proizvod LEFT JOIN TipProizvoda ON Proizvod.tip=TipProizvoda.id_t WHERE Proizvod.id_p IN #spremljeno", Conn);
SqlCommandBuilder cmd = new SqlCommandBuilder(da);
da.Fill(ukosarici);
GridView1.DataSource = ukosarici;
GridView1.DataBind();
Conn.Close();
I want to show only data where id_p is equal to values in spremljeno, and do not want to do a temp table in db, but dont know if it is possible... Connecting to SQL server 2008...
You could add all ID's as parameter to an IN clause in SQL:
var parameters = new string[k_p.Count];
using(var cmd = new SqlCommand())
{
for (int i = 0; i < k_p.Count; i++)
{
parameters[i] = string.Format("#id_p{0}", i);
cmd.Parameters.AddWithValue(parameters[i], k_p[i]);
}
var sql = "Select Proizvod.id_p, Proizvod.ime, TipProizvoda.tip, Proizvod.dimenzije, Proizvod.cijena FROM Proizvod LEFT JOIN TipProizvoda ON Proizvod.tip=TipProizvoda.id_t WHERE Proizvod.id_p IN ({0})";
cmd.CommandText = string.Format(sql, string.Join(", ", parameters));
using(var con = new SqlConnection(connStr))
{
cmd.Connection = con;
using(var da = new SqlDataAdapter(cmd))
{
da.Fill(ukosarici);
}
}
}
Note that you should use using-statements for everything that implements IDisposable(f.e. SqlConnection, Dispose also closes the connection). Also note that i used only your List<int>, the second DataTable was redundant.

Categories