-2

I have a string that I want to insert into a column of a table using a sql command. If I have

string someText = 'onetwothreetest';
clsDB.ExecuteSQL("INSERT INTO tbl_SOMETABLE (SOMECOLUMN) VALUES (????)")

How would I put the string, someText, into the ???? without it giving me an error.

Clemens
  • 123,504
  • 12
  • 155
  • 268
TeddyBear
  • 1
  • 1

2 Answers2

0

Please refer to this post Parameterize SQL query

You need to create a Command Object and add Specify SQL, Parameters

using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
    command.CommandText = "INSERT INTO Contacts ([First], [Last], [Address], [City], [State], [ZIP]) VALUES (@first, @last, @address, @city, @state, @zip)";

    command.Parameters.AddWithValue("@first", first);
    // or
    // command.Parameters.Add("@first", SqlDbType.Type).Value = first;
    // ...

    connection.Open();
    command.ExecuteNonQuery();
}
ullfindsmit
  • 279
  • 1
  • 5
  • 20
  • You should check out [Can we stop using AddWithValue() already?](http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/) and stop using `.AddWithValue()` - it can lead to unexpected and surprising results... – marc_s Sep 25 '20 at 04:00
  • ::thumbsup:: thanks – ullfindsmit Sep 25 '20 at 14:26
-1

You can simply do this:

 string someText = 'onetwothreetest';
 clsDB.ExecuteSQL($"INSERT INTO tbl_SOMETABLE (SOMECOLUMN) VALUES ({someText})")
Gauravsa
  • 6,330
  • 2
  • 21
  • 30