I want to execute a .sql
script from C#. Basically the script inserts a row into few different tables.
The point is I have values in C# code that I need to pass to the .sql
query. These values will be collected during program execution.
Here is the query that I want to execute from C# code:
INSERT INTO [DB].[dbo].[User]
([Id]
,[AccountId]
,[FirstName]
,[LastName]
,[JobTitle]
,[PhoneNumber]
)
VALUES
('00A640BD-1A0D-499D-9155-BA2B626D7B68'
,'DCBA241B-2B06-48D7-9AC1-6E277FBB1C2A'
,'Mark'
,'Wahlberg'
,'Actor'
,'9889898989'])
GO
The values will vary from time to time i.e., they are captured in C# code and need to be passed.
Can anyone please help me do this..I am learning both C# and SQL. Thanks a lot.
Expand the database that you want, expand Programmability, and then expand Stored Procedures. Right-click the user-defined stored procedure that you want and select Execute Stored Procedure. In the Execute Procedure dialog box, specify a value for each parameter and whether it should pass a null value.
A parameterized query (also known as a prepared statement) is a means of pre-compiling a SQL statement so that all you need to supply are the "parameters" (think "variables") that need to be inserted into the statement for it to be executed. It's commonly used as a means of preventing SQL injection attacks.
You could open yourself up to SQL injection attacks here, so best practice is to use parameters:
using (SqlConnection dbConn = new SqlConnection(connectionString))
{
dbConn.Open();
using (SqlTransaction dbTrans = dbConn.BeginTransaction())
{
try
{
using (SqlCommand dbCommand = new SqlCommand("insert into [DB].[dbo].[User] ( [Id], [AccountId], [FirstName], [LastName], [JobTitle], [PhoneNumber] ) values ( @id, @accountid, @firstname, @lastname, @jobtitle, @phonenumber );", dbConn))
{
dbCommand.Transaction = dbTrans;
dbCommand.Parameters.Add("id", SqlType.VarChar).Value = id;
dbCommand.Parameters.Add("accountid", SqlType.VarChar).Value = accountId;
dbCommand.Parameters.Add("firstname", SqlType.VarChar).Value = firstName;
dbCommand.Parameters.Add("lastname", SqlType.VarChar).Value = lastName;
dbCommand.Parameters.Add("jobtitle", SqlType.VarChar).Value = jobTitle;
dbCommand.Parameters.Add("phonenumber", SqlType.VarChar).Value = phoneNumber;
dbCommand.ExecuteNonQuery();
}
dbTrans.Commit();
}
catch (SqlException)
{
dbTrans.Rollback();
throw; // bubble up the exception and preserve the stack trace
}
}
dbConn.Close();
}
This is a good article for beginners with ADO.Net
EDIT - Just as a bit of extra info, I've added a transaction to it so if the SQL command fails it will rollback.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With