Update the first row of two columns in SQL table - c#

I'm new to C# SQL. What im trying is to update existing Rows in my CurrencyRates Table which
has 2 columns buyEURrate and sellEURrate with type float.
on button click i want to change its values of its first rows
im getting the new data from 2 textboxes "EURbuyRate" and EURsellRate"
dont really know the syntax for it
var insertSQL = "UPDATE CurrencyRates (buyEURrate, sellEURrate) VALUES (#buyEURrate, #sellEURrate)";
string connectionString = #"Data Source=C:\Users\FluksikartoN\Documents\Visual Studio 2012\Projects\BuroFoki\BuroFoki\MainDB.sdf";
using (var cn = new SqlCeConnection(connectionString))
using (var cmd = new SqlCeCommand(insertSQL, cn))
{
cn.Open();
cmd.Parameters.Add("buyEURrate", SqlDbType.Float);
cmd.Parameters.Add("sellEURrate", SqlDbType.Float);
cmd.Parameters["buyEURrate"].Value = float.Parse(EURbuyRate.Text.ToString());
cmd.Parameters["sellEURrate"].Value = float.Parse(EURsellRate.Text.ToString());
cmd.ExecuteNonQuery();
}
On button click for update "SqlCeException was unhandeled
System error "

From your posted code looks like you are using UPDATE statement like
UPDATE CurrencyRates (buyEURrate, sellEURrate) VALUES (buyEURrate, sellEURrate);
That syntax is for INSERT and not UPDATE. Your SQL statement should looks like
UPDATE CurrencyRates SET buyEURrate = buyEURrate,
sellEURrate = sellEURrate
WHERE some_condition;

Related

How can I use results from query in c# script in visual studio

I want to run a query in a C# script in visual studio and use the results in my C# code (what I basically want to do is to store the results of the query in a table and use the elements in this table one by one).
The query looks like this in my C# script:
string Connection_sheets = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (SqlConnection connection = new SqlConnection(Connection_sheets))
{
connection.Open();
SqlCommand cmd = new SqlCommand("select distinct [Sheet Code] from cell where [Table Code] = 'Table Number' order by [Sheet Code] asc", connection);
SqlDataReader readert = cmd.ExecuteReader();
}
Here 'Table Number' is a string which comes from a column in another database table.
In the following code, which is placed in a for loop, I want to add another column where I print each time a single element from the resulting query
DataRow newRow2 = _longDataTable.NewRow();
newRow2.ItemArray = drlibrary.ItemArray;
newRow2["VariableTableCode"] = tableName;
newRow2["VariableRowCode"] = ssRowNoBars;
newRow2["VariableColumnCode"] = ssColumnNoBars;
_longDataTable.Rows.Add(newRow2);
Anyone an idea how to do this?
Within your using statement add
While(reader.read()){
DataRow datarow3= _longDataTable.NewRow();
datarow3.ItemArray = drlibrary.ItemArray;
datarow3["VariableTableCode"] = reader.tostring(0);
datarow3["VariableRowCode"] = reader.tostring(1);
datarow4["VariableColumnCode"] = reader.tostring(2);
_longDataTable.Rows.Add(datarow3);
// you may need to encrement the row name variable.
}

Update multiple checkboxlist values to SQL DB asp.net C#

I am updating a row in SQL DB using the code below. The loop works and it updates the row but the problem is that each time it goes through the loop, it only updates one value and the other values are overwritten. So at the end, it has updated but instead of multiple values being inputted to the table for the respective Project ID, it only puts one value for the respective Project ID. I am not receiving any errors for this. Any help is much appreciated.
for (int i = 0; i < cbAvailableEntities.Items.Count - 1; i++)
{
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("UpdateProjectEntity", connection);
using (connection)
{
connection.Open();
using (cmd)
{
if (cbAvailableEntities.Items[i].Selected)
{
cmd.CommandType = CommandType.StoredProcedure;
//the following is the Project ID for the row being updated.
SqlParameter paramPID = new SqlParameter("#ProjectID", nr.ProjectID);
cmd.Parameters.Add(paramPID);
nr.Entities = cbAvailableEntities.Items[i].Value;
cmd.Parameters.AddWithValue("#CorpID", nr.Entities);
cmd.ExecuteNonQuery();
}
}
}
}
Here is the SQL query for the Stored Procedure "UpdateProjectEntity"
ALTER PROCEDURE [dbo].[UpdateProjectEntity]
#ProjectID int,
#CorpID int
AS
BEGIN
UPDATE [dbo].[ProjectEntity]
SET
[CorpID] = #CorpID
WHERE
ProjectID = #ProjectID
END
Here are screenshots of inputs and results when I run the program.
These are the checkboxes I am saving to the DB
This is the result after I have saved to the DB
I changed the date to show that everything else works in this program.
I can see you save your enity INT, maybe you should save it as a Comma Separated String.
So instead of save 1, you can save 1,2,3
Of course you will have to add some logic before the save building and concat the string. And also need to do some parsing when you read from db doing the split by ,
The other aproach is creating a relation table to indicate with are the options selected.
But this is also have problem when you remove a selection and add new ones.
ProjectID CorpID
1 1
1 2
1 3
The way I resolved this without making any changes to the DB is I used a DELETE Statement to delete the rows with the ProjectID and then I used an insert stored procedure that I have used before. It was a lot faster than creating another table among all that is already in place. So the code looks like this
for (int i = 0; i < cbAvailableEntities.Items.Count - 1; i++) {
SqlConnection connection = new SqlConnection(connString);
SqlCommand com = new SqlCommand("InsertProjectEntity", connection);
SqlCommand dcm = new SqlCommand();
using(connection) {
//First time going through the loop, i = 0 is true.
if (i == 0) {
connection.Open();
using(com) {
//This will remove anything in the DB related to the ProjectID being edited.
dcm.Connection = connection;
dcm.CommandText = "DELETE FROM [dbo].[ProjectEntity] WHERE ProjectID = " + _pID;
dcm.ExecuteNonQuery();
//This will insert all items checked in the checkboxlist but will not insert the unchecked.
if (cbAvailableEntities.Items[i].Selected) {
com.CommandType = CommandType.StoredProcedure;
SqlParameter paramPID = new SqlParameter("#ProjectID", nr.ProjectID);
com.Parameters.Add(paramPID);
nr.Entities = cbAvailableEntities.Items[i].Value;
com.Parameters.AddWithValue("#CorpID", nr.Entities);
com.ExecuteNonQuery();
}
}
} else {
connection.Open();
using(com) {
//This will insert all items checked in the checkboxlist but will not insert the unchecked.
if (cbAvailableEntities.Items[i].Selected) {
com.CommandType = CommandType.StoredProcedure;
SqlParameter paramPID = new SqlParameter("#ProjectID", nr.ProjectID);
com.Parameters.Add(paramPID);
nr.Entities = cbAvailableEntities.Items[i].Value;
com.Parameters.AddWithValue("#CorpID", nr.Entities);
com.ExecuteNonQuery();
}
}
}
}

C# DatagridVIew Delete SQL date

How i make delete a data SELECTED(CHECKED) from MYSQL in datagridview in C# ?
My code:
string CONFIG = "server=localhost;userid=root;password=admin;database=program";
MySqlConnection cone = new MySqlConnection(CONFIG);
MySqlCommand query2 = new MySqlCommand();
query2.Connection = cone;
query2.CommandText = "DELETE FROM TABLE WHERE ID = #ID";
// I believe the key from this problem stay in line below//
query2.Parameters.AddWithValue("#ID", gridMovie.SelectedRows);
cone.Open();
query2.ExecuteNonQuery();
cone.Close();
SelectedRow property of the gridview gives the entire row . So you need to provide the column value (in you case it is ID) -
query2.Parameters.AddWithValue("#ID", gridMovie.SelectedRow
.Cells[indexofIDcolumn].Value)

Updating SQL table with the contents of a datatable

I am creating an application in WPF using C# where users populate a datagrid and the information is then stored in a DataTable called smb1. The following code works for inserting the data into the SQL database but when I modify the code for updating it does not work. Does anyone know how I can modify my code to allow Updates as there are no errors thrown when I run my application in Visual Studio. I must add that the Equipment column cannot be edited in the datagrid so the returned data is the same as the data taken from the database so that the updated rows will be matched to the equipment rows in the SQL database using the WHERE clause. Below is the original insertion code plus my attempt for updating the database.
Insert Code
SqlConnection con = new SqlConnection(MyConnectionString);
string SqlCmdText = "Insert into SHIFTLOG Values(#EQUIPMENT,#BATCHNO,#PRODUCTNO,#STATUS,#DATE,#PERIOD,#MACHINE)";
SqlCommand sc = new SqlCommand(SqlCmdText, con);
con.Open();
foreach (DataRow row in smb1.Rows)
{
sc.Parameters.Clear();
sc.Parameters.AddWithValue("#EQUIPMENT", row["EQUIPMENT"]);
sc.Parameters.AddWithValue("#BATCHNO", row["BATCHNO"]);
sc.Parameters.AddWithValue("#PRODUCTNO", row["PRODUCTNO"]);
sc.Parameters.AddWithValue("#STATUS", row["STATUS"]);
sc.Parameters.AddWithValue("#DATE", DateTime.Now.ToString("yyyy-MM-dd"));
sc.Parameters.AddWithValue("#PERIOD", DateTime.Now.ToString("tt"));
sc.Parameters.AddWithValue("#MACHINE", "SMB1");
sc.ExecuteNonQuery();
}
con.Close();
Attempt for Update Code
SqlConnection con = new SqlConnection(MyConnectionString);
string SqlCmdText = "UPDATE SHIFTLOG SET EQUIPMENT='#EQUIPMENT',BATCHNO='#BATCHNO',PRODUCTNO='#PRODUCTNO',STATUS='#STATUS',DATE='2013-09-12',PERIOD='#PERIOD',MACHINE='#MACHINE' WHERE EQUIPMENT='#EQUIPMENT'";
SqlCommand sc = new SqlCommand(SqlCmdText, con);
con.Open();
foreach (DataRow row in smb1.Rows)
{
sc.Parameters.Clear();
sc.Parameters.AddWithValue("#EQUIPMENT", row["EQUIPMENT"]);
sc.Parameters.AddWithValue("#BATCHNO", row["BATCHNO"]);
sc.Parameters.AddWithValue("#PRODUCTNO", row["PRODUCTNO"]);
sc.Parameters.AddWithValue("#STATUS", row["STATUS"]);
sc.Parameters.AddWithValue("#PERIOD", DateTime.Now.ToString("tt"));
sc.Parameters.AddWithValue("#MACHINE", row["MACHINE"]);
sc.ExecuteNonQuery();
}
con.Close();
Thanks for any help.
Remove the single quotes around the parameters.
string SqlCmdText = "UPDATE SHIFTLOG SET EQUIPMENT=#EQUIPMENT,BATCHNO=#BATCHNO,PRODUCTNO=#PRODUCTNO,STATUS=#STATUS,DATE='2013-09-12',PERIOD=#PERIOD,MACHINE=#MACHINE WHERE EQUIPMENT=#EQUIPMENT";
Also, I think the update section for EQUIPMENT=#EQUIPMENT is redundant, as the where clause will not be correct if it has changed. So you could use
string SqlCmdText = "UPDATE SHIFTLOG SET BATCHNO=#BATCHNO,PRODUCTNO=#PRODUCTNO,STATUS=#STATUS,DATE='2013-09-12',PERIOD=#PERIOD,MACHINE=#MACHINE WHERE EQUIPMENT=#EQUIPMENT";
remove the '' in all the parameters in your sql statement
"UPDATE SHIFTLOG SET BATCHNO=#BATCHNO,....... WHERE EQUIPMENT=#EQUIPMENT
if you use quotes all your parameters take as string values, not as SQL parameters
And also you need to use columns with [] like [DATE] if those are reserved keywords
How to deal with SQL column names that look like SQL keywords?

where condition in MySQL Insert statement

Can I use where condition in Insert statement????
I have coded like this, its showng me an error call MySQLException was unhandled, You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE RegistrationID='3'' at line 1. My code:-
MySqlCommand cmd1 = new MySqlCommand("INSERT INTO registration(DueAmount) VALUES ('"+textBox5.Text + "') WHERE RegistrationID='"+textBox2.Text+"'",connection);
You're mixing 2 different statements.
An UPDATE statement updates an existing row in your table.
An INSERT statement adds a new row in your table.
I think you want to use an UPDATE statement and modify an existing row.
MySqlCommand cmd1 = new MySqlCommand("
UPDATE Registration Set DueAmount= '"+textBox5.Text
+ "' WHERE RegistrationID='"+textBox2.Text+"'",connection);
The correct syntax of INSERT doesn't have WHERE clause. I think you want UPDATE instead of INSERT,
UPDATE registration
SET DueAmount = 'txt5'
WHERE RegistrationID = 'txt2'
the only way you can use WHERE in SELECT is when you are using INSERT INTO....SELECT statement.
one more thing, since you are using ADO.NET, make sure that you parameterized your query to avoid SQL Injection, and use USING statement.
string query = "UPDATE registration
SET DueAmount = #dateAmount
WHERE RegistrationID = #RegID"
using (MySqlCommand cmd1 = new MySqlCommand(query,connection))
{
cmd1.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#dateAmount", textBox5.Text);
cmd.Parameters.AddWithValue("#RegID", textBox2.Text);
// other codes
}
INSERT with WHERE doesn't make sense. INSERT always inserts a new row. You might be looking for REPLACE INTO which does a insert if that record doesnt exist or an update if it does based on its primary key.
INSERT puts a new line to database. You can not put a new line WHERE sth is sth. But you can UPDATE it. Hope this helps.
You need to use an UPDATE statement.
tHS SYNTAX IS SIMILAR: "UPDATE registration SET DueAmount = '" + textBox5.Text + "' WHERE RegistrationID='"+textBox2.Text+"'"
You can try with Update
var query = "UPDATE Registration SET DueAmount= $Paremeter1 WHERE RegistrationID = $Paremeter2";
var cmd1 = new MySqlCommand(query, connection);
cmd1 .Parameters.AddWithValue("$Paremeter1", textBox5.Text);
cmd1 .Parameters.AddWithValue("$Paremeter2", textBox2.Text);

Categories

Resources