I want to return the row ID from SQL Server through C#. Below is the code I am using:
const string sqlQuery = "SELECT ID " +
"FROM CleaningCycleTime " +
"WHERE ActualFinishDayTime < DATEADD(day, -60, GETDATE()) AND LotWorkOrder = #LotWorkOrder AND Process = #Process AND CleanType = #CleanType " +
"Group By ID " +
"Having (Min(ActualStartDayTime) IS NOT NULL AND Max(ActualFinishDayTime) IS NOT NULL)";
using (SqlCommand myCommand = new SqlCommand(sqlQuery, _myConnection))
{
try
{
myCommand.Parameters.AddWithValue("#LotWorkOrder", lstOpenCleans.SelectedItem.ToString());
myCommand.Parameters.AddWithValue("#Process", lstProcess.SelectedItem.ToString());
myCommand.Parameters.AddWithValue("#CleanType", lstProcess.SelectedItem.ToString());
_myConnection.Open();
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
txtID.Text = myReader["ID"].ToString();
}
_myConnection.Close();
}
catch (Exception ee)
{
MessageBox.Show(ee.ToString());
_myConnection.Close();
}
}
Which generates
SELECT ID
FROM CleaningCycleTime
WHERE ActualFinishDayTime < DATEADD(day, -60, GETDATE())
AND LotWorkOrder = 'X90744'
AND Process = 'PRE BLEND'
AND CleanType = 'FULL'
GROUP BY
ID
HAVING
(Min(ActualStartDayTime) IS NOT NULL
AND Max(ActualFinishDayTime) IS NOT NULL)
When I run the generated query in SQL Server Management Studio, it returns a value. When I do this in C#, it gets as far as myReader.Read(), but never loops
I notice a couple of things:
1 - No quotes around your C# string where appropriate.
SQL:
AND LotWorkOrder = 'X90744'
AND Process = 'PRE BLEND'
AND CleanType = 'FULL'
vs
C#:
"AND LotWorkOrder = #LotWorkOrder AND Process = #Process AND CleanType = #CleanType "
2 - We do not see how your connection is defined. Why not wrap it in a using statement?
To be concise:
using (var cn = new SqlConnection("connection string"))
{
cn.Open();
using (var cmd = cn.CreateCommand())
{
// set the command text
const string sqlQuery = "SELECT ID " +
"FROM CleaningCycleTime " +
"WHERE ActualFinishDayTime < DATEADD(day, -60, GETDATE()) AND LotWorkOrder = '#LotWorkOrder' AND Process = '#Process' AND CleanType = '#CleanType' " +
"Group By ID " +
"Having (Min(ActualStartDayTime) IS NOT NULL AND Max(ActualFinishDayTime) IS NOT NULL)";
cmd.CommandText = sqlQuery;
// Add your paramters to the command object.
cmd.Parameters.AddWithValue("#LotWorkOrder", lstOpenCleans.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#Process", lstProcess.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#CleanType", lstProcess.SelectedItem.ToString());
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
txtID.Text = myReader["ID"].ToString();
}
}
}
}
New sqlQuery:
const string sqlQuery = "SELECT ID " +
"FROM CleaningCycleTime " +
"WHERE ActualFinishDayTime < DATEADD(day, -60, GETDATE()) AND LotWorkOrder = '#LotWorkOrder' AND Process = '#Process' AND CleanType = '#CleanType' " +
"Group By ID " +
"Having (Min(ActualStartDayTime) IS NOT NULL AND Max(ActualFinishDayTime) IS NOT NULL)";
Related
So I want to manually convert the PHP function to C# Windows Form but I don't know the equivalent function mysqli_fetch_array in C# and how to do array PHP in C#?
I've googling but there is no correct solution.
This is in C# Windows Form
openConnection();
string selectQuery = "SELECT * FROM data_pegawai WHERE is_deleted=0 AND username='" + user + "'";
MySqlCommand command = new MySqlCommand(selectQuery, conn);
MySqlDataReader reader = command.ExecuteReader();
while (valuesList = reader.Read())
{
id = reader.GetInt32("id_peg");
}
closeConnection();
kembali = bayar - subtotal;
lblKembali.Text = kembali.ToString();
string insertQuery1 = "UPDATE data_transaksi SET status_pengerjaan='Lunas',potongan_harga='" + diskonrupiah.ToString() + "',subtotal='" + txtSubtotal.Text + "' WHERE id_transaksi =" + int.Parse(txtID_T.Text);
string insertQuery2 = "INSERT INTO pegawai_onduty VALUES(NULL, '" + id + "','" + txtID_T.Text + "')";
openConnection();
string selectQuery1 = "SELECT dsp.id_spareparts, dtsp.JUMLAH_SPAREPART from data_transaksi dt LEFT JOIN detail_transaksi_sparepart dtsp ON dt.id_transaksi=dtsp.id_transaksi LEFT JOIN spareparts_motor sm ON dtsp.ID_SPAREPARTMOTOR=sm.ID_SPAREPARTMOTOR LEFT JOIN data_spareparts dsp ON sm.id_spareparts=dsp.id_spareparts where dtsp.id_transaksi =" + int.Parse(txtID_T.Text);
MySqlCommand command1 = new MySqlCommand(selectQuery1, conn);
MySqlDataReader reader1 = command1.ExecuteReader();
while (reader1.Read())
{
int getData = "SELECT jumlah_stok FROM data_spareparts dsp WHERE id_spareparts='$jml[0]'";
}
closeConnection();
runQuery(insertQuery1);
runQuery(insertQuery2);
loadTransaksi();
And this is PHP code that I trying to convert to
while($jml=mysqli_fetch_array($dataJumlah))
{
$getData = mysqli_query($conn, "SELECT jumlah_stok FROM data_spareparts dsp WHERE id_spareparts='$jml[0]' ") or die (mysqli_error($conn));
$dataSP = mysqli_fetch_array($getData);
$idSpareparts = $dataSP[0];
$jmlStok = (int) $dataSP[0];
$jmlJual = (int) $jml[1];
$sisaStok = $jmlStok-$jmlJual;
$updateStok = mysqli_query($conn,"UPDATE data_spareparts SET jumlah_stok=$sisaStok WHERE id_spareparts='$jml[0]'") or die (mysqli_error($conn));
}
So I want to do "while($jml=mysqli_fetch_array($dataJumlah))" in C# and the rest of it. But how?
This question has been answered.
Below is the answer
subtotal = Convert.ToDouble(txtSubtotal.Text);
bayar = Convert.ToDouble(txtBayar.Text);
if (bayar < subtotal)
{
MessageBox.Show("Nominal yang dibayarkan lebih kecil dari Subtotal!");
}
else
{
openConnection();
string selectQuery = "SELECT * FROM data_pegawai WHERE is_deleted=0 AND username='" + user + "'";
MySqlCommand command1 = new MySqlCommand(selectQuery, conn);
MySqlDataReader reader1 = command1.ExecuteReader();
while (reader1.Read())
{
id = reader1.GetInt32("id_peg");
}
closeConnection();
kembali = bayar - subtotal;
lblKembali.Text = kembali.ToString();
string insertQuery1 = "UPDATE data_transaksi SET status_pengerjaan='Lunas',potongan_harga='" + diskonrupiah.ToString() + "',subtotal='" + txtSubtotal.Text + "' WHERE id_transaksi =" + int.Parse(txtID_T.Text);
string insertQuery2 = "INSERT INTO pegawai_onduty VALUES(NULL, '" + id + "','" + txtID_T.Text + "')";
openConnection();
string selectQuery1 = "SELECT dsp.id_spareparts, dtsp.JUMLAH_SPAREPART from data_transaksi dt LEFT JOIN detail_transaksi_sparepart dtsp ON dt.id_transaksi=dtsp.id_transaksi LEFT JOIN spareparts_motor sm ON dtsp.ID_SPAREPARTMOTOR=sm.ID_SPAREPARTMOTOR LEFT JOIN data_spareparts dsp ON sm.id_spareparts=dsp.id_spareparts where dtsp.id_transaksi =" + int.Parse(txtID_T.Text);
MySqlCommand command2 = new MySqlCommand(selectQuery1, conn);
MySqlDataReader reader2 = command2.ExecuteReader();
while (reader2.Read())
{
idSparepart = reader2.GetString(0);
jmlJual = reader2.GetInt32(1);
}
closeConnection();
openConnection();
string getData = "SELECT jumlah_stok FROM data_spareparts dsp WHERE id_spareparts='" + idSparepart + "'";
MySqlCommand command3 = new MySqlCommand(getData, conn);
MySqlDataReader reader3 = command3.ExecuteReader();
while (reader3.Read())
{
jmlStok = reader3.GetInt32(0);
}
closeConnection();
sisastok = jmlStok - jmlJual;
string updateStok = "UPDATE data_spareparts SET jumlah_stok = '" + sisastok + "' WHERE id_spareparts ='" + idSparepart + "'";
try
{
openConnection();
MySqlCommand command4 = new MySqlCommand(updateStok, conn);
if (command4.ExecuteNonQuery() == 1)
{
MessageBox.Show("Data berhasil disimpan!");
}
else
{
MessageBox.Show("Data tidak berhasil disimpan!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
closeConnection();
}
runQuery(insertQuery1);
runQuery(insertQuery2);
loadTransaksi();
}
I try to do it with expressions:
// QUERY
string query1 = "SELECT * "
+ "FROM Url_tabl "
+ "WHERE ID = (SELECT MAX(id) FROM Url_tabl)";
db.Execute(query1);
But the request does not work.
I tried for the test to check whether there is a connection to the database table.
To do this, use the expression:
string query1 = "delete from url_tabl";
This expression works.
To create a Recordset with the last entry from a database table, I tried several queries, but they do not work.
I get an error:
- "Cannot start a sample query."
string query1 = "select top 1 * "
+ "from url_tabl "
+ "order by id desc";
string query1 = "select max(id) "
+ "from url_tabl ";
string query1 = "select * "
+ "from url_tabl "
+ "where max(id)";
string query1 = "Select top 1 * "
+ "FROM Url_tabl "
+ "order by id desc";
"Recordset" I plan to use in this method.
public void TestDAOTransferToAccess()
{
try
{
DAO.DBEngine dbEngine = new DAO.DBEngine();
DAO.Database db = dbEngine.OpenDatabase(#"C:\db\db_test.accdb", false, false); // ++
// QUERY
string query1 = "SELECT * "
+ "FROM Url_tabl "
+ "WHERE ID = (SELECT MAX(id) FROM Url_tabl)";
db.Execute(query1); // Работает
DAO.Recordset rs = db.OpenRecordset("Url_tabl");
for (int i = 0; i < 10; i++)
{
rs.AddNew();
rs.Fields["status_url"].Value = "status_url_" + i;
rs.Fields["url"].Value = "status_url_" + i;
rs.Update();
}
rs.Close();
db.Close();
}
catch (Exception ex)
{
throw;
}
}
How to create a record with the latest record from a database table?
string connetionString = null;
SqlConnection connection;
SqlCommand command;
SqlDataAdapter adpter = new SqlDataAdapter();
DataSet ds = new DataSet();
XmlReader xmlFile;
string sql = null;
int ID = 0;
string Name = null, Text = null, Screenname = null;
connetionString = "myconnection";
connection = new SqlConnection(connetionString);
xmlFile = XmlReader.Create("my.XML", new XmlReaderSettings());
ds.ReadXml(xmlFile);
int i = 0;
connection.Open();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
ID = Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[0]);
Text = ds.Tables[0].Rows[i].ItemArray[1].ToString().Replace("'", "''");
Name = ds.Tables[0].Rows[i].ItemArray[2].ToString().Replace("'", "''");
Screenname = ds.Tables[0].Rows[i].ItemArray[3].ToString().Replace("'", "''");
//sql = "insert into nicktest values(" + ID + ",'" + Text + "'," + Name + "," + Screenname + "," + DateTime.Now.ToString() + ")";
sql = "If Exists(Select * from niktest2 Where Id = ID) " +
" BEGIN " +
" update niktest2 set Name = '" + Text + "' , Screenname = '" + Name + "', Profimg= '" + Screenname + "', InsertDateTime= '" + DateTime.Now.ToString() + "' where Id=ID" +
" END " +
" ELSE " +
" BEGIN " +
" insert into niktest2(Id,Name,Screenname,Profimg,InsertDateTime) values('" + ID + "','" + Text + "','" + Name + "','" + Screenname + "' ,'" + DateTime.Now.ToString() + "')" +
" END ";
command = new SqlCommand(sql, connection);
adpter.InsertCommand = command;
adpter.InsertCommand.ExecuteNonQuery();
}
}
after running this code only first row gets updated even my xml file is having more data.
i Want to insert all data into database with assign id to it in xml file.
Please help..
As soon as you have inserted one row, this condition will be true:
If Exists(Select * from niktest2 Where Id = ID)
So you will perform the update, rather than the insert, so you will only ever get one row in the database.
Since you are using SQL Server 2008 I would adopt a completely different approach, using Parameterised queries, MERGE, and table valued parameters.
The first step would be to create your table valued parameter (I have had to guess at your type:
CREATE TYPE dbo.nicktestTableType AS TABLE
(
Id INT,
Name VARCHAR(255),
Screenname VARCHAR(255),
Profimg VARCHAR(255)
);
Then you can write your MERGE statement to upsert to the database:
MERGE nicktest WITH (HOLDLOCK) AS t
USING #NickTestType AS s
ON s.ID = t.ID
WHEN MATCHED THEN
UPDATE
SET Name = s.Name,
Screenname = s.Screenname,
Profimg = s.Profimg,
InsertDateTime = GETDATE()
WHEN NOT MATCHED THEN
INSERT (Id, Name, Screenname, Profimg, InsertDateTime)
VALUES (s.Id, s.Name, s.Screenname, s.Profimg, GETDATE());
Then you can pass your datatable to the query as a parameter:
using (var command = new SqlCommand(sql, connection))
{
var parameter = new SqlParameter("#NickTestType", SqlDbType.Structured);
parameter.Value = ds.Tables[0];
parameter.TypeName = "dbo.nicktestTableType";
command.Parameters.Add(parameter);
command.ExecuteNonQuery();
}
If you don't want to make such a drastic change, then you should at the very least use parameterised queries, so your SQL would be:
IF EXISTS (SELECT 1 FROM nicktest WHERE ID = #ID)
BEGIN
UPDATE nicktest
SET Name = #Name,
ScreenName = #ScreeName,
InsertDateTime = GETDATE()
WHERE ID = #ID;
END
ELSE
BEGIN
INSERT (Id, Name, Screenname, Profimg, InsertDateTime)
VALUES (#ID, #Name, #Screenname, #Profimg, GETDATE());
END
Or preferably still using MERGE as the HOLDLOCK table hint prevents (or at least massively reduces the chance of) a race condition:
MERGE nicktest WITH (HOLDLOCK) AS t
USING (VALUES (#ID, #Name, #ScreenName, #ProfImg)) AS s (ID, Name, ScreenName, ProfImg)
ON s.ID = t.ID
WHEN MATCHED THEN
UPDATE
SET Name = s.Name,
Screenname = s.Screenname,
Profimg = s.Profimg,
InsertDateTime = GETDATE()
WHEN NOT MATCHED THEN
INSERT (Id, Name, Screenname, Profimg, InsertDateTime)
VALUES (s.Id, s.Name, s.Screenname, s.Profimg, GETDATE());
This will be considerably less efficient than the first solution though using table-valued parameter
Then your c# would be something like:
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("#ID", ds.Tables[0].Rows[i][0]);
command.Parameters.AddWithValue("#Name", ds.Tables[0].Rows[i][1]);
command.Parameters.AddWithValue("#ScreeName", ds.Tables[0].Rows[i][2]);
command.Parameters.AddWithValue("#ProfImg", ds.Tables[0].Rows[i][3]);
command.ExecuteNonQuery();
}
}
I have the following function:
private static DataTable GetDataFromDatabase(DateTime myDate)
{
DataTable table = new DataTable();
table.Columns.AddRange(new DataColumn[]
{
new DataColumn("Event"), new DataColumn("Room"),
new DataColumn("From"), new DataColumn("To"), new DataColumn("Persons"),
new DataColumn("Equipment"), new DataColumn("Catering")
});
string strSQL = "SELECT distinct ID FROM VIEW_RAUMBUCHUNG_DISPO " +
"WHERE BOOKSTATUS >= 1 AND convert(char, von,104) = '" +
BookITVbSQL.to_104(myDate) + "'";
SqlDataReader objRS;
objRS = SQLrunReaderDP(strSQL);
while (objRS.Read())
{
using (SqlConnection con = new SqlConnection(GetConnectionString()))
{
using (SqlCommand cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "SELECT distinct EVENT, ROOM, CONVERT(char(5), from, 108) " +
"FROM, CONVERT(char(5), to, 108) TO, PERSONS FROM VIEW_RAUMBUCHUNG_DISPO " +
"WHERE ID = '" + objRS["ID"] + "'; " +
"SELECT EQUIPMENTNAME FROM EQUIPMENT WHERE BUCHUNG_ID = '" + objRS["ID"] +
"' and STATUS = '2'; " +
"SELECT CATERINGNAME FROM CATERING WHERE BUCHUNG_ID = '" + objRS["ID"] +
"' and STATUS = '1';";
using (SqlDataReader rdr = cmd.ExecuteReader())
{
do
{
while (rdr.Read())
{
table.Rows.Add(
rdr["EVENT"],
rdr["ROOM"],
rdr["FROM"],
rdr["TO"],
rdr["PERSONS"] );
}
}
while (rdr.NextResult());
rdr.Close();
}
con.Close();
}
}
}
return table;
}
This works fine for the first Statement. I can get all the Data from the five Columns.
But how can i Add the Columns from the other two Querys to the same Row?
If i try:
while (rdr.Read())
{
table.Rows.Add(
rdr["EVENT"],
rdr["ROOM"],
rdr["FROM"],
rdr["TO"],
rdr["PERSONS"],
rdr["EQUIPMENTNAME"]);
}
so iam getting an IndexOutOfRange - Exception.
Can someone help me with that please?
SqlDataReader class:
Provides a way of reading a forward-only stream of rows from a SQL Server database.
You can use this class make a single statement with 2 joins. It will return 7 columns
"SELECT distinct EVENT, ROOM, CONVERT(char(5), from, 108) FROM, CONVERT(char(5), to, 108) TO, PERSONS, EQUIPMENTNAME, CATERINGNAME FROM VIEW_RAUMBUCHUNG_DISPO T1"
+ "INNER JOIN (SELECT EQUIPMENTNAME FROM EQUIPMENT) T2 ON T1.ID = T2.BUCHUNG_ID"
+ "INNER JOIN (SELECT CATERINGNAME FROM CATERING) T3 ON T1.ID = T3.BUCHUNG_ID" +
+ "WHERE T1.ID = '" + objRS["ID"] + "' AND T2.STATUS = '2' AND T3.STATUS = '1' "
UPDATE
Use NextResult method:
Advances the data reader to the next result, when reading the results of batch Transact-SQL statements
If you need to access whole recordset, rather than row at a time you can use SqlDataAdapter (SqlDataAdapter vs SqlDataReader).
I am new in asp & sql server. I have a problem in sql query.
string obal ;
decimal _obalss = 0;
decimal obalss = 0;
sconnection c = new sconnection();
string cus_id = Session["cusid"].ToString();
DateTime maxdate = DateTime.Parse(fromdt.Text, new System.Globalization.CultureInfo("en-US"));
string mdate = maxdate.ToString();
string query_sl = "select sum(amount) as amount from sale where cusid = " + cus_id + " and invdate < " + maxdate + " group by cusid";
SqlDataReader dr = c.reader(query_sl);
if (dr.Read())
{
decimal.TryParse(dr["amount"].ToString(), out _obalss);
obalss = _obalss;
}
else
{
obalss = 0;
}
dr.Close();
dr.Dispose();
string query_sl = "select sum(amount) as amount from sale where cusid = " + cus_id + " and invdate < " + maxdate + " group by cusid";
maxdate is a date, you have to put it in single quotes. Even better you should use parameterized SQL queries otherwise you are vulnerable to SQL injection attacks. How about something like this:
string query_sl = "select sum(amount) as amount from sale where cusid = #CUSID and invdate < #MAXDATE group by cusid";
using(SqlCommand cmd = new SqlCommand(query_sl, c))
{
cmd.Parameters.Add(new SqlParameter("#CUSID", SqlDbType.Int)).Value = cus_id;
cmd.Parameters.Add(new SqlParameter("#MAXDATE", SqlDbType.DateTime)).Value = maxdate;
...
}
string query_sl = "select sum(amount) as amount from sale where cusid = " + cus_id + " and invdate < '" + maxdate + "' group by cusid";
Notice the single quotes around maxdate...