SQL insert clause.

MiPakTeh 1,476 Reputation points
2022-06-13T07:57:36.07+00:00

Hi All,
I just do a simple database for learning.Create Database and Table, ok but when to INSERT statement error area "Column Name" for button_4.

Here some code to trying.
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;
using System.Data.SqlClient;

namespace Store_6  
{  
    public partial class Form1 : Form  
    {  
        public Form1()  
        {  
            InitializeComponent();  
            button1.Text = "Create Database";  
            button2.Text = "Create Table";  
            button3.Text = "Data Analisis";  
            button4.Text = "Save";  
            button5.Text = "Update";  
  
  
  
        }  
  
        private void button1_Click(object sender, EventArgs e)  
        {  
            SqlConnection conn = new SqlConnection(@"server=(localdb)\v11.0");  
            using (conn)  
            {  
                conn.Open();  
                string sql = string.Format(@"CREATE DATABASE [TRIAL] ON PRIMARY (NAME=TRIAL_a, FILENAME='{0}\TRIAL.mdf')  
                            LOG ON (NAME=TRIAL_log, FILENAME='{0}\TRIAL.ldf')", @"C:\Users\family\Documents\");  
                SqlCommand command = new SqlCommand(sql, conn);  
                command.ExecuteNonQuery();  
            }  
        }  
  
        private void button2_Click(object sender, EventArgs e)  
        {  
            SqlConnection conn = new SqlConnection(@"server=(localdb)\v11.0");  
            SqlCommand command = new SqlCommand(@"CREATE TABLE Store(Lokasi varchar(200), Nitrogen decimal, Phosphate decimal, Kalium real)",conn);  
            conn.Open();  
            command.ExecuteNonQuery();  
        }  
  
        private void button3_Click(object sender, EventArgs e)  
        {  
            SqlDataAdapter da = new SqlDataAdapter("Select * from Store", @"server=(localdb)\v11.0");  
            DataSet ds = new DataSet();  
            da.Fill(ds, "Store");  
            dataGridView1.DataSource = ds.Tables["Store"].DefaultView;  
        }  
  
  
  
        private void button4_Click(object sender, EventArgs e)  
        {  
            string StrQuery = "";  
  
            for (int i = 0; i < dataGridView1.Rows.Count; i++)  
            {  
  
            SqlConnection conn = new SqlConnection(@"server=(localdb)\v11.0");  
            conn.Open();  
            SqlCommand comm = new SqlCommand(StrQuery, conn);  
  
                StrQuery = @"INSERT INTO Store VALUES ("+ dataGridView1.Rows[i].Cells[0].Value + dataGridView1.Rows[i].Cells[1].Value + dataGridView1.Rows[i].Cells[2].Value + dataGridView1.Rows[i].Cells[3].Value +")";  
  
                comm.CommandText = StrQuery;  
                comm.ExecuteNonQuery();  
            }  
  
              
  
  
        }  
  
        private void button5_Click(object sender, EventArgs e)  
        {  
  
        }  
  
        private void button6_Click(object sender, EventArgs e)  
        {  
  
        }  
  
        private void button7_Click(object sender, EventArgs e)  
        {  
  
        }  
    }  
}  
  
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-06-13T13:55:14.46+00:00

    I slapped together a code sample with all that should be needed. Tested adding a record and modifying a record.

    The following _ = new SqlCommandBuilder(_sqlDataAdapter); glues things together.

    Code can be optimized and perhaps placed into a class method.

    using System;  
    using System.Data;  
    using System.Data.SqlClient;  
    using System.Windows.Forms;  
      
    namespace DataAdapterFormApp  
    {  
        public partial class Form1 : Form  
        {  
            private static string ConnectionString =  
                "Data Source=.\\sqlexpress;Initial Catalog=ForumExample;Integrated Security=True";  
      
            private SqlDataAdapter _sqlDataAdapter = new SqlDataAdapter();  
            private readonly DataSet _dataSet = new DataSet();  
            private readonly SqlConnection connection = new SqlConnection(ConnectionString);  
      
            public Form1()  
            {  
                InitializeComponent();  
                Shown += OnShown;  
            }  
      
            private void OnShown(object sender, EventArgs e)  
            {  
                _sqlDataAdapter = new SqlDataAdapter(  
                    "SELECT id, FirstName, LastName, HiredDate FROM dbo.employee;",   
                    connection);  
      
                _sqlDataAdapter.Fill(_dataSet);  
                _ = new SqlCommandBuilder(_sqlDataAdapter);  
                dataGridView1.DataSource = _dataSet.Tables[0];  
                dataGridView1.Columns[0].ReadOnly = true;  
            }  
      
            private void UpDateAllButton_Click(object sender, EventArgs e)  
            {  
                _sqlDataAdapter.Update(_dataSet);  
            }  
        }  
    }  
      
    

    EDIT

    If only adding records, the above can be altered to use the following SELECT statement which returns zero rows and in this case only new records (and modifications to new records are done)

    SELECT TOP 0 id, FirstName, LastName, HiredDate FROM dbo.employee;  
    
    0 comments No comments

3 additional answers

Sort by: Most helpful
  1. Olaf Helper 47,441 Reputation points
    2022-06-13T08:08:04.783+00:00

    StrQuery = @"INSERT INTO Store VALUES ("+ dataGridView1.Rows[i].Cells[0].Value + dataGridView1.Rows[i].Cells[1].Value + dataGridView1.Rows[i].Cells[2].Value + dataGridView1.Rows[i].Cells[3].Value +")";

    You concat all values to one big string, that don't work, they must be comma-separated values, see https://learn.microsoft.com/en-us/sql/t-sql/statements/insert-transact-sql?view=sql-server-ver16 => Samples.

    Better use parameterized statements, see https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlparameter?view=dotnet-plat-ext-6.0

    0 comments No comments

  2. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2022-06-13T08:58:48.187+00:00

    There is no need to write SQL as a SqlDataAdapter when used correctly does updates for you. Take time to read the documentation along with making the SqlDataAdapter a private scoped field in your form.


  3. Jack J Jun 25,296 Reputation points
    2022-06-13T09:33:36.43+00:00

    @MiPakTeh , Welcome to Microsoft Q&A, based on my test, I reproduced your problem.

    First, Please set dataGridView1.AllowUserToAddRows to be false in your constructor.

    Second, Please ensure that your database has the data, otherwise you will add empty row to the table.

    Third, Please use string.format method in your button4_click event, like the following:

    private void button4_Click(object sender, EventArgs e)  
            {  
                string StrQuery = "";  
      
                for (int i = 0; i < dataGridView1.Rows.Count; i++)  
                {  
      
                    SqlConnection conn = new SqlConnection(@"str");  
                    conn.Open();  
                    SqlCommand comm = new SqlCommand(StrQuery, conn);  
                    StrQuery = String.Format("INSERT INTO Store VALUES('{0}',{1},{2},{3})", dataGridView1.Rows[i].Cells[0].Value, dataGridView1.Rows[i].Cells[1].Value, dataGridView1.Rows[i].Cells[2].Value, dataGridView1.Rows[i].Cells[3].Value);  
                    //StrQuery = @"INSERT INTO Store VALUES (" + dataGridView1.Rows[i].Cells[0].Value + dataGridView1.Rows[i].Cells[1].Value + dataGridView1.Rows[i].Cells[2].Value + dataGridView1.Rows[i].Cells[3].Value + ")";  
      
                    comm.CommandText = StrQuery;  
                    comm.ExecuteNonQuery();  
                }  
                Console.WriteLine("success created");  
            }  
    

    Hope my advice could help you.

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.