コード例 #1
0
        //Inserting data into database
        public bool Insert(FastFoodClass f)
        {
            //Creating default return type and setting its value to false
            bool isSuccess = false;

            //Step 1 Connect database
            SqlConnection conn = new SqlConnection(myconnstrng);

            try
            {
                //Step 2 Creating SQL query to insert data
                string sql = "INSERT INTO fastFood(Name, Address, PhoneNo) VALUES (@Name, @Address, @PhoneNo)";

                //Creating sql command using sql and conn
                SqlCommand cmd = new SqlCommand(sql, conn);
                //Create parameter to add data
                cmd.Parameters.AddWithValue("@Name", f.Name);
                cmd.Parameters.AddWithValue("@PhoneNo", f.PhoneNo);
                cmd.Parameters.AddWithValue("@Address", f.Address);
                cmd.Connection = conn;

                //Connection open
                conn.Open();
                int rows = cmd.ExecuteNonQuery();
                //If the query runs then the value of rows will be > 0 else it will be 0
                if (rows > 0)
                {
                    isSuccess = true;
                }
                else
                {
                    isSuccess = false;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                conn.Close();
            }
            return(isSuccess);
        }