C# SQL Update query wont work - c#

SqlCommand insertCoins = new SqlCommand("UPDATE [Table] SET coins =
#rouletteCoins
WHERE steamid = #userid", cnn);
insertCoins.Parameters.AddWithValue("#rouletteCoins", coins);
insertCoins.Parameters.AddWithValue("#userid", info);
insertCoins.ExecuteScalar();
Trying to send a basic query to the database, it works with insert and select but not with update. Help would be much appreciated.

Use ExecuteNonQuery() instead of ExecuteScalar(). Use this (ExecuteNonQuery) for insert, update and delete statements.

Related

SQL query result to C# Variable

I'm trying to pull data from an SQL variable in C# to use in another SQL query.
Basically I have a for loop that is running through a datagrid and inserting the data into a table which I need to be linked to #DataID in this query below. As it is in a different query I can't access it so I want to pull it out into a var.
What's the best way to go about this? already searched lots of options and not coming up with anything that works
The help is appreciated!
Cheers
string dartBoxQuery = #"DECLARE #DataID int;
INSERT INTO DartBox (DartBoxNumber, ReturnDate, Comments)
VALUES (#dbn, #rtndate, #cmmts)
SELECT #DataID = scope_identity();";
// set up the command before exec
SqlCommand cmd = new SqlCommand(dartBoxQuery, con);
//set parameters
cmd.Parameters.AddWithValue("#rtndate", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("#dbn", textBox1.Text);
cmd.Parameters.AddWithValue("#cmmts", textBox2.Text);
// call SQL connection
con.Open();
// execute above query
cmd.ExecuteNonQuery();
//close connection
con.Close();
If you want to fetch #DataID back to the caller, there are 3 options:
declare an output parameter... presumably just moving #DataID to be an output parameter rather than a local variable; add an extra parameter and give it the direction of ParameterDirection.Output; after the ExecuteNonQuery, read out the value
at the end of your existing SQL, return #DataID; add an extra parameter and give it the direction of ParameterDirection.ReturnValue; after the ExecuteNonQuery, read out the value
at the end of your existing SQL, select #DataID; use ExecuteScalar and read out the return value
In this case, ExecuteScalar is probably the easiest option:
string dartBoxQuery = #"DECLARE #DataID int;
INSERT INTO DartBox (DartBoxNumber, ReturnDate, Comments)
VALUES (#dbn, #rtndate, #cmmts)
SELECT #DataID = scope_identity();
SELECT #DataID";
// set up the command before exec
SqlCommand cmd = new SqlCommand(dartBoxQuery, con);
//set parameters
cmd.Parameters.AddWithValue("#rtndate", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("#dbn", textBox1.Text);
cmd.Parameters.AddWithValue("#cmmts", textBox2.Text);
// call SQL connection
con.Open();
// execute above query
var dataId = Convert.ToInt32(cmd.ExecuteScalar());
//close connection
con.Close();

How to insert a value to MySQL C#

I have do some calculation in C# and i want insert that value to MySql database. Example totalPrice= Price1+Price2; I want pass the totalPrice into my table. How to do that?
You need to use an INSERT statement. It's probably best to use parameterized queries rather than just an INSERT command.
MySqlCommand command = new MySqlCommand();
string sql = "INSERT INTO YourTable (TotalPrice) VALUES (#TotalPrice)";
command.Parameters.AddWithValue("#TotalPrice", totalPrice);
Then remember to execute your query. command.ExecuteNonQuery();
If you are using EntityFramework...
yourTable obj = new yourTable();
obj.name = "name";
obj.created = DateTime.Now;
etc.......
ctx.yourTable.Add(obj);
ctx.SaveChanges();
or
ctx.Database.ExecuteSqlCommand("Insert intoy YourTable values etc..");

Return last inserted ID without using a second query

I'm working on an ASP.NET project (C#) with SQL Server 2008.
When I insert a row into a table in the database, I would like to get the last inserted ID, which is the table's IDENTITY (Auto Incremented).
I do not wish to use another query, and do something like...
SELECT MAX(ID) FROM USERS;
Because - even though it's only one query - it feels lame...
When I insert something I usually use ExecuteNonQuery(), which returns the number of affected rows.
int y = Command.ExecuteNonQuery();
Isn't there a way to return the last inserted ID without using another query?
Most folks do this in the following way:
INSERT dbo.Users(Username)
VALUES('my new name');
SELECT NewID = SCOPE_IDENTITY();
(Or instead of a query, assigning that to a variable.)
So it's not really two queries against the table...
However there is also the following way:
INSERT dbo.Users(Username)
OUTPUT inserted.ID
VALUES('my new name');
You won't really be able to retrieve this with ExecuteNonQuery, though.
You can return the id as an output parameter from the stored procedure, e.g. #userId int output
Then, after the insert, SET #userId = scope_identity()
even though it's only one query - it feels lame...
It actually is also wrong as you can have multiple overlapping iserts.
That is one thing that I always fuind funny - people not reading the documentation.
SELECT SCOPE_IDENTITY()
returns the last identity value generated in a specific scope and is syntactically correct. It also is properly documented.
Isn't there a way to return the last inserted ID without using another query?
Yes. Ask for the number in the saame SQL batch.
INSERT (blablab9a); SELECT SCOPE_IDENTITY ();
as ONE string. ExecuteScalar.
You can have more than one SQL statement in one batch.
If you want to execute query from C# code & want to get last inserted id then you have to find the following code.
SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
connection.Open();
string sql = "Insert into [Order] (customer_id) values (" + Session["Customer_id"] + "); SELECT SCOPE_IDENTITY()";
SqlCommand cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
var order_id = cmd.ExecuteScalar();
connection.Close();
Console.Write(order_id);

UPSERT query/syntax in OLE DB (MS Access)

For SQL Server, I could do this
UPDATE [Table] SET b=2, c=3 WHERE a=1;
IF ##ROWCOUNT=0
INSERT INTO [Table] (a,b,c) VALUES (1,2,3)
How do you do a similar thing on MS Access (using OleDbConnection)?
Doing that I got
Characters found after end of SQL statement.
I don't think the Jet/ACE OleDB engine has an equivalent of T-SQL syntax for this kind of problem.
You should go for the long route of checking if record exist, then decide for INSERT or UPDATE.
However, being Access mainly a single/local user database system you should not have many problems doing something like this pseudocode:
using(OleDbConnection cn = new OleDbConnection(constring))
{
cn.Open();
using(OleDbCommand cmd = new OleDbCommand("select count(*) from table where pkID = ?", cn);
{
cmd.Parameters.AddWithValue("pk", myID);
int result = Convert.ToInt32(cmd.ExecuteScalar());
if(result == 0)
// do your insert command here
else
// do your update command here
}
}
Of course, as I have said, this doesn't take into account concurrency problems.

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