Syntax problem Inserting variables into database

Discussion in 'ASP .Net' started by altergothen, Apr 19, 2004.

  1. altergothen

    altergothen Guest

    Hi there

    I am a newbie to ASP.Net - Please Help!
    I am trying to insert the values of my variables into a database.
    If I try the following it works perfectly:
    string insertQuery = "INSERT into test(name,surname,email) VALUES('Bob',
    'Sly', '')";

    but instead of inputing the values directly, I want to insert them as
    variables like so:
    string insertQuery = "INSERT into test (name,surname,email)

    The problem is that SQL requires ' ' around the values like this:
    string insertQuery = "INSERT into test (name,surname,email)

    If I do it this way the values are taken literaly so the actual words
    name,surname,email are entered into the database instead of their values?

    Please can you tell me how I can insert the varibles values into my database

    Maybe my code will explain things more clearly ............

    <%@ Page Language="C#" Debug="true" %>
    <%@ Import Namespace="System.Data" %>
    <%@ Import Namespace="System.Data.SqlClient" %>
    <title>Inserting Data into a Database</title>
    <script language="C#" runat="server">

    void Page_Load()
    string name;
    string surname;
    string email;

    string connectionStr =

    string insertQuery = "INSERT into test(name,surname,email) VALUES(name,
    surname, email)";

    SqlConnection connectObj = new SqlConnection(connectionStr);
    SqlCommand commandObj = new SqlCommand(insertQuery,connectObj);


    Inserting Data into a Database
    altergothen, Apr 19, 2004
    1. Advertisements

  2. Hi There,

    Please make the following changes and it should work.

    string insertQuery = "INSERT into test (name,surname,email) VALUES( '" +
    name +"','"+ surname + "','" + email + "')";

    Ashish M Bhonkiya
    Ashish M Bhonkiya, Apr 19, 2004
    1. Advertisements

  3. altergothen

    Hans Kesting Guest

    You want "parameters".

    1) use as a query
    string insertQuery = "INSERT into test (name,surname,email)

    2) add parameters with the values
    commandObj.Parameters.Add("@name", name);

    This way you will have no problems with names like "O'Brien" etc.

    Hans Kesting
    Hans Kesting, Apr 19, 2004
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.