MySQL query not works (C#) - c#

I try to update my MYSQL table with this code.
string sqlquery = String.Format("if exists(select 1 from orders where id =\" {0}\" ) begin update orders set customer_id = \"{1}\", total = \"{2}\", fio = \"{3}\", adress =\" {4}\" where id = \"{0}\" end else begin insert into orders (id, customer_id, total, fio, adress) values(\"{0}\", \"{1}\", \"{2}\", \"{3}\", \"{4}\") end", id, customer_id, total, fio, adress);
MySqlCommand addCommand2 = new MySqlCommand(sqlquery.ToString(), connection);
addCommand2.ExecuteNonQuery();
But I have this error
Additional information: 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 'if exists(select 1 from orders where id = 1913 ) begin update orders set custome' at line 1
Database
What wrong in query?
Thank's for help!

why dont you do it in more elegant way:Something like.:
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "if exists(select 1 from orders where id =#id)
begin
update orders set customer_id = #customer_id, total = #total, fio = #fio, adress =#adress where id = #id end
else
begin insert into orders (id, customer_id, total, fio, adress) values(#id, #customer_id, #total, #fio,#adress) end";
command.Parameters.AddWithValue("#id", val1);
command.Parameters.AddWithValue("#customer_id", val2);
command.Parameters.AddWithValue("#total", val3);
command.Parameters.AddWithValue("#fio", val4);
command.Parameters.AddWithValue("#adress", val5);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}

Related

C# pass parameters to Postgres Npgsqlcommand DO block

I get the error "42883: operator does not exist: integer =# integer" Npgsql.PostgresException
when trying to pass parameters to a DO block:
var cmd = new NpgsqlCommand();
cmd.CommandText =
#"DO $$
BEGIN
IF EXISTS (SELECT id FROM pub.table1 WHERE id = #id) THEN
UPDATE pub.table1
SET Field1 = #Field1
,Field2 = #Field2
WHERE id = #id;
ELSE
INSERT INTO pub.table1 (id, Field1, Field2)
VALUES (#id, #Field1, #Field2);
END IF;
END $$;";
cmd.Parameters.AddWithValue("#id", 1);
cmd.Parameters.AddWithValue("#Field1", "text");
cmd.Parameters.AddWithValue("#Field2", "text2");
Otherwise connection to postgres works and also (classic) queries work when passing parameters; e.g.:
cmd.CommandText = #"SELECT * FROM pub.table1 WHERE id = #id;";
Is it not possible to pass parameters to a "DO" block or am I missing something?
Thank you.
M

Web API to call a stored procedure to insert/update DB

I have been working on creating the Web API that accepts the input parameter and calls a Stored Procedure passing the input parameter we received that insert/updates the Account Table in the Database. Now that is perfectly , but my API also need to select the record which was updated/inserted and return them as response
public class ProjectNameCreationController : ApiController
{
[HttpGet]
public HttpResponseMessage Get(string Account)
{
if (string.IsNullOrEmpty(Account))
{
return Request.CreateResponse(new { error = "Input parameters cannot be Empty or NULL" });
}
string strcon = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
SqlConnection DbConnection = new SqlConnection(strcon);
DbConnection.Open();
SqlCommand command = new SqlCommand("[dbo].[usp_InserUpadte]", DbConnection);
command.CommandType = CommandType.StoredProcedure;
//create type table
DataTable table = new DataTable();
table.Columns.Add("AccountID", typeof(string));
table.Rows.Add(Account);
SqlParameter parameter = command.Parameters.AddWithValue("#account_TT", table);
parameter.SqlDbType = SqlDbType.Structured;
parameter.TypeName = "account_TT";
command.ExecuteNonQuery();
Now I am not sure if we will able to select the record that was now insert/updated as part of the Stored Procedure or will I have to create a Query seperately like below
string strQuery = "select AccountID,CounterSeq from Account where AccountID = #accountID ";
var cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#accountID",Account);
Because I will have to Return the response as AccountID-CounterSeq (Eg: IT-1) when the API is called like http://localhost/api/ProjectNameCreation?Account=IT. How can I deal with this. Any help is greatly appreciated
You have to change your procedure as below it will return a record of last inserted or updated.
**--for insert**
IF #StatementType = 'Insert'
BEGIN
insert into Account (first_name,last_name,salary,city) values( #first_name, #last_name, #salary, #city)
--below line to return last inserted record
select * from Account where accountid= SCOPE_IDENTITY()
END
**--for Update**
IF #StatementType = 'Update'
BEGIN
UPDATE Account SET
First_name = #first_name, last_name = #last_name, salary = #salary,
city = #city
WHERE accountid= #accountid
--below line to return last Updated record
select * from account where accountid = #accountid

Two ExecuteScalar then query

I'm looking for a way to check if a customer ID exists in the Customer table, and if it exists in the table being queried.
If it doesn't exist in the Customer table or it already exists in the table being queried (or it is in Customer but also already exists in table in question) then I don't want it to insert the data.
I thought that maybe I could do if..if code - more code - if..if code - else, but that didn't work. Here is what I mean:
cmd.CommandText = "SELECT COUNT(*) FROM Customer WHERE customer_id = #cid";
cmd.Connection = conn;
conn.Open();
int count = (int)cmd.ExecuteScalar();
conn.Close();
if (count < 1)
{
System.Web.HttpContext.Current.Response.Write("<script>alert('Customer ID does not exist and will not be submitted')</script>");
tb0.Focus();
}
cmd.CommandText = "SELECT COUNT(*) FROM table_name WHERE customer_id = #cid";
cmd.Connection = conn;
conn.Open();
int count2 = (int)cmd.ExecuteScalar();
conn.Close();
if(count2 > 0)
{
System.Web.HttpContext.Current.Response.Write("<script>alert('Customer ID already exists in table_name and will not be submitted')</script>");
tb0.Focus();
}
else
{
cmd.CommandText = "INSERT INTO table_name VALUES(#cid, #val1, #val2, #val3, #val4, #val5)";
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close(); }
Unless I comment one out then the second one will work and the first I guess gets ignored? I'm not really sure but they both work if the other is commented out
Errors from answer:
Incorrect syntax near the keyword 'THEN'.
Incorrect syntax near the keyword 'ELSE'.
Incorrect syntax near the keyword 'THEN'.
Incorrect syntax near the keyword 'ELSE'.
#"IF NOT EXISTS (SELECT * FROM Customer WHERE customer_id = #cid) THEN BEGIN
SELECT 'NO_CUSTOMER' as Result
END ELSE IF EXISTS (SELECT * FROM table_name WHERE customer_id = #cid) THEN BEGIN
SELECT 'ALREADY_RECORD' as Result
END ELSE BEGIN
INSERT INTO table_name VALUES(#cid, #val1, #val2, #val3, #val4, #val5);
SELECT 'SUCCESS' AS Result;
END";
Why not try something a bit simpler, like this?
cmd = conn.CreateCommand();
cmd.CommandText =
#"IF NOT EXISTS (SELECT * FROM Customer WHERE customer_id = #cid) THEN BEGIN
SELECT 'NO_CUSTOMER' as Result
END ELSE IF EXISTS (SELECT * FROM table_name WHERE customer_id = #cid) THEN BEGIN
SELECT 'ALREADY_RECORD' as Result
END ELSE BEGIN
INSERT INTO table_name VALUES(#cid, #val1, #val2, #val3, #val4, #val5);
SELECT 'SUCCESS' AS Result;
END";
cmd.Parameters.AddWithValue(#cid, ...);
cmd.Parameters.AddWithValue(#val1, ...);
cmd.Parameters.AddWithValue(#val2, ...);
...
switch((string)cmd.ExecuteScalar()) {
case "NO_CUSTOMER":
System.Web.HttpContext.Current.Response.Write("<script>alert('Customer ID does not exist and will not be submitted')</script>");
tb0.Focus();
break;
case "ALREADY_RECORD":
System.Web.HttpContext.Current.Response.Write("<script>alert('Customer ID already exists in table_name and will not be submitted')</script>");
tb0.Focus();
break;
}

Inserting a row into a sql table in c# with autoincrement primary key

How do I execute a table insert command when the ID column is the primary key and set to autoincrement?
I've tried the following:
using (SqlConnection conn = new SqlConnection(connstring))
{
SqlCommand identChange = conn.CreateCommand();
identChange.CommandText = "SET IDENTITY_INSERT table1 ON";
conn.Open();
string commtext = #"Insert INTO table1 (ID, Username)
SELECT #ID, #User";
SqlCommand comm = new SqlCommand(commtext, conn);
comm.Parameters.AddWithValue("#ID", -1);
comm.Parameters.AddWithValue("#User", loggedinuser);
identChange.ExecuteNonQuery();
comm.ExecuteNonQuery();
conn.Close();
}
but regardless of what value is put into ID (i've tried 0 and -1), it creates a new row with that value under the ID column. As a result, when I try to insert the next row, it gives me an error since now I have two rows with the same ID.
You just don't have to mention the column if it is a autoincrement column.
string commtext = #"Insert INTO table1 (Username) SELECT #User";
SqlCommand comm = new SqlCommand(commtext, conn);
comm.Parameters.AddWithValue("#User", loggedinuser);
You say something like this:
int addUser( string userName )
{
if ( string.IsNullOrWhiteSpace(userName) throw new ArgumentException("invalid user name" , "userName") ;
int user_id ;
string connectString = GetSomeConnectString() ;
using ( SqlConnection connection = new SqlConnection( connectString ) )
using ( SqlCommand cmd = connection.CreateCommand() )
{
cmd.CommandType = CommandType.Text ;
cmd.CommandText = #"
insert dbo.user ( user_name ) values ( #user_Name )
select user_id = ##SCOPE_IDENTITY
" ;
cmd.Parameters.AddWithValue( "#user_name" , userName ) ;
connection.Open() ;
user_id = (int) cmd.ExecuteScalar() ;
connection.Close() ;
}
return user_id ;
}
any column with an identity property (or autoincrementing column) can't be specified on the insert. You have to specify the columns whose value you are supplying. Any columns not supplied must be nullable, have a default constraint or be an auto-incrementing column.
Unless you want to explicitly set the ID you don't set IDENTITY_INSERT ON otherwise use the auto incremented value.
using (SqlConnection conn = new SqlConnection(connstring))
{
conn.Open();
string commtext = #"Insert INTO table1 (Username)
SELECT #User";
SqlCommand comm = new SqlCommand(commtext, conn);
comm.Parameters.AddWithValue("#User", loggedinuser);
identChange.ExecuteNonQuery();
comm.ExecuteNonQuery();
conn.Close();
}

C# SQL stored procedure (which inserts) - pass parameters and retrieve parameter

I have a stored procedure on my server that inserts some parameters and returns the ID that was inserted. I am writing a form to do this easily but I cannot seem to get the parameter which is passed back.
To save you doing a whole bunch of possibly pointless reading, it's probably better to just pay attention to my C# code and let me know what I need to do in order to pass parameters and get one in return.
C# Default.aspx
connection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionInfo"]);
sql = "aStoredProc";
command = new SqlCommand(sql, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameter.Add(new SqlParameter("#FirstName", SqlDbType.VarChar)).Value = sFirstname;
command.Parameter.Add(new SqlParameter("#SurName", SqlDbType.VarChar)).Value = sSurname;
connection.Open();
int ID = command.ExecuteNonQuery();
connection.Close();
SQL aStoredProc
IF EXISTS(SELECT * FROM aTable WHERE ID = #ID)
-- User exists, update details
BEGIN
BEGIN TRAN
UPDATE aTable
SET
FirstName = #FirstName,
SurName = #SurName,
LastUpdate = GetDate()
WHERE ID = #ID
IF (##Error != 0)
ROLLBACK TRAN
ELSE
COMMIT TRAN
END
ELSE
-- New user
BEGIN
BEGIN TRAN
INSERT aTable (
FirstName,
SurName,
GetDate()
)
VALUES (
#FirstName,
#SurName,
#LastUpdate
)
SELECT #ID = ##IDENTITY
IF (##Error != 0)
ROLLBACK TRAN
ELSE
COMMIT TRAN
END
The parameter #ID is listed in the stored proc as:
#ID (int, Input/Output, No default)
and proc has 'Return integer'. This used to work fine with a VBA solution prior to a SQL Server 2005 upgrade.
Thanks in advance.
connection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionInfo"]);
sql = "aStoredProc";
command = new SqlCommand(sql, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameter.Add(new SqlParameter("#FirstName", SqlDbType.VarChar)).Value = sFirstname;
command.Parameter.Add(new SqlParameter("#SurName", SqlDbType.VarChar)).Value = sSurname;
command.Parameter.Add(new SqlParameter("#SurName", SqlDbType.VarChar)).Value = sSurname;
SqlParameter ParamId = cmd.Parameters.Add( "#Id", SqlDbType.Int);
ParamId.Direction = ParameterDirection.InputOutput;
command.Parameter.Add(ParamId);
connection.Open();
command.ExecuteNonQuery();
int ID = ParamId.Value;
connection.Close();
you have to add output paramter in Parameter collection.
Read Value like above.
You have an error in your SQL, it should look like this:
INSERT aTable (FirstName,SurName,LastUpdate)
VALUES (#FirstName, #SurName, GetDate() )
Not like this:
INSERT aTable (
FirstName,
SurName,
GetDate()
)
VALUES (
#FirstName,
#SurName,
#LastUpdate
)

Categories

Resources