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..");
Related
How to write mysql update query for updating multiple rows of datagridview in single statement by passing parameters and then executing all together in c#.net windows application
for example create update query like is given below
foreach(DatagridViewRow dr in datagridview)
{
sql = "update table1 set name=#name where id=#id; update table1 set name=#name where id=#id; update table1 set name=#name where id=#id;"
}
How to create a sql query with parameters? So that after creation of query; we can execute it together to make changes in multiple rows.
You don't need to put multiple Update queries together.
Here take a look:
string sql = "update table1 set name=#name where id=#id";
MySqlParameter pId = new MySqlParameter("#id", SqlDbType.BigInt);
MySqlParameter pName = new MySqlParameter("#name", SqlDbType.NVarchar);
cmd.Parameters.Clear();
cmd.CommandText = query;
cmd.Parameters.Add(pName);
cmd.Parameters.Add(pId);
foreach(DatagridViewRow dr in datagridview)
{
pId.Value = dr.Rows["iDColumn"].ToString();
pName.Value = dr.Rows["nameColumn"].ToString();
cmd.ExecuteNonQuery();
}
Hope this helps.
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();
I iterate over an external source and get a list of strings. I then insert them into the DB using:
SqlCommand command = new SqlCommand(commandString, connection);
command.ExecuteNonQuery();
Where commandString is an insert into command. i.e.
insert into MyTable values (1, "Frog")
Sometimes the string contains ' or " or \ and the insert fails.
Is there an elegant way to solve this (i.e. #"" or similar)?
Parameters.
insert into MyTable values (#id, #name)
And
int id = 1;
string name = "Fred";
SqlCommand command = new SqlCommand(commandString, connection);
command.Parameters.AddWithValue("id", id);
command.Parameters.AddWithValue("name", name);
command.ExecuteNonQuery();
Now name can have any number of quotes and it'll work fine. More importantly it is now safe from sql injection.
Tools like "dapper" (freely available on NuGet) make this easier:
int id = 1;
string name = "Fred";
connection.Execute("insert into MyTable values (#id, #name)",
new { id, name });
You should look into using parameterized queries. This will allow you insert the data no matter the content and also help you avoid possible future SQL injection.
http://csharp-station.com/Tutorial/AdoDotNet/Lesson06
http://www.c-sharpcorner.com/uploadfile/puranindia/parameterized-query-and-sql-injection-attacks/
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);
I have this stored procedure in my SQL Server;
CREATE PROC GetChild
#Child_ID int
AS
SELECT * FROM Children WHERE Child_ID = #Child_ID
I am calling this stored procedure from C#.
I would like to know, if it is possible to call just one column from this table instead of the whole record from C#.?
Assuming you mean return one column, if this is what your stored procedure looks like then no. It will always return all columns back to the client.
You can simply ignore the returned columns that you do not need. Or you can change the stored procedure to only return one column. But as is, it always returns all of them.
You have only have three choices.
Rewrite the Stored procedure to just return the columns you want.
e.g. SELECT foo from Children Where Child_id = #Child_ID
Use a DataReader and just get the columns you want from that
Using a reader directly
while (reader.Read())
`Console.WriteLine("{0}", reader.GetInt32(0));`
Using the Linq extension methods which allows you to filter and sort the results as well as getting just the columns you want.
var List = rdr.Cast<IDataRecord>()
.Select(s => s.GetInt32(0)).ToList();
Abandon the stored procedure and write Select statements against the table. See Pranay's answer
just write below query
select columnname from Children where Child_ID = #Child_ID
columnname- is name of the column you want to retrive
Code for you
SqlConnection mySqlConnection =new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText ="select columnname from Children where Child_ID = #Child_ID";
mySqlCommand .Parameters.Add("#Child_ID", SqlDbType.Int);
mySqlCommand .Parameters["#Child_ID"].Value = idvalue;
mySqlConnection.Open();
SqlDataReader mySqlDataReader = mySqlCommand.ExecuteReader(CommandBehavior.SingleRow);
while (mySqlDataReader.Read()){
Console.WriteLine("mySqlDataReader[\" columnname\"] = " +
mySqlDataReader["columnname"]);
}
mySqlDataReader.Close();
mySqlConnection.Close();
Use a SqlDataReader for this:
SqlConnection DbConn = new SqlConnection(YourConnStringHere);
SqlCommand ExecStoredProc = new SqlCommand();
ExecStoredProc.CommandType = CommandType.StoredProcedure;
ExecStoredProc.CommandText = "GetChild";
ExecStoredProc.Connection = DbConn;
ExecStoredProc.Parameters.AddWithValue("#ChildID", YourChildId);
using (DbConn)
{
DbConn.Open();
using (SqlDataReader sdr = ExecStoredProc.ExecuteReader())
{
while(sdr.Read())
// reference your column name like this:
// sdr.GetString(sdr.GetOrdinal("YourColumnName"));
}
}
You can reference any column returned by the SqlDataReader.Read() method. Likewise, if you are looking for an integer value:
int someInt = sdr.GetInt32(sdr.GetOrdinal("YourColumnName"));
From this thread ( Insert results of a stored procedure into a temporary table ), you might want to try OPENROWSET.
First, configure your DB,
sp_configure 'Show Advanced Options', 1
GO
RECONFIGURE
GO
sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO
then, depending on your connection :
SELECT yourcolumnname
FROM
OPENROWSET(
'SQLNCLI',
'server=yourservername;database=yourdbname;uid=youruserid;pwd=youruserpwd',
'EXEC [GetChild] yourchildid'
)
or
SELECT yourcolumnname
FROM
OPENROWSET(
'SQLNCLI',
'server=yourservername;database=yourdbname;Trusted_Connection=yes',
'EXEC [GetChild] yourchildid')
I wouldn't use this solution when retrieving only one line. Performance would be really bad.
For retrieving a great number of lines, this should do the job.