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;
}
}
...
Related
This is the function for automatically stored value to TotalAmt_tx.Text..
void TotalAmount()
{
.
.
.
.
TotalAmt_tx.Text = Total.ToString("00.00");
.
.
.
catch { }
}
Save button code :here the image of my forms
private void Save_bt_Click(object sender, EventArgs e)
{
//Purchase Table
{
string insertPur = "Insert into Purchase (Invoice,VendorName,PurchaseDate,TotalAmt) values ("+Invoice_tx.Text+"," +
"'"+VendorName_cb.Text+"','"+PurchaseDate_dt.Value.Date.ToString()+"',"+TotalAmt_tx.Text+" )";
OleDbDataAdapter da = new OleDbDataAdapter(insertPur, conn);
DataSet ds = new DataSet();
da.Fill(ds);
}
//Purchase Item Table
for (int i = 0; i < metroGrid1.Rows.Count; i++)
{
string insertPur = "Insert into PurchaseItem (Invoice, PId, Product, Qty, Rate, Amount) values (" + Invoice_tx.Text + "," +
""+metroGrid1.Rows[i].Cells["PId"].Value.ToString()+ ",'" + metroGrid1.Rows[i].Cells["Product"].Value.ToString() + "'," +
"" + metroGrid1.Rows[i].Cells["Qty"].Value.ToString() + "," + metroGrid1.Rows[i].Cells["Rate"].Value.ToString() + "," +
"" + metroGrid1.Rows[i].Cells["Amount"].Value.ToString() + ")";
OleDbDataAdapter da = new OleDbDataAdapter(insertPur, conn);
DataSet ds = new DataSet();
da.Fill(ds);
}
MessageBox.Show("Data Saved!!");
The problems show up because this
TotalAmt_tx.Text = Total.ToString("00.00")
What should I do, to solve it??
I've try follow some tutorial about formatting string but nothings works.
Please help
I suggest you try to use OleDbParameter Class, because if one of the values you combine to your query string has the , character it will mess-up you query (for example a number in the following format 1,000).
Hope it helps!
You should always stick to parameterized queries to avoid SQL Injection. It also helps in avoiding mistakes like missing a "'"
using (OleDbConnection connection =new OleDbConnection(connectionString))
{
var query = "Insert into Purchase (Invoice,VendorName,PurchaseDate,TotalAmt) values (#invoice,#vendor,#purchasedate,#amt)";
OleDbDataAdapter adapter = new OleDbDataAdapter(queryString, connection);
adapter.SelectCommand.Parameters.Add("#invoic", OleDbType.Integer).Value = Convert.ToInt32(Invoice_tx.Text);
adapter.SelectCommand.Parameters.Add("#vendor", OleDbType.VarChar,100).Value = VendorName_cb.Text;
adapter.SelectCommand.Parameters.Add("#invoic", OleDbType.Date).Value = PurchaseDate_dt.Value.Date; // I do not know what PurchaseDate_dt.Value.Date type is, so I leave it to you to convert to approapriate type
adapter.SelectCommand.Parameters.Add("#CategoryName", OleDbType.Integer).Value = Convert.ToInt32(TotalAmt_tx.Text);
connection.Open();
DataSet ds = new DataSet();
adapter.Fill(ds);
}
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
string constr = Properties.Settings.Default.Subject_1ConnectionString;
SqlConnection conn = new SqlConnection(constr);
SqlCommand com = new SqlCommand("SELECT * from Subject_Title WHERE Date BETWEEN #hello and #hello1 ", conn);
// com.Parameters.Add("#hello", SqlDbType.NVarChar).Value = textBox1.Text;
// com.Parameters.Add("#hello1", SqlDbType.NVarChar).Value = textBox2.Text;
com.Parameters.Add("#hello", SqlDbType.NVarChar);
com.Parameters["#hello"].Value = textBox1.Text;
com.Parameters.Add("#hello1", SqlDbType.NVarChar);
com.Parameters["#hello1"].Value = textBox2.Text;
// com.Parameters.AddWithValue("#hello", textBox1.Text);
// com.Parameters.AddWithValue("#hello1", textBox2.Text);
SqlDataAdapter da = new SqlDataAdapter(com);
DataSet ds = new DataSet();
da.Fill(ds, "Subject_title");
for (int i = 0; i < 8; i++)
{
this.labeltext = this.labeltext + " " + ds.Tables["Subject_Title"].Rows[i]["Date"].ToString();
this.labeltext = this.labeltext + " " + ds.Tables["Subject_Title"].Rows[i]["Subject"].ToString();
this.labeltext = this.labeltext + " ";
}
this.label1.Text = this.labeltext;
Here I'm not getting any data from the database
Date is my column name with a nvarchar type, and Subject is another column of type text.
Pls anyone solve my problem
I guess you should use:
Con.Open();
Con.Close();
But if I were you I would have written this code like this:
string constr = Properties.Settings.Default.Subject_1ConnectionString;
SqlConnection conn = new SqlConnection(constr);
SqlCommand com = new SqlCommand("SELECT * from Subject_Title WHERE Date BETWEEN \"01-03-14\" and \"01-04-14\" ", conn);
conn.Open();
SqlDataReader reader =com.ExecuteReader();
while(reader.read()){
this.labeltext += " " + reader.GetString(0); //Use column ordinal for Date
this.labeltext += " " + reader.GetString(1)+" "; //Use column ordinal for Subject
}
conn.Close()
this.label1.Text = this.labeltext;
I tried to come up with a better code base for you.
You need to:
use more meaningful names! Parameters like hello and hello1 aren't very useful to someone reading your code.... also: don't name your columns with reserved keywords like Date - again: use something more meaningful to your context
if you want to use date-related methods, you must use DATE or DATETIME2(N) datatypes. If you have stored your data as nvarchar - you must convert it first to a DATE
please always put your SqlConnection and SqlCommand into using(...) { .. } blocks to ensure proper and speedy disposal
if you only need a single DataTable - just instantiate a DataTable and fill it - don't use the unnecessary additional overhead of a DataSet - that's just wasted resources...
Code:
string constr = Properties.Settings.Default.Subject_1ConnectionString;
// if you only need one single data table - use a DataTable - not a DataSet !
DataTable dt = new DataTable();
// *ALWAYS* put your SqlConnection and SqlCommand into using() blocks!
// also - if you want to use BETWEEN, you *MUST* use DATE!
// also: don't call your column "date" - that's a SQL Server reserved keyword! Use a more meaningful name
// like "DateCreated" or "DateLastUpdated" or something
// and please also use more meaningful parameter names - "hello" and "hello1" is very confusing and not clear!!
using (SqlConnection conn = new SqlConnection(constr))
using (SqlCommand com = new SqlCommand("SELECT * FROM dbo.Subject_Title WHERE CAST(DateCreated AS DATE) BETWEEN #start and #end ", conn))
{
// add parameters as DATE type!
com.Parameters.Add("#start", SqlDbType.Date);
com.Parameters["#start"].Value = DateTime.Parse(textBox1.Text).Date;
com.Parameters.Add("#end", SqlDbType.Date);
com.Parameters["#end"].Value = DateTime.Parse(textBox2.Text).Date;
SqlDataAdapter da = new SqlDataAdapter(com);
da.Fill(dt);
}
for (int i = 0; i < 8; i++)
{
this.labeltext = this.labeltext + " " + dt.Rows[i]["Date"].ToString();
this.labeltext = this.labeltext + " " + ds.Rows[i]["Subject"].ToString();
this.labeltext = this.labeltext + " ";
}
this.label1.Text = this.labeltext;
I have this query set up in my application to work for searching through my database. I put this query into Access and it works fine. However, when I put it into my program the table has 0 entries. Can you please help?
private async Task FilterDB()
{
List<string> Filter = new List<string>();
if (CardNameCheck.IsChecked == true)
Filter.Add("*" + CardNameBox.Text + "*");
else
Filter.Add("*");
if (CardExpanCheck.IsChecked == true)
Filter.Add("*" + CardExpanBox.Text + "*");
else
Filter.Add("*");
OleDbConnection DBCon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Properties.Settings.Default.DatabaseLocation);
await DBCon.OpenAsync();
OleDbDataAdapter CardDA = new OleDbDataAdapter("SELECT * FROM Cards WHERE Name like '" + Filter[0] + "' and Expansion like '" + Filter[1] + "'", DBCon);
DataSet CardDS = new DataSet();
CardDA.Fill(CardDS);
DBCon.Close();
I tried your code and modified it a bit. Works for me for the Access2003 .mdb format.
OleDbConnection DBCon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=(k:\mydatabases\mydatabase.mdb");
DBCon.Open();
// Create a select Command - you need System.Data.OleDb and System.Data for this
OleDbCommand selectCommand = new OleDbCommand();
// define the CommandText with two parameters #Filter1 and #Filter2
selectCommand.CommandText = "SELECT * FROM Cards WHERE Name like #Filter1 and Expansion like #Filter2";
selectCommand.Connection = DBCon;
// Create two string / VarChar Parameters -
// the following is a standard I commonly use
// for string/varchar; you might also use OleDbType.NVarChar
OleDbParameter param01 = new OleDbParameter();
param01.ParameterName = "Filter1";
param01.DbType = DbType.AnsiString;
param01.OleDbType = OleDbType.VarChar;
param01.SourceVersion = DataRowVersion.Current;
param01.SourceColumn = "Name";
// provide them with values - I used text boxes for input
// use '%' for like statement - if no parameter provided use single '%' only
if (txtFilter1.Text.ToString().Equals(""))
{
param01.Value = '%';
}
else
{
param01.Value = '%' + txtFilter1.Text.ToString() + '%';
}
// add the parameter to the SelectCommand
selectCommand.Parameters.Add(param01);
// same goes for the second parameter
OleDbParameter param02 = new OleDbParameter();
param02.ParameterName = "Filter2";
param02.DbType = DbType.AnsiString;
param02.OleDbType = OleDbType.VarChar;
param02.SourceVersion = DataRowVersion.Current;
param02.SourceColumn = "Expansion";
if (txtFilter2.Text.ToString().Equals(""))
{
param02.Value = '%';
}
else
{
param02.Value = '%' + txtFilter2.Text.ToString() + '%';
}
selectCommand.Parameters.Add(param02);
OleDbDataAdapter CardDA = new OleDbDataAdapter();
// tell the DataAdapter to use a SelectCommand
CardDA.SelectCommand = selectCommand;
CardDA.GetFillParameters(); // actually not sure if you need this but does no harm either
DataSet CardDS = new DataSet();
CardDA.Fill(CardDS, "TargetTable");
DBCon.Close();
foreach(DataRow row in CardDS.Tables["TargetTable"].Rows)
{
// do something ;
}
Good luck!
I have created a function in SQL, now I need to use that function in my C# application.
I tried using something like this, but it seems I'm doing it wrong since I'm getting:
Must declare the scalar value '#2064734117'
...when I give 2064734117 as the first parameter and 1 as the second parameter. Here is the code I'm talking about:
SqlConnection con = new SqlConnection(clsDb.connectionString);
string query = string.Format("select Function1(#{0},#{1}) ",
int.Parse(e.CurrentRow.Cells["CodeMeli"].Value.ToString()),1);
con.Open();
SqlCommand cmd = new SqlCommand(query,con);
SqlDataAdapter READER = new SqlDataAdapter();
READER.SelectCommand = cmd;
DataTable table = new DataTable();
READER.Fill(table);
radGridView1.DataSource = table;
con.Close();
And my function takes two integer parameters and returns a table. I checked it in Visual Studio and it worked, but I couldn't get it to work in my application.
And this is my function declaration:
ALTER FUNCTION dbo.Function1
(
/*
#parameter1 int = 5,
#parameter2 datatype
*/
#ID int,
#clsTypeID int
)
RETURNS TABLE/* #table_variable TABLE (column1 datatype, column2 datatype) */
AS
/*BEGIN */
/* INSERT INTO #table_variable
SELECT ... FROM ... */
RETURN SELECT * FROM tblCLASS2
WHERE STNID = #ID AND CLASSTYPEID = #clsTypeID
/*END */
/*GO*/
Your SQL is a bit off, it should be:
string query = string.Format("select * from dbo.Function1({0},{1});", int.Parse(e.CurrentRow.Cells["CodeMeli"].Value.ToString()),1);
You might want to use SqlParameter-objects to prevent sql injections:
string query = "select * from dbo.Function1(#pa1,#par2);";
cmd.Parameters.Add("#par1", SqlDbType.Int).Value = int.Parse(e.CurrentRow.Cells["CodeMeli"].Value.ToString());
cmd.Parameters.Add("#par2", SqlDbType.Int).Value = 1;
At a glance, the first thing I can see is that you aren't specifying the object owner / schema; that is required for functions, so it should be select dbo.Function1(...
Second: look at what your call to string.Format generates; that is generating #1 and #n for n another integer, but that is not a valid parameter name. Which is handy, because
Third: you didn't add any parameters
Fourth: for a table UDF (rather than a scalar UDF), you must select * from dbo.Function1(..., not just select dbo.Function1(...
You can do something like this:
myConn.Open();
//generating the new command for our database
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT OBJECTID_1, NDNT as theAddress, MIN(ABS(x - " + double.Parse(x.ToString()) + ") + ABS(y - " + double.Parse(y.ToString()) +")) from dbo.DWH_OUTPUT GROUP BY OBJECTID_1,NDNT HAVING (MIN(ABS(x - " + double.Parse(x.ToString()) + ") + ABS(y - " + double.Parse(y.ToString()) + ")) = (Select MIN(ABS(a.x - " + double.Parse(x.ToString()) + ") + ABS(a.y - " + double.Parse(y.ToString()) + ")) from dbo.DWH_OUTPUT a ) )";
cmd.Connection = myConn;
//getting some more ado.net objects
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = cmd;
da.Fill(ds, #"Addresses");
if (ds.Tables[0].Rows.Count > 0)
{
theAddress = ds.Tables[0].Rows[0][#"theAddress"] + #" (proximity address)";
}
myConn.Close();
Note how in this example, you set the SqlCommand's CommandType to CommandType.Text. Specify your command parameters (i.e. the select function in your code snippet), and then populate the dataset with the Fill method. Then you can pluck out the values from the rows as you ordinarily would with standard ado.net.
If you need to call a stored proc, have a look at this:
How do I call a TSQL function from ado.net
You need fully qualified name of function with owner/schema name
A working sample available at following link: