I am trying to display some data on crystal report. after written the code the issued part of the report displayed well while the receiving part displayed only the first data within the range selected and duplicated several times. here is the code below
public DataSet itembincardreport(string date1, string date2, string
itemcode)
{
SqlCommand cmd = new SqlCommand();
SqlConnection con = null;
Connection cs = new Connection();
con = new SqlConnection(cs.DBcon);
con.Open();
DataSet ds = new DataSet();
frmReport frm = new frmReport();
string sql = "select * from ISSUED, RECEIVED WHERE
ISSUED.ITEMCODE=RECEIVED.ITEMCODE AND ISSUED.ITEMCODE = '" + itemcode + "'
AND RECEIVED.ITEMCODE = '" + itemcode + "' and ISSUED.TRANSDATE
between '" + Convert.ToDateTime(date1) + "' and '" +
Convert.ToDateTime(date2) + "' and RECEIVED.TRANSDATE between '" +
Convert.ToDateTime(date1) + "' and '" + Convert.ToDateTime(date2) + "'";
SqlDataAdapter dadbt = new SqlDataAdapter(sql, mycon.DBcon);
dadbt.Fill(ds);
dadbt.Dispose();
return ds;
}
The root cause of your problem is the query. Whether the received and issued tables have multiple rows that match each other or not, I cannot say (you need to post some better example table data than the screenshot given) but your query in the string should be written like this:
string sql =
#"select *
from
ISSUED
inner join
RECEIVED
on
ISSUED.ITEMCODE=RECEIVED.ITEMCODE -- this is probably the fault
-- try joining on ISSUEDID = RECEIVED instead??
where
ISSUED.ITEMCODE = #itemcode and
ISSUED.TRANSDATE between #date1 and #date2 and
RECEIVED.TRANSDATE between #date1 and #date2";
Later in your code, you should call:
var c = new SqlCommand();
c.CommandText = sql;
c.Connection mycon;
c.Parameters.AddWithValue("#itemcode", itemcode);
c.Parameters.AddWithValue("#date1", Convert.ToDateTime(date1)); //you should make the method argument a DateTime
c.Parameters.AddWithValue("#date2", Convert.ToDateTime(date2)); //you should make the method argument a DateTime
SqlDataAdapter dadbt = new SqlDataAdapter(c);
That's how to PROPERLY do database queries with parameters.. Now whether there are duplicate rows or not is purely down to your table data*, but at least your SQL is immune from hackers putting an itemcode of '; DROP table issued; -- in and screwing up your world
*post some detailed example data if you want help with that and I'll edit this answer. Take a look at SQLFiddle.com
Related
I am developing a POS system for a stationary. I am currently stuck in the sales page. I want to add to data grid view a product when user inputs barcode, quantity, discount and client id and this is the error I am getting:
System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'transaction'
string query;
string query2;
using (SqlConnection sqlcon2 = new SqlConnection(cons))
{
query = "insert into dbo.transaction set (qte,remise,idclt) values ('" + textBox4.Text + "','" + comboBox1.Text + "','" + textBox6.Text + "')";
SqlDataAdapter sda = new SqlDataAdapter(query, sqlcon2);
}
using (SqlConnection sqlcon = new SqlConnection(cons))
{
sqlcon.Open();
query2 = "select produit.idprod, produit.nom_produit, transaction.qte, transaction.remise, transaction.idclt, transaction.qte*produit.prixV as Total from [dbo].[produit] join [dbo].[transaction] on produit.idprod=transaction.idprod join [dbo].[clients] clt on clt.idclt=transaction.idclt where produit.idprod= '" + textBox4.Text+"' and transaction.qte='"+textBox5.Text+"'";
SqlDataAdapter sda2 = new SqlDataAdapter(query2, sqlcon);
DataTable dt = new DataTable();
sda2.Fill(dt);
dgv.DataSource = dt;
}
Database Schema:
Form Design:
Hello and welcome to Stack Overflow.
It's highly likely that the problem in your code is the table's name being transaction, a keyword in the RDBMS you are using (as evidenced by the exception's message). Try to change it to something else.
In addition, your snippet is vulnerable to an SQL injection attack. Unless your project is well into development, you should consider using an ORM framework like Entity Framework Core.
I am trying to get top 3 safety data row according to equipment and plant selection from database. Now I could get top 3 safety value from database with equipment and plant selection and insert to textbox.
When I wrote "' or Safety '" + textbox.text + it is getting other plant and equipment selections
sqlcon1.Open();
SqlDataAdapter Data = new SqlDataAdapter (#"select * from ****** Where "
+ "[Equipment Type]='" + equipmenttype_combobox.Text.Trim()
+ "' and Plant='" + plant_combobox.Text.Trim()
+ "' and Safety= '" + firstsafety_textbox.Text.Trim()
+ "' or Safety='" + secondsafety_textbox.Text.Trim()
+ "' or Safety='" + thirdsafety_textbox.Text.Trim() + "'", sqlcon);
DataTable dt1 = new DataTable();
SqlDataAdapter db1 = new SqlDataAdapter();
Data.Fill(dt1);
datagridview1.DataSource = dt1;
sqlcon1.Close();
Keep your sql been readable with a help of verbatim strings and string interpolation and many an error will be evident. Here you should either wrap Safety = ... or Safety = ... in parenthesis (Safety = ... or Safety = ... ) or use in construction Safety in (...).
Quick but dirty amendment is
...
string sql = $#"select *
from Makerinfo
where [Equipment Type] = '{equipmenttype_combobox.Text.Trim()}'
and [Plant] = '{plant_combobox.Text.Trim()}'
and [Safety] in ('{firstsafety_textbox.Text.Trim()}',
'{secondsafety_textbox.Text.Trim()}',
'{thirdsafety_textbox.Text.Trim()}')";
SqlDataAdapter Data = new SqlDataAdapter(sql, sqlcon1);
...
However, this implementation has at least 3 flaws:
It's prone to SQL Injection
It will crash on equipmenttype_combobox.Text = "Browns' equipment" (note apostroph)
For different plants, you have different queries which should be parsed, optimized etc.
Much better aproach is parametrized query:
...
string sql = $#"select *
from Makerinfo
where [Equipment Type] = #prm_Equipment
and [Plant] = #prm_Plant
and [Safety] in (#prm_Safety_1, #prm_Safety_2, #prm_Safety_3)";
using (SqlCommand q = new SqlCommand(sql, sqlcon1)) {
// I don't know the underlying RDMBS types, that's why I've put AddWithValue
//TODO: change AddWithValue to Add and provide the right rdbms type
// Something (and most probably) like
// q.Parameters.Add("#prm_Equipment", SqlDbType.VarChar).Value =
// plant_combobox.Text.Trim();
q.Parameters.AddWithValue("#prm_Equipment", equipmenttype_combobox.Text.Trim());
q.Parameters.AddWithValue("#prm_Plant", plant_combobox.Text.Trim());
q.Parameters.AddWithValue("#prm_Safety_1", firstsafety_textbox.Text.Trim());
q.Parameters.AddWithValue("#prm_Safety_2", secondsafety_textbox.Text.Trim());
q.Parameters.AddWithValue("#prm_Safety_3", thirdsafety_textbox.Text.Trim());
using (var reader = q.ExecuteReader()) {
DataTable dt1 = new DataTable();
dt1.Load(reader);
datagridview1.DataSource = dt1;
}
}
...
Using Visual studio coding C# I have a windows form and have two datetime pickers, how would I select two different date ranges and retrieve data from my SQL database. This is what I have done so far...
SqlConnection ssl = new SqlConnection();
ssl.ConnectionString = #"connection goes ";
ssl.Open();
var a = dateTimePicker1.Value.ToString("yyyy-MM-dd");
var b = dateTimePicker2.Value.ToString("yyyy-MM-dd");
SqlDataAdapter ad = new SqlDataAdapter("SELECT name FROM DATABASENAME WHERE columnname >='" + a + "' AND modified_time <= '"+ b +"'", ssl);
DataTable dt = new DataTable();
ad.Fill(dt);
dataGridView1.DataSource = dt;
When you do this:
"... >= '" + a + "' AND ..."
You're creating a string literal that has your date value in it. The database won't treat it as a date though, and if the query executes it won't do what you want.
Instead, parameterize your query, which is the correct way to pass the dates (or any other values) in:
SqlDataAdapter ad =
new SqlDataAdapter("SELECT name FROM DATABASENAME WHERE columnname >= #Date1 AND modified_time <= #Date2", ssl);
ad.SelectCommand.Parameters.AddWithValue("#Date1", dateTimePicker1.Value);
ad.SelectCommand.Parameters.AddWithValue("#Date2", dateTimePicker2.Value);
public void SPROC_LoadGroups()
{
//This gets the table name.
string tablename = cboNetChannel.SelectedItem.ToString();
SqlConnection sqlConnectionCmdString = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Rick\Documents\Visual Studio 2010\Projects\Server\database\ClientRegit.mdf;Integrated Security=True;User Instance=True");
//This is the table name and Query that identifies with the selected table
string Command = "SELECT Client_Groups" + "FROM" + tablename;
SqlCommand sqlCommand = new SqlCommand(Command, sqlConnectionCmdString);
SqlDataAdapter objDA = new SqlDataAdapter(sqlCommand);
DataSet dsGroups = new DataSet();
objDA.Fill(dsGroups, "dtGroup");
cboExistingG.DataSource = dsGroups.Tables["dtGroup"];
cboExistingG.DisplayMember = "Client_Groups";
//cboExistingG.ValueMember = "ID";
}
Error I am getting is this {"Incorrect syntax near '-'."}
I got a situation is it possible to query as table with a name similar to a GUID value
my table name is 43d5377-0dcd-40e6-b95c-8ee980b1e248
I am generating groups that are identified with a Networking Data table that is named 43d5377-0dcd-40e6-b95c-8ee980b1e248 The table name is allowed and SQL does not prohibit such table names.
This is my code I am getting an error, I am table mapping with this by creating a Query that allows me to identify the query with the selected table value.
If your table name is similar as a GUID add [] block
something like:
string Command = "SELECT Client_Groups FROM [" + tablename+ "]";
Best Regards
You were missing a space between the concatination of these two strings:
"SELECT Client_Groups" + "FROM"
change to
"SELECT Client_Groups " + "FROM "
SqlCommand cmd;
cmd = new SqlCommand("SELECT client_Groups FROM Table name where name='" + txtbox. Text + "' , lastname='" + txtbox. Text + "'", con);
I need to show every record which equals the var modid and the current session's userid.
In .cs code this would be:
SELECT Mod_Naam
FROM Model
WHERE Mod_ID = " + modid + "
AND User_ID = '" + Session["status"].ToString() + "'
How can I import this query in a dropdownlist?
I may also need to use this on a gridview.
You can get the data from a DB via the DataTable and then bind that DataTable to the dropdownlist as follows:
using (SqlCommand cmd = new SqlCommand()
{
cmd.Connection = cnn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Mod_Naam FROM Model WHERE Mod_ID = " + modid + " AND User_ID = '" + Session["status"].ToString() + "' "";
//cmd.Parameters.Add(param);// You add parameter
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
Take a look here, on how to get Data in DataTable Retrieve a DataTable using a SQL Statement
DropDownList1.DataSourceID = dt;
DropDownList1.DataTextField= "Mod_Naam";
DropDownList1.DataValueField= "Mod_Naam";
DropDownList1.DataBind();