Is this a correct form of inserting values to database?

Madhu V 1 Reputation point
2022-11-13T12:18:39.53+00:00

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class appointment : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=USER ;Initial Catalog=Project;Integrated Security=True");
string uname;
protected void Page_Load(object sender, EventArgs e)
{

}  
protected void Button1_Click(object sender, EventArgs e)  
{  
}  
protected void Calendar1_SelectionChanged(object sender, EventArgs e)  
{  

}  
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)  
{  

}  
protected void Button1_Click1(object sender, EventArgs e)  
{  

    uname = Session["email"].ToString();  
    con.Open();  
    string sql = "insert into appointmt values('" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','"+TextBox6.Text+"','"+TextBox7.Text+"','" + DropDownList1.SelectedItem.Text + "')";  
    SqlCommand cmd = new SqlCommand(sql, con);  
    cmd.ExecuteNonQuery();  
    Response.Write("<script>alert('Booked successfully')</script>");\  

con.close();
}
}

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,625 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. AgaveJoe 27,656 Reputation points
    2022-11-13T12:29:03.013+00:00

    Is this a correct form of inserting values to database?

    No. The correct approach is using a parameter query.

    Configuring parameters and parameter data types

    0 comments No comments

  2. Roderick Bant 2,051 Reputation points
    2022-11-13T12:38:41.667+00:00

    Hi, the example you show is quite vulnerable to SQL injection as user input is used directly in composing the SQL Query. This allows a potential attacker to enter SQL Server commands in the TextBoxes that could be harmful.

    Although written about PHP, the same principles as described in this article apply to your example.

    The documentation on SqlParameterCollections has an example on using parameterized queries, which are not vulnerable to SQL Injection, in dotnet code.

    0 comments No comments