Question

Write a robust ADO.NET connectIon-oriented code snippet which inserts a record (with parameters coming from the...

Write a robust ADO.NET connectIon-oriented code snippet which inserts a record (with parameters coming from the user, assume these are already stored in some variables) into the following table: StudentID, Name, YearOfBirth). Make sure you avoid SQL injection type attacks by using a parameterized SQL query. StudentID is an automatically generated column, provided by the database.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
try{

//create  object  of Connection 
SqlConnection conn = new SqlConnection();

// Set Connection String property of Connection object
conn.ConnectionString = "Data Source=<Enter your Own>;Initial Catalog=<Database Name> ;IntegratedSecurity=True";

//Open Connection
conn.Open();

//Create object of Command Class
SqlCommand cmd = new SqlCommand();

//set Connection Property  of  Command object
cmd.Connection = conn;
//Command type for command object
//1.StoredProcedure
//2.TableDirect
//3.Text   (By Default)

cmd.CommandType = CommandType.Text;

//Set Command text Property of command object

cmd.CommandText = "Insert into <TableName> (StudentID,Name,YearOfBirth) values ('@id','@name',@yob)";

//Assign values as `parameter`. It avoids `SQL Injection`
//Make sure Values have proper Validation before inserting

cmd.Parameters.AddWithValue("id", <Variable>);
cmd.Parameters.AddWithValue("name", <Variable>);
cmd.Parameters.AddWithValue("yob", <Variable>);
//For Update,Delete,Insert Query
cmd.ExecuteNonQuery(); 

//THIS IS MOST IMPORTANT FROM PROGRAMMING POINT OF VIEW
conn.Close();

}catch(Exception ex){

conn.Close();

}

Add a comment
Know the answer?
Add Answer to:
Write a robust ADO.NET connectIon-oriented code snippet which inserts a record (with parameters coming from the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT