ASP.NET , C# how to write this sql command - c#

How can I write this code in asp.net c# code behinds?
Wwhat I'm trying to do is to select all rows in invoicetable with orderno that is equal to current session and deduct the inventory of my inventorytable from `invoicetable qty that matches their itemid's.
SqlCommand cmd =
new SqlCommand("UPDATE inventorytable
JOIN invoicetable ON inventorytable.ItemID = invoicetable.ItemID
SET inventorytable.inventory = inventorytable.inventory-invoice.QTY
WHERE invoicetable.No='" + Convert.ToInt32(Session["invoiceno"]) + "'"
, con);
InsertUpdateData(cmd);

Your update query is not formed correctly, and you should be using parameterized SQL. Try using something like this
var sqlQuery =
#"UPDATE inventorytable
SET inventorytable.inventory = inventorytable.inventory-invoice.QTY
FROM inventorytable
INNER JOIN invoicetable ON inventorytable.ItemID = invoicetable.ItemID
WHERE invoicetable.No=#invNo";
using (var conn = new SqlConnection(CONN_STR))
{
var sqlCmd = new SqlCommand(sqlQuery, conn);
sqlCmd.Parameters.AddWithValue("#invNo", Session["invoiceno"].ToString());
sqlCmd.ExecuteNonQuery();
}
I typed this without VS in front of me, so let me know if there are any syntax issues

var n = Session["invoiceno"] != null ? Convert.ToInt32(Session["invoiceno"]) : 0;
using (var conn = new SqlConnection(CONN_STR))
{
conn.Open();
var sql = "SELECT * FROM invoicetable WHERE orderno = #n";
var cmd = new SqlCommand(sql);
cmd.Connection = conn ;
cmd.Parameters.AddWithValue("#n", n);
using(var dr = cmd.ExecuteReader())
{
while(dr.Read())
{
//loop through DataReader
}
dr.Close();
}
}

Related

How to make an "if" based on value retrieved from Query?

I need to insert into a table "pass" or "fail", if from the query done there is a single fail instead of 'RProva' I have to put "fail" if the query can't find a single fail instead of 'RProva' I have to insert "pass", the query is working but I can't figure out how to do the if with the results of a query, maybe I have to use a "for"? Don't know. It is the attempt to make it, the second is the query where I have to insert the result of the possbile "IF"
1.
SqlCommand cmdRD = new SqlCommand("SELECT ResItem AS RD FROM tSE JOIN tL ON tSE.idSE=tL.idL WHERE tL.Selection=1");
var RD = cmdRD.ExecuteScalar();
var values = new List<string>();
using (cmdRD,sqliteCon)
{
using (SqlDataReader reader = cmdRD.ExecuteReader())
{
while (reader.Read())
{
values.Add(reader[0].ToString());
}
}
}
2.
SqlCommand cmd1 = new SqlCommand("INSERT INTO tSD(NomeItem,ResItemDet,DateStartDet,DateEndDet) OUTPUT inserted.Id VALUES (#NI,#RProva,#DATESE,#DATEED)");
cmd1.Parameters.AddWithValue("#DATESE", DATESE);
cmd1.Parameters.AddWithValue("#DATEED", DATEED);
cmd1.Parameters.AddWithValue("#NI", NI);
using (cmd1,sqliteCon)
{
foreach (var value in values)
{
if (value.Equals(pass))
{
cmd1.Parameters.AddWithValue("#RProva", value);
}
else
{
cmd1.Parameters.AddWithValue("#RProva", fail);
}
cmd1.ExecuteNonQuery();
}
}
int generatedId = Convert.ToInt32(cmd1.ExecuteScalar());
cmd1.Parameters.Clear();
SqlCommand cmd2 = new SqlCommand("UPDATE tSE SET FK_TSD_id = #tsdId FROM tL JOIN tSE ON tL.idL = tSE.idSE WHERE tL.Selection=1 ", sqliteCon);
cmd2.Parameters.AddWithValue("#tsdId", generatedId);
cmd2.ExecuteNonQuery();
MessageBox.Show("Dato Aggiunto");
}
sqliteCon.Close();
1.1
SqlCommand cmdRD = new SqlCommand("SELECT ResItem AS RD FROM tSE JOIN tL ON tSE.idSE=tL.idL WHERE tL.Selection=1", sqliteCon);
var RD = cmdRD.ExecuteScalar();
var tot =pass;
using (cmdRD)
{
using (SqlDataReader reader = cmdRD.ExecuteReader())
{
while (reader.Read())
{
if(reader[0].ToString()==fail)
{
tot = fail;
break;
}
}
MessageBox.Show(tot);
}
}
i'm arrived to that(1.1) it works but i've to insert the TOT into RProva
Based on your question and comment I think you misunderstood ExecuteScalar:
ExecuteScalar executes the query, and returns the first column of the first row in the result set returned by the query. learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.executescalar
I dont know the Type of "RD" or "PASS", but the IF in your example (when using ExecuteScalar) seems OK. Else when you are using ExecuteReader you should use some kind of an loop to iterate through the Items. Like this:
string pass = "abc"; // guessing types and values
string fail = "failed";
string sqliteCon = "Data Source=(localdb)\\MSSQLLocalDB;Database=BooksDb";
using (SqlConnection connection = new SqlConnection(sqliteCon))
{
connection.Open();
var queryString = #"SELECT ResItem AS RD
FROM tSE
JOIN tL ON tSE.idSE = tL.idL
WHERE tL.Selection=1";
var values = new List<string>();
using (SqlCommand command = new SqlCommand(queryString, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
values.Add(reader[0].ToString());
}
}
}
var queryInsert = #"INSERT INTO tSD (NomeItem,ResItemDet,DateStartDet,DateEndDet)
VALUES (#NI, #RProva, #DATESE, #DATEED)";
using (SqlCommand command2 = new SqlCommand(queryInsert, connection))
{
foreach(var value in values)
{
command2.Parameters.Clear();
if (value.Equals(pass))
{
command2.Parameters.AddWithValue("#RProva", value);
}
else
{
command2.Parameters.AddWithValue("#RProva", fail);
}
command2.ExecuteNonQuery();
}
}
}
Theres for sure a better way, but maybe this helps you out.
EDIT:
Here is how I would implement your code example:
using (SqlConnection sqliteCon = new SqlConnection(connection))
{
sqliteCon.Open();
var values = new List<string>();
var query = "SELECT ResItem AS RD FROM tSE JOIN tL ON tSE.idSE=tL.idL WHERE tL.Selection=1";
using (SqlCommand cmdRD = new SqlCommand(query, sqliteCon))
{
var RD = cmdRD.ExecuteScalar();
using (SqlDataReader reader = cmdRD.ExecuteReader())
{
while (reader.Read())
{
values.Add(reader[0].ToString());
}
}
}
int generatedId = 0;
var query2 = "INSERT INTO tSD(NomeItem,ResItemDet,DateStartDet,DateEndDet) OUTPUT inserted.Id VALUES (#NI,#RProva,#DATESE,#DATEED)";
using (SqlCommand cmd1 = new SqlCommand(query2, sqliteCon))
{
foreach (var value in values)
{
cmd1.Parameters.Clear();
cmd1.Parameters.AddWithValue("#DATESE", DATESE);
cmd1.Parameters.AddWithValue("#DATEED", DATEED);
cmd1.Parameters.AddWithValue("#NI", NI);
if (value.Equals(pass))
{
cmd1.Parameters.AddWithValue("#RProva", value);
}
else
{
cmd1.Parameters.AddWithValue("#RProva", fail);
}
cmd1.ExecuteNonQuery();
}
generatedId = Convert.ToInt32(cmd1.ExecuteScalar());
}
var query3 = "UPDATE tSE SET FK_TSD_id = #tsdId FROM tL JOIN tSE ON tL.idL = tSE.idSE WHERE tL.Selection=1 ";
using (SqlCommand cmd2 = new SqlCommand(query3, sqliteCon))
{
cmd2.Parameters.AddWithValue("#tsdId", generatedId);
cmd2.ExecuteNonQuery();
}
}

MySql.Data.MySqlClient.MySqlException : 'There is already an open DataReader associated with this Connection which must be closed first.'

MySqlCommand Sql1 = new MySqlCommand("SELECT * FROM animal WHERE idAnimal ='" + label1.Text + "'", Connection);
MySqlDataReader dr1;
dr1 = Sql1.ExecuteReader();
while (dr1.Read())
{
String idAnimal = dr1["idAnimal"].ToString();
MySqlCommand Sql2 = new MySqlCommand("SELECT * FROM town WHERE id ='" + idAnimal + "'", Connectio);
MySqlDataReader dr2;
dr2 = Sql2.ExecuteReader();
while (dr2.Read())
{
dataGridView1.Rows.Add(dr2["number"], dr2["name"]);
}
dr2.Close();
}
dr1.Close();
Connection.Close();
The best way to solve this is with a JOIN (and fix that HUGE sql injection hole while we're at it):
string sql = "SELECT t.number, t.name FROM animal a INNER JOIN town t ON t.ID = a.idAnimal WHERE a.idAnimal= #idAnimal";
using (var cn = new MySqlConnection("connection string here"))
using (var cmd = new MySqlCommand(sql, cn))
{
cmd.Parameters.Add("#idAnimal", MySqlDbType.Int32).Value = int.Parse(label1.Text);
cn.Open();
using (var dr = cmd.ExecuteReader())
{
while(dr.Read())
{
dataGridView1.Rows.Add(dr["number"], dr["name"]);
}
dr.Close();
}
}
Additionally, you should probably look into databinding to connect those results to your grid, rather than manually adding rows. That would let you write code like this:
string sql = "SELECT t.number, t.name FROM animal a INNER JOIN town t ON t.ID = a.idAnimal WHERE a.idAnimal= #idAnimal";
using (var cn = new MySqlConnection("connection string here"))
using (var cmd = new MySqlCommand(sql, cn))
{
cmd.Parameters.Add("#idAnimal", MySqlDbType.Int32).Value = int.Parse(label1.Text);
cn.Open();
using (var dr = cmd.ExecuteReader())
{
dataGridView1.DataSource = dr;
dr.Close();
}
}
But if you really want to know how to have two DataReaders active together, you do that by having two connection objects:
using (var cn1 = new MySqlConnection("connection string here"))
using (var sql1 = new MySqlCommand("SELECT * FROM animal WHERE idAnimal = #idAnimal", cn1))
{
sql1.Parameters.Add("#idAnimal", MySqlDbType.Int32).Value = int.Parse(label1.Text);
cn1.Open();
using (var dr1 = sql1.ExecuteReader())
{
while (dr1.Read())
{
String idAnimal = dr1["idAnimal"].ToString();
using (var cn2 = new MySqlConnection("connection string here"))
using (var sql2 = new MySqlCommand("SELECT * FROM town WHERE id = #idAnimal", cn2))
{
cn2.Parameters.Add("#idAnimal", MySqlDbType.Int32).Value = int.Parse(idAnimal);
cn2.Open();
using(var dr2 = sql2.ExecuteReader())
{
while (dr2.Read())
{
dataGridView1.Rows.Add(dr2["number"], dr2["name"]);
}
dr2.Close();
}
}
}
dr1.Close();
}
}
But note how this is more than twice as much code as the JOIN + DataBinding option.
Also note that it's poor practice in ADO.Net providers to keep one database connection for re-use in your application. In addition to limiting your ability to use multiple database queries at the same time, as we see here, ADO.Net uses a feature called Connection Pooling, and re-using the same connection object interferes with this. It really is better to create a new connection object in most cases, and simply re-use the connection string.
You can't use the same "Connection" variable in two commands at the same time. Just have to create a second one if you want to open another connection inside of the Read of the first one.
You are using the same connection for the DataReader and the ExecuteNonQuery.which is not supported, according to MSDN You have to create sperate connection for each datareader

Select with where clause in MySql

Is it possible to select data from a table with a specific ID? I know it works for update but what is the code for the select?
Im using c# in visual studios, my goal is to display the details in readOnly textboxes.
string corp =
#"select corporateName,
corporateAddress,
corporateContact
from corporatemembership
where corporateID = CorpID.Text";
this should do it
string Command =
#"select corporateName,
corporateAddress,
corporateContact
from corporatemembership
where corporateID = #CorpID;";
using (MySqlConnection myConnection = new MySqlConnection(ConnectionString))
{
using (MySqlDataAdapter myDataAdapter = new MySqlDataAdapter(Command, myConnection))
{
myDataAdapter.SelectCommand.Parameters.Add(new MySqlParameter("#CorpID", CorpID.Text));
DataTable dtResult = new DataTable();
myDataAdapter.Fill(dtResult);
corporateName.Text = dtResult.Rows[0]["corporateName"];
corporateAddress.Text = dtResult.Rows[0]["corporateAddress"];
corporateContact.Text = dtResult.Rows[0]["corporateContact"];
}
}
probably you should add some error handling and handle the case that CorpID doesn't exist
UPDATE another approach
string Command =
#"select corporateName,
corporateAddress,
corporateContact
from corporatemembership
where corporateID = #CorpID;";
using (MySqlConnection mConnection = new MySqlConnection(ConnectionString))
{
mConnection.Open();
using (MySqlCommand cmd = new MySqlCommand(Command, mConnection))
{
cmd.Parameters.Add(new MySqlParameter("#CorpID", CorpID.Text));
using (MySqlDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
corporateName.Text = (string)reader["corporateName"];
corporateAddress.Text = (string)reader["corporateAddress"];
corporateContact.Text = (string)reader["corporateContact"];
}
}
}
}
Yes, it is possible,
your sql string is OK, except last part, you will edit last part
string corp = "select corporateName, corporateAddress, corporateContact from corporatemembership where corporateID = " + "'" + CorpID.Text + "'";

How to avoid duplication in sql connection and execute command

I can use this loop to give me list of names:
string commandText = #"SELECT ....;";
string connectionString = ConfigurationSettings.AppSettings["connectionString"];
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
try
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
DataTable dt = new DataTable();
dt.Load(reader);
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
SqlCommand addresscommand = new SqlCommand(address, connection);
addresscommand.Parameters.AddWithValue("#companyName", dt.Rows[i][0].ToString());
SqlDataReader addressreader = command.ExecuteReader();
string address = addressreader.GetString(0);
}
}
}
catch (Exception ex)
{
}
}
so the dt.Rows[i][0].ToString() is the name I need to add to all my different sql commands. So inside that for loop I will get each value from executing each sql command, one by one:
SqlCommand addresscommand = new SqlCommand(address, connection);
addresscommand.Parameters.AddWithValue("#companyName", dt.Rows[i][0].ToString());
SqlDataReader addressreader = addresscommand.ExecuteReader();
string comaddress = addressreader.GetString(0);
SqlCommand keyProcessescommand = new SqlCommand(keyProcesses, connection);
keyProcessescommand.Parameters.AddWithValue("#companyName", dt.Rows[i][0].ToString());
SqlDataReader keyProcessesreader = keyProcessescommand.ExecuteReader();
string comkeyProcesses = keyProcessesreader.GetString(0);
SqlCommand standardscommand = new SqlCommand(standards, connection);
standardscommand.Parameters.AddWithValue("#companyName", dt.Rows[i][0].ToString());
SqlDataReader standardsreader = standardscommand.ExecuteReader();
string comstandards = standardsreader.GetString(0);
Where the command string determined by:
string address = #"SELECT address FROM Companies where companyName = #companyName";
string keyProcesses = #" SELECT distinct STUFF((SELECT ', '+ cn.name from WMCCMCategories cn
INNER JOIN CategorySets uc ON uc.categoryId = cn.categoryID
INNER JOIN KeyProcesses u ON u.categorySetId = uc.setId
INNER JOIN Companies c ON c.companyId = u.companyId
WHERE c.companyName = #companyName
ORDER BY cn.name
FOR XML PATH('')), 1, 1, '') AS listStr
FROM WMCCMCategories cnn Group by cnn.name";
string standards = #" SELECT cn.name from WMCCMCategories cn
INNER JOIN CategorySets uc ON uc.categoryId = cn.categoryID
INNER JOIN Companies c ON c.standards = uc.setId
WHERE c.companyName = #companyName";
Can I execute multiple sql commands like above? How is the best way to do that ?
One way you can solve this through JOIN in SQL. However, it may not be right thing to do if it is not representing same columns.
Now in terms of using multiple select in one command. Yes, you can use SqlDataReader with NextResult()
Please see this link:
http://csharp.net-informations.com/data-providers/csharp-multiple-resultsets.htm

How to count the number of rows from sql table in c#?

How to count the number of rows from sql table in c#?
I need to extract some data from my database...
You may try like this:
select count(*) from tablename where columname = 'values'
C# code will be something like this:-
public int A()
{
string stmt = "SELECT COUNT(*) FROM dbo.tablename";
int count = 0;
using(SqlConnection thisConnection = new SqlConnection("Data Source=DATASOURCE"))
{
using(SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
}
}
return count;
}
You need to make a database connection from c# first. Then, you need to pass below query as commandText.
Select count(*) from TableName
Use ExecuteScalar/ExecuteReader to get the returned count.
Do you means likes this ?
SELECT COUNT(*)
FROM yourTable
WHERE ....
You can make global function that you can use all the time as
public static int GetTableCount(string tablename, string connStr = null)
{
string stmt = string.Format("SELECT COUNT(*) FROM {0}", tablename);
if (String.IsNullOrEmpty(connStr))
connStr = ConnectionString;
int count = 0;
try
{
using (SqlConnection thisConnection = new SqlConnection(connStr))
{
using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
}
}
return count;
}
catch (Exception ex)
{
VDBLogger.LogError(ex);
return 0;
}
}
This works for me
using (var context = new BloggingContext())
{
var blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList();
}
For more information consult: https://learn.microsoft.com/es-es/ef/ef6/querying/raw-sql?redirectedfrom=MSDN
Use this its working
string strQuery = "SELECT * FROM staff WHERE usertype='lacturer'";
connect.Open();
SqlCommand cmd = new SqlCommand(strQuery, connect);
SqlDataAdapter OleDbDa = new SqlDataAdapter(cmd);
DataSet dsData = new DataSet();
OleDbDa.Fill(dsData);
connect.Close();
std.Text = dsData.Tables[0].Rows.Count.ToString();
I used this method in my own application to count the number of active users within the program. This can be easily manipulated for your own use.
con.open();
string ActiveUsers = "SELECT * FROM Devices WHERE Status='" + "Online" + "'";
SqlCommand cmd = new SqlCommand(ActiveUsers, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
con.Close();
Users.Text = ds.Tables[0].Rows.Count.ToString();

Categories

Resources