Search code examples
c#databaseoledboledbcommandoledbdataadapter

How to insert data in single column(cell) of new row in c#?


I have an .accdb file with four tables in it

Product_Particulars
Cust_Details
Variable_fields
Permanant_fields

The number of column in the 'Variable_fields' table is not fixed (changed using 'ALTER TABLE' OleDb nonQuery). But it has two fixed columns 'Tranx_ID', 'Tranx_time'.

I want to accomplish something that will enable me to add data in the 'Tranx_ID' Column in a new row from a textBox without caring about other columns in the table (i.e. other cells in that row, in which the 'textBox.Text' is attempted to insert) and save the row with data in only one cell.

N.B.: I am actually using OleDb & I will use the 'Tranx_ID' for Updating that particular row using an OleDbCommand like,

"UPDATE Variable_fields " +
"SET [This column]='" +thistxtBx.Text +
     "',[That column]='" +thattxtBx.Text +
 "'WHERE ([Tranx_ID]='" +textBox.Text+ "')";

Solution

  • The exception is caused by the fact that one or more of the columns that you don't insert cannot have NULL as value. If you can remove this flag and allow a null value then your INSERT could work or not for other reasons.

    Indeed you use a string concatenation to build your query and this is a well known source of bugs or a vector for an hacking tecnique called Sql Injection (I really suggest you to document yourself about this nasty problem)

    So your code could be the following

    string query = @"UPDATE Variable_fields 
                     SET [This column]= @this,
                         [That column]=@that
                     WHERE ([Tranx_ID]=@trans";
    using(OleDbConnection con = new OleDbConnection(....constringhere....))
    using(OleDbCommand cmd = new OleDbCommand(query, con))
    {
       con.Open();
       cmd.Parameters.Add("@this", OleDbType.VarWChar).Value = thisTextBox.Text;
       cmd.Parameters.Add("@that", OleDbType.VarWChar).Value = thatTextBox.Text;
       cmd.Parameters.Add("@trans", OleDbType.VarWChar).Value = transTextBox.Text;
       int rowsInserted = cmd.ExecuteNonQuery();
       if(rowsInserted > 0)
           MessageBox.Show("Record added");
       else
           MessageBox.Show("Record NOT added");
    }
    

    Helpful links:

    Sql Injection explained
    Give me parameterized query or give me death
    Using statement