Skip to content
Advertisement

Executing a SQL query with C#

I would like to add some information to my database. I searched for some tutorials, but none of them work.

NonQuery can do what he needs to do, because the messagebox returns “Success” (1). But it does not update my database. If I put the same query to “Add New Query”, directly to my database, it works.

Can someone help me?

My class code at the moment:

namespace BurnThatFat
{
    class databaseconnection
    {
        //fields
        SqlConnection connection;
        string connectionstring;

        public databaseconnection()
        {
            // fields waarde toewijzen
            connectionstring = @"Data Source=(LocalDB)MSSQLLocalDB;" +
                @"AttachDbFilename=|DataDirectory|Database2.mdf;Integrated Security=True";
            connection = new SqlConnection(connectionstring);
            OpenConnection();
            CloseConnection();
        }

        public List<Object> getObjectsFromDatabase()
        {
            try
            {
                OpenConnection();
                // sql query
                // Datareader
                // sqlcommand
                // return list van objecten , objecten veranderd naar jouw wens van data.
                CloseConnection();
            }
            catch (Exception)
            {
                throw;
            }
            return new List<object>();
        }

        private bool OpenConnection()
        {
            try
            {
                connection.Open();
                return true;
            }
            catch (MySqlException ex)
            {
                switch (ex.Number)
                {
                    case 0:
                        MessageBox.Show("Cannot connect to server.  Contact administrator");
                        break;
                    case 1045:
                        MessageBox.Show("Invalid username/password, please try again");
                        break;
                }
                return false;
            }
        }

        private bool CloseConnection()
        {
            try
            {
                connection.Close();
                return true;
            }
            catch (MySqlException ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }

        public void AddGebruiker()
        {
            string query = "insert into Gebruiker VALUES(3, 'Cihan', 'Kurt', 18, 'Man', 85, 75, 'Admin1', 'Test123', 'testen');";
            using (connection)
            {
                SqlCommand command = new SqlCommand(query, connection);
                OpenConnection();
                int resultaat = command.ExecuteNonQuery();
                if (resultaat == 1)
                {
                    MessageBox.Show("succes");
                }
                else
                {
                    MessageBox.Show("fail");
                }
            }
        }
    }
}

Edit:

And this is the code for my buttons etc:

   using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

// voor sql connectie.
using System.Data.SqlClient;



namespace BurnThatFat
{
    public partial class SignUp : Form
    {

        databaseconnection db = new databaseconnection();

        public SignUp()
        {
            InitializeComponent();
            gb_login.Visible = false;
            gb_Voornaam.Visible = false;
            gb_Achternaam.Visible = false;
            gb_leeftijdgeslacht.Visible = false;
            gb_gewicht.Visible = false;
            gb_email.Visible = false;
            gb_Start.Visible = true;


        }


        private void btn_SignUp_Click(object sender, EventArgs e)
        {
            gb_Start.Visible = false;
            gb_Voornaam.Visible = true;
        }

        private void btn_login_Click(object sender, EventArgs e)
        {
            gb_Start.Visible = false;
            gb_login.Visible = true;
        }

        private void btn_loginvolgende_Click(object sender, EventArgs e)
        {
            gb_login.Visible = false;
            // hier moet nog een GB!!!!!!
        }

        private void btn_voornaamvolgende_Click(object sender, EventArgs e)
        {


            gb_Voornaam.Visible = false;
            gb_Achternaam.Visible = true;
        }

        private void btn_achternaamvolgende_Click(object sender, EventArgs e)
        {
            gb_Achternaam.Visible = false;
            gb_leeftijdgeslacht.Visible = true;
        }

        private void btn_leeftijdvolgende_Click(object sender, EventArgs e)
        {
            gb_leeftijdgeslacht.Visible = false;
            gb_gewicht.Visible = true;
        }


        // einde registratie
        // opslaan van gegevens in database
        private void btn_emailvolgende_Click(object sender, EventArgs e)
        {
            // gebruiker = new Gebruikerklasse();
           // gebruiker.Naam = Convert.ToString(tb_voornaam.Text);
           //// gebruiker.Achternaam = Convert.ToString(tb_achternaam.Text);
          //  gebruiker.Leeftijd = Convert.ToInt32(nud_leeftijd.Value);
          ///  gebruiker.Geslacht = Convert.ToString(cb_geslacht.Text);
          //  gebruiker.Huidig_gewicht = Convert.ToInt32(nud_huidiggewicht.Value);
          //  gebruiker.Streef_gewicht = Convert.ToInt32(nud_streefgewicht.Value);
          ///  gebruiker.Gebruikersnaam = Convert.ToString(tb_gebruikersnaam2.Text);
          //  gebruiker.Email = Convert.ToString(tb_email.Text);
         //   gebruiker.Wachtwoord = Convert.ToString(tb_wachtwoordsignup.Text);

            db.AddGebruiker();
            gb_email.Visible = false;
            // hier moet nog een GB!!!!!

        }

        private void btn_gewichtvolgende_Click(object sender, EventArgs e)
        {
            gb_gewicht.Visible = false;
            gb_email.Visible = true;
        }
    }
}    

Advertisement

Answer

The simplest way to insert into a SQL Server database:

string connectionString = @"Data Source=(LocalDB)MSSQLLocalDB;AttachDbFilename=|DataDirectory|Database2.mdf;Integrated Security=True";

string commandText = "INSERT INTO MyTable (ID, Name, Address) VALUES (10, 'Bob', '123 Main Street');";

using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(commandText, conn))
{
    conn.Open();
    cmd.ExecuteNonQuery();
    conn.Close();
}

As long as commandText is a working query, it should insert a row. It would be better to use parameters for your values instead of hard coding them like I did here – that avoids SQL injection attacks and other potential problems. You can search Google for that (or the question you are asking now) and find tons of resources to help you.

If you need more specific help, post details such as what is actually happening when you try to run your code – are you getting an exception?

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement