1

I'm Experimenting with databases and I'm finding different methods to optimize my codes. Here I'm using a different class to stop re writing the same codes such as for add, Delete and update we use the same ExecuteNonQuery() method. So far Update delete methods worked well except the Insert. Compiler doesn't give any errors but the values taken from the text boxes doesn't go to the variable string query. I'm new to c# coding. Can anyone help me? or an advice?

using DBconnectionExercise.DBConnection_Components;
namespace DBconnectionExercise
{
    public partial class Student_Form : Form
    {
        DBComps dc = new DBComps();

        //public string constring;
        //public SqlConnection con = null;
        //public SqlCommand com = null;
        public String query;

        public Student_Form()
        {
            InitializeComponent();

            //constring = "Data Source=ASHANE-PC\\ASHANESQL;Initial Catalog=SchoolDB;Integrated Security=True";
            //con = new SqlConnection(constring);

            dc.ConnectDB();


        }

        private void Form1_Load(object sender, EventArgs e)
        {

           loadGridData();

        }
        private void dtp_dob_ValueChanged(object sender, EventArgs e)
        {
            DateTime Now = DateTime.Today;
            DateTime Dob = dtp_dob.Value.Date;
            int a = Now.Year - Dob.Year;
            if (Now < Dob.AddYears(a)) a--;
            tb_Age.Text = a.ToString();
        }

        private void loadGridData()
        {
            try
            {
                query = "Select * from tb_Student";
                //dc.OpenCon();
                //SqlDataAdapter da = new SqlDataAdapter(query, con);
                DataTable dt1 = new DataTable();
                dt1 = dc.Data_Table(query);
                //da.Fill(dt);
                Stu_DataGrid.DataSource = dt1;
                //con.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void ClearData()
        {
            tb_Name.Clear();
            tb_Address.Clear();
            tb_Telno.Clear();
            tb_Search.Clear();
            tb_Age.Clear();
            dtp_dob.Value = DateTime.Today;

        }

        private void btn_Add_Click(object sender, EventArgs e)
        {
            try
            {
                String name = tb_Name.Text;
                DateTime dob = dtp_dob.Value.Date;
                int age = Convert.ToInt32(tb_Age.Text);
                String Address = tb_Address.Text;
                int telno = Convert.ToInt32(tb_Telno.Text);
                int line = 0;


                //con.Open();
                query = "Insert into tb_Student values(@Stu_Name, @Stu_DOB, @Age, @Stu_Address, @Stu_Tel_no)";
                //query = "Insert into tb_Student (Stu_Name, Stu_DOB, Age, Stu_Address, Stu_Tel_no) Values('" + name + "','" + dob + "','" + age + "','" + Address + "','" + telno + "')";
                MessageBox.Show(query);
                //com = new SqlCommand(query, con);

               // This is the Insert/save code

                DBComps.com.Parameters.AddWithValue("@Stu_Name", name);
                DBComps.com.Parameters.AddWithValue("@Stu_DOB", dob);
                DBComps.com.Parameters.AddWithValue("@Age", age);
                DBComps.com.Parameters.AddWithValue("@Stu_Address", Address);
                DBComps.com.Parameters.AddWithValue("@Stu_Tel_no", telno);

                //line = com.ExecuteNonQuery();
                line = dc.ExeNonQuery(query);
                //com.Dispose();
                //con.Close();

                if (line > 0)
                {
                    loadGridData();
                    ClearData();
                    MessageBox.Show("Data saved sucessfully!", "Data Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                    MessageBox.Show("Data not Saved", "Error Save", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

This is the DBComps class which I used to write the Sql Function methods.

 namespace DBconnectionExercise.DBConnection_Components
    {
        public class DBComps
        {
            public String conSring;
            public SqlConnection con = null;
            public static SqlCommand com = null;

            public void ConnectDB()
            {
                conSring = "Data Source=ASHANE-PC\\ASHANESQL;Initial Catalog=SchoolDB;Integrated Security=True";
                con = new SqlConnection(conSring);
            }

            public void OpenCon()
            {
                con.Open();
            }

            public void CloseCon()
            {
                con.Close();
            }

            public int ExeNonQuery(String query) //the method for Insert, update and delete.
            {

                int line = 0;
                OpenCon();
                com = new SqlCommand(query, con);
                line = com.ExecuteNonQuery();
                com.Dispose();
                CloseCon();

                return line;
            }
    }
} 
Ashane Alvis
  • 770
  • 2
  • 18
  • 42
  • Each time you call `dc.ExeNonQuery` you create new command instance `com = new SqlCommand(query, con);`, thus losing all the parameters you added to the previous `com` value before. The simplest solution is to stop creating a new command instance each time, replacing it by setting the [command text property](https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.commandtext(v=vs.110).aspx) of the existing command(!!!it can be null first time!!!). – Eugene Podskal Jun 14 '15 at 19:30
  • P.S.: And it is a bad idea to mix instance methods and static fields when it is not required by any actual need. Also, [using](https://msdn.microsoft.com/en-us/library/yh598w02.aspx) statement may be of interest for you. – Eugene Podskal Jun 14 '15 at 19:31
  • @EugenePodskal Yes exactly silly me. I removed all of them and I finally found the answer. Thanks for the help. – Ashane Alvis Jun 17 '15 at 17:21

2 Answers2

2

This is really really bad way of talking to database, its hackable using SQL injection and since you are learning, its right time to point this out:

query = "Insert into tb_Student values('"+ name +"','"+ dob +"','"+ age +"','"+ Address +"','"+ telno +"')";

read up on sql injection as to why and how, and look for best practices to find out better ways .

Mladen Oršolić
  • 1,352
  • 3
  • 23
  • 43
  • Now I see that i'm in great danger. I should use parameters for this problem. Also fixed an annoying bug in the Date time picker. Wow thanks for letting me know of SQL injection. – Ashane Alvis Jun 19 '15 at 17:17
1

OK finally I came up with the Answer to my question as I expected. Here how to do this;

private void btn_Add_Click(object sender, EventArgs e)
        {
            try
            {
                String name = tb_Name.Text;
                DateTime dob = dtp_dob.Value.Date;
                int age = Convert.ToInt32(tb_Age.Text);
                String Address = tb_Address.Text;
                int telno = Convert.ToInt32(tb_Telno.Text);
                int line = 0;


                query = "Insert into tb_Student values('"+ name +"','"+ dob +"','"+ age +"','"+ Address +"','"+ telno +"')";

                MessageBox.Show(query); //To see it works!

                line = dc.ExeNonQuery(query);

                if (line > 0)
                {
                    loadGridData();
                    ClearData();
                    MessageBox.Show("Data saved sucessfully!", "Data Saved", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                    MessageBox.Show("Data not Saved", "Error Save", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        } 

Always remember to write the query statement variables/values exactly as to coincide with the table headers. Otherwise it will generate errors. Thanks everyone for helping with this question! :-)

Ashane Alvis
  • 770
  • 2
  • 18
  • 42