Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello, i'm having a little problem inserting data from my application into my database. I do not get any errors while connecting or trying to insert into the database but data just doesn't get inserted. I use Visual Studio 2010 with C# And SQL SERVER Management Studio 2012. Here is my code:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;

 <summary>
 Summary description for Sources
 </summary>
public class Sources
{
	private string conString;
	public int mSourceID;
	public string mSourceName;
	public int mActive;

	public Sources()
	{	
		conString = WebConfigurationManager.ConnectionStrings["dbconstring"].ConnectionString;
		mSourceID = 0;
		mSourceName = "";
		mActive = 0;
	}

	public void insertData()
	{
        using (SqlConnection con = new SqlConnection(conString))
        {
            con.Open();
            try
            {
                using (SqlCommand cmd = new SqlCommand("INSERT INTO dbo.Sources(SourceID, SourceName, Active) VALUES(@SourceID, @SourceName, @Active)", con))
                {
                    cmd.Parameters.Add(new SqlParameter("SourceID", mSourceID));
                    cmd.Parameters.Add(new SqlParameter("SourceName", mSourceName));
                    cmd.Parameters.Add(new SqlParameter("Active", mActive));
                }
            }
            catch (Exception Ex)
            {
                Console.WriteLine("Unable To Save Data. Error - " + Ex.Message);
            }
        }
	}
}


C#
protected void btnOk_Click(object sender, ImageClickEventArgs e)
{
    Sources src = new Sources();
    src.mSourceID = 1;
    src.mSourceName = "aboa";
    src.mActive = 0;
    src.insertData();
}
Posted
Comments
[no name] 16-Jun-13 9:45am    
Try "cmd.Parameters.Add(new SqlParameter("@SourceID", mSourceID)); cmd.Parameters.Add(new SqlParameter("@SourceName", mSourceName)); cmd.Parameters.Add(new SqlParameter("@Active", mActive));"

1 solution

You forgot to execute the query:
C#
using (SqlCommand cmd = new SqlCommand("INSERT INTO dbo.Sources(SourceID, SourceName, Active) VALUES(@SourceID, @SourceName, @Active)", con))
{
    cmd.Parameters.Add(new SqlParameter("SourceID", mSourceID));
    cmd.Parameters.Add(new SqlParameter("SourceName", mSourceName));
    cmd.Parameters.Add(new SqlParameter("Active", mActive));
    cmd.ExecuteNonQuery();  // <---- ADD THIS LINE
}
 
Share this answer
 
Comments
Member 9465564 17-Jun-13 13:45pm    
Thank you.
OriginalGriff 17-Jun-13 13:50pm    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900