Javacadabra
Javacadabra

Reputation: 5758

Executing an INSERT command using ASP.net

I am using Visual Studio 2010 to create a simple Website for a college assignment. I am trying to create a contact form that submits the users name, email and message to my database table Messages.

I have created the relevant web service and I know that it is working when I try to GET data from the Table. I am just a little confused as to how I can INSERT data into the table.

Below is the code to my web service. The method I am concerned with is addMessage() I call the method when a button is clicked that is located on the contact.aspx page.

    public class Customers : System.Web.Services.WebService {

    [WebMethod]
    public DataSet getCustomers() {
        SqlConnection conn;
        SqlDataAdapter myDataAdapter;
        DataSet myDataSet;
        string cmdString = "Select * From Customers";
        conn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;AttachDbFilename=C:\\Users\\n00093500\\Desktop\\MMCA2\\APP_DATA\\NORTHWIND.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
        myDataAdapter = new SqlDataAdapter(cmdString, conn);
        myDataSet = new DataSet();
        myDataAdapter.Fill(myDataSet, "Customers");
        return myDataSet;
    }

    [WebMethod]
    public void addMessage(String n, String e, String m)
    {
        SqlConnection conn;
        SqlDataAdapter myDataAdapter;
        SqlCommand myCommand = new SqlCommand("INSERT INTO Messages VALUES("+n+","+e+","+m+")");
        conn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;AttachDbFilename=C:\\Users\\n00093500\\Desktop\\MMCA2\\APP_DATA\\NORTHWIND.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
        //UNSURE WHAT TO DO FROM THIS POINT... CAN I USE myDataAdapter to execute a query?
    }

}

Appreciate any help you guys might have! Thanks

Upvotes: 1

Views: 3138

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415600

[WebMethod]
public void addMessage(String n, String e, String m)
{
    string sql = "INSERT INTO Messages VALUES(@n, @e, @m)";
    using (var conn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;AttachDbFilename=C:\\Users\\n00093500\\Desktop\\MMCA2\\APP_DATA\\NORTHWIND.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"))
    using (var cmd = new SqlCommand(sql, conn))
    {
       //change these three lines to use actual database column types, lengths
       //I'll pretend "e" is a date column just to show an example of how that might look
       cmd.Parameters.Add("@n", SqlDbType.NVarChar, 50).Value = n;
       cmd.Parameters.Add("@e", SqlDbType.DateTime).Value = DateTime.Parse(e);
       cmd.Parameters.Add("@m", SqlDbType.NVarChar, 50).Value = m;

       conn.Open();
       cmd.ExecuteNonQuery();
    }
}

Upvotes: 5

Related Questions