Home > Software engineering >  basic inserting data into database sql
basic inserting data into database sql

Time:06-04

hello guys I'm a newbie in MS visual studio and I want to make a database system that allows the user to insert, update, delete and search data using windows form application.

I already watched 3 tutorial how but I'm getting the same error. when I delete my "executenonquery()" it doesn't have any error but the data I putted in my textbox is not inserted into my database. when I put it back I'm getting this kind of error

database

CodePudding user response:

As a newbie, getting the pieces working first, then applying to the user interface I would apply second. I will try to summarize each piece. First your connection itself looked strange as others have pointed out. I would try to first make sure the connection itself works before applying any attempt at sql insert/update/delete going on. So you might try

   SqlConnection connection = new SqlConnection(
@"Data Source (LocalDB)\MSSQLLocalDB; AttachDbFilename=C:\Users\Adrian\Documents\EaglePlannersDataBase.mdf;
Integrated Security=True;
Connect Timeout=30" );

private void TestConnect()
{
   if( connection.Open() )
      // great, you have a good connection
      connection.Close();
   else
      // message to yourself why a failed connection and fix it...
}

Once you know your connection is good, then on to your sql-insert. Having good column names is important. Dont try to be fancy with human readable with spaces types of column names, just causes headaches. Use simple and direct as others have pointed out in prior comments. Also, when parameterizing, I have tried to always slightly alter the insert/update/delete parameters with a "p" prefix indicating the PARAMETER FOR the column, such as

insert into SomeTable ( oneColumn, secondCol ) values ( @pOneColumn, @pSecondCol )

just to avoid bad confusion. If an error comes out via "oneColumn" vs "pOneColumn" in the message, you KNOW which thing is at fault. The column itself does not work, or the specific parameter/value being supplied.

Next, readability of your SQL statements, especially as they get longer. Use spaces and I typically use a leading "@" before the quoted sql command to allow for line continuations as I edited your previous answer. So the same above insert would be written more like

   var cmd = new SqlCommand(
@"insert into SomeTable
 ( oneColumn,
   secondCol
 )
 values
 ( @pOneColumn,
   @pSecondCol
  )", connection );

So if you ever needed to add additional columns (or remove), you can see the paired set of insert columns vs parameters much easier.

Now the testing. Don't try to work off some user-entered values, put in known VALID values so you dont have to worry about user entered values. Get the command to WORK, then pull values from interface later. (continuing from above sample)

cmd.Parameters.AddWithValue("@pOneColumn", 17 );
cmd.Parameters.AddWithValue("@pSecondCol", "some Text");
        

Then try to execute that and make sure IT works. Once it does, THEN start pulling from your user interface

cmd.Parameters.AddWithValue("@pOneColumn", int.Parse( yourTextControl.Text ));
cmd.Parameters.AddWithValue("@pSecondCol", anotherTextControl.Text );

Find your mistakes BEFORE you let any human interaction get into and screw-up the rest of what you think SHOULD work.

Note, if you make public properties to your view models such as

public int someAge {get; set;}

and then set the bindings of the data entry control in the screen to this someAge property, it will only allow a numeric entry to be entered and will otherwise have a value of zero if someone tries to put in text. Similarly if you are dealing with dates, and if date/time, always use datetime fields for querying purposes vs formatted date as a text field. You will thank yourself in the future when querying for things within date range periods. HTH

Finally,try to avoid using AddWithValue. Instead, properly identify the expected data type as described in the linked article. I just left original context to your code for testing and debug researching purposes.

CodePudding user response:

This would be the possible answer on your question, what I have done here, first I changed your connection string by removing AttachDbFilename attribute, and replace that by adding of Initial Catalog attribute where I set the name of your database. Next thing, I declared variables where the values from textboxes will be stored, these values of variables will be our parameters, this is not necessary to do, it is just my own style, you can keep as you done. I have seen also, that you are not using try/catch/finally block and you are closing the connection in the same part of code where you opening the connection, and maybe that is the reason why your values are not being stored into the table, so I decided to round your code within that block. If you don't know what is try/catch/finally block you can read the documentation here . We are opening the connection and do all operations on database in try block, in catch block we are catching all errors that might be caused in our application and in finally we are closing the connection. You will also notice that I created additional check, where I checking the result of ExecuteNonQuery() method, and if result of ExecuteNonQuery method is equals to 1 - records is inserted successfully, otherwise it fails.

using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.SqlClient;
    using System.Threading.Tasks;
    
    namespace EaglePlannersDatabase
    {
        public partial class Form1 : Form
        {
            SqlConnection connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=EaglePlannersDataBase;Integrated Security=True;Connect Timeout=30");
            public Form1()
            {
                InitializeComponent();
            }
    
            private void label1_Click(object sender, EventArgs e)
            {
    
            }
    
            private void InsertButton_Click(object sender, EventArgs e)
            {
                int policyNumber = Convert.ToInt32(policyNumbertxtbox.Text);
                string planType = planTypetxtbox.Text;
                int renewalDate = Convert.ToInt32(renewalDatetxtbox.Text);
                string name = nametxtbox.Text;
                int age = Convert.ToInt32(agetxtbox.Text);
                string address = addresstxtbox.Text;
                int birthday = Convert.ToInt32(birthdaytxtbox.Text);
                string email = emailtxtbox.Text;
                int homeOfficeNumber = Convert.ToInt32(homeofficetxtbox.Text);
                string modeOfPayment = modeofpaymenttxtbox.Text;
                int amount = Convert.ToInt32(ammounttxtbox.Text);
                
                try
                {
                    connection.Open();
                
                    SqlCommand cmd = new SqlCommand("Insert Into tbl1 (PolicyNumber,planType,renewalDate,name,age,address,birthday,email,homeOfficeNumber,modeOfPayment,ammount) values (@PolicyNumber,@planType,@renewalDate,@name,@age,@address,@birthday,@email,@homeOfficeNumber,@modeOfPayment,@ammount)", connection);
                    cmd.Parameters.AddWithValue("@PolicyNumber",policyNumber);
                    cmd.Parameters.AddWithValue("@planType",planType);
                    cmd.Parameters.AddWithValue("@renewalDate",renewalDate);
                    cmd.Parameters.AddWithValue("@name",name);
                    cmd.Parameters.AddWithValue("@age",age);
                    cmd.Parameters.AddWithValue("@address",address);
                    cmd.Parameters.AddWithValue("@birthday",birthday);
                    cmd.Parameters.AddWithValue("@email",email);
                    cmd.Parameters.AddWithValue("@homeOfficeNumber",homeOfficeNumber);
                    cmd.Parameters.AddWithValue("@modeOfPayment",modeOfPayment);
                    cmd.Parameters.AddWithValue("@ammount",amount);
                    int result = cmd.ExecuteNonQuery();
                    if(result == 1)
                    {
                    
                        MessageBox.Show("Record Inserted Successfully!");
                        policyNumbertxtbox.Text = "";
                        planTypetxtbox.Text = "";
                        renewalDatetxtbox.Text = "";
                        nametxtbox.Text = "";
                        agetxtbox.Text = "";
                        addresstxtbox.Text = "";
                        birthdaytxtbox.Text = "";
                        emailtxtbox.Text = "";
                        homeofficetxtbox.Text = "";
                        modeofpaymenttxtbox.Text = "";
                        ammounttxtbox.Text = "";
                    }
                    else
                    {
                        MessageBox.Show("Something went wrong!");
                    }
                }
                catch(SqlException ex)
                {
                    MessageBox.Show("We have found error with operation on database: "   ex.Message);
                }
                catch(Exception ex)
                {
                    MessageBox.Show("We have found error in your code: "   ex.Message);
                }
                finally
                {
                    connection.Close();
                }
            }
        }
    }
  • Related