Inserting value into database - c#

I wanted to insert values into database but it is not working eventhough my code perfectly working when its used as stored procedure. I am trieng to use button click to store the value. Please tell whats wrong with the code. Its not showing any error or exception but data is not getting updated in the table
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection sqlConnection1 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO sales(acnum, scripname, shares_bought) VALUES ('12', 'abcd', '20')";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}

my columns acnum and shares_bought are "int" and scripname is
"varchar"
Then you will not need single quotes for your integer values. Use it as;
...VALUES (12, 'abcd', 20)"
A few things more;
Use using statement to dispose your connection and command automatically instead of calling Close method manually.
You don't need cmd.CommandType = CommandType.Text line. It is .Text by default.
var conStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
using(var sqlConnection1 = new SqlConnection(conStr))
using(var cmd = sqlConnection1.CreateCommand())
{
cmd.CommandText = "INSERT INTO sales(acnum, scripname, shares_bought) VALUES (12, 'abcd', 20)";
sqlConnection1.Open();
cmd.ExecuteNonQuery();
}

Set breakpoint in code and see if code is executing. In case you don't know how to, see here.
As you are not getting any exception on insert statement and it's not reflecting in database, either you have different connection string or your code is not getting executed.

Related

Data insertion obviously works, but is not showing up on table

I am trying to insert data into my database table using the insert statement as shown below:
private void buttonPurchase_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Purchase?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) {
////store invoice
string connectionString = ConfigurationManager.ConnectionStrings
["CarDBConnectionString"].ConnectionString;
SqlConnection sqlConnection1 = new SqlConnection(connectionString);
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO [dbo].[invoiceTbl] ([invoiceId], [dateAndTime]) VALUES (2, N'2014-06-22 00:00:00')";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
but although no errors were shown, the code works, the data inserted is not showing up in my table data. I tried adding them manually in the table, and copied the sql statement directly into the code shown above, when I add in duplicate data it is detected, but when I add in data again (without duplicating the primary key) the table data shows NULL and NULL respectively. So in short I think my code works, but for some weird reason it just doesn't show up in my schema! Any help is deeply appreciated! :)

Adding to database using Oledb Syntax error in INSERT INTO statement

when i hit the add button to insert a new book, i get an error at cmd.ExecuteNonQuery(); Syntax error in INSERT INTO statement. Am i missing anything?
protected void btnAddBook_Click(object sender, EventArgs e)
{
string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|Bookdb.accdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
OleDbCommand cmd = new OleDbCommand("INSERT INTO Books (Title, Author, Price, Edition) VALUES (#Title, #Author, #Price, #Edition)");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#Title", TextBox1.Text);
cmd.Parameters.AddWithValue("#Author", TextBox2.Text);
cmd.Parameters.AddWithValue("#Price", TextBox3.Text);
cmd.Parameters.AddWithValue("#Edition", TextBox4.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
The only reason that I can find as a possible failure for your code is if the Price field is a numeric field in your database table. You are creating a parameter with AddWithValue and this method creates a parameter whose datatype is derived from the datatype of the value passed. You pass a string (TextBox3.Text) and so AddWithValue creates a string parameter.
You could try to force the AddWithValue to create a numeric parameter with
cmd.Parameters.AddWithValue("#Price", Convert.ToDecimal(TextBox3.Text));
(Of course assuming a decimal Price column)
Right before you call conn.Open(), you need to call cmd.Prepare(), so that all the parameters you set are actually loaded into the SQL statement.

inserted values on updated database are not correct - MVC

im trying to update the values of columns from the same row in my database.
Here is my code:
if (ModelState.IsValid)
{
using (SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand();
cmd = cn.CreateCommand();
cmd.CommandText = #"Update Content Set Des='#Des', Sc='#Sc' Where ID_Img=#Id_Img";
cmd.Parameters.Add("#Des", SqlDbType.VarChar);
cmd.Parameters["#Des"].Value = model.Des;
cmd.Parameters.Add("#Sc", SqlDbType.VarChar);
cmd.Parameters["#Sc"].Value = model.Sc;
cmd.Parameters.Add("#Id_Img", SqlDbType.Int);
cmd.Parameters["#Id_Img"].Value = model.Id_Img;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
}
the code works and i get no error, but when i check in my database the values inserted are #Desc and #Sc and not properly the values which comes from form in my view.
I have set a breakpoint and check which values are in the variables all off them have the correct one..
What im doing wrong?
Someone can give me a hand pls?
Don't wrap your parameters in quotes in the actual query. Try this:
cmd.CommandText = #"Update Content Set Des=#Des, Sc=#Sc Where ID_Img=#Id_Img";
The parameters are smart enough to know if they need to be wrapped in quotes or not based on their data types.

Unable to insert data in MS Access using parameterized query in c#

I have the following code which tries to store e values form 3 textboxes into a MS Access 2007 database.
string ConnString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\dxs.accdb");
string SqlString = "Insert Into tests( [Nam], [add], [phone]) Values (?,?,?)";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue(#"Nam", textBox1.Text);
cmd.Parameters.AddWithValue(#"add", textBox2.Text);
cmd.Parameters.AddWithValue(#"phone",textBox3.Text);
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("entered");
}
}
But even though the code is correct after entering values nothing is being stored in table.
Shouldn't
cmd.Parameters.AddWithValue(#"Nam", textBox1.Text);
Be:
cmd.Parameters.AddWithValue("#Nam", textBox1.Text);
And so on for the other parameters?
When i had the similar problems, solution was:
If database is part of application it can be copied in a bin folder - and then application work with it. That is why you can`t find your changes in datatables with MS Access client.
Make sure your database exists in output(bin) folder where exists your exe file of project. If not then copy it there. After your have your database file at right place, You will be to see the changes.
Additionally, you also need few changes in your code, you have problem with your parameter.
Change Values (?,?,?) to Values (#Nam,#add,#phone)"; and #"Nam" to "#Nam". See the comments Correction1 and Correction2.
Also no need to use double slash \\ when you are using # at beginning of string
string ConnString=#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\dxs.accdb");
string sql="Insert Into tests([Nam],[add],[phone]) Values (#Nam,#add,#phone)";
// Correction 1: Above line is changed ?,?,? to parameter names (names used by your command)
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Nam", textBox1.Text);
cmd.Parameters.AddWithValue("#add", textBox2.Text);
cmd.Parameters.AddWithValue("#phone",textBox3.Text);
// Correction 2: your parameter names are changed #"xyz" to "#xyz"
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("entered");
}
}
your insert statement should be like dis
string SqlString = "Insert Into tests( [Nam], [add], [phone]) Values (#Nam, #add, #phone)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Nam", textBox1.Text);
cmd.Parameters.AddWithValue("#add", textBox2.Text);
cmd.Parameters.AddWithValue("#phone",textBox3.Text);
try this

issues using parameter queries

I'm trying to switch come of my SQL queries to parameter queries but i keep getting some errors shown after the code below:
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//Define data objects
SqlConnection conn;
//SqlCommand comm;
//Read the connection string from web config
string connectionString = ConfigurationManager.ConnectionStrings["clientsConnectionString"].ConnectionString;
//Initialize the connection
conn = new SqlConnection(connectionString);
//Create Command
// comm = new SqlCommand();
const string SQL = "insert into request (Surname,[Other Names], mobileno, date, email, faculty, dept, [Registration Number], session, thesis, yearGrad, tellerno, amount, address, question ) values (#Surname,[#Other Names],#mobileno,#date, #email, #faculty, #dept, [#Registration Number], #session,#thesis, #yearGrad, #tellerno, #amount, #address,#question)";
SqlCommand cmd = new SqlCommand(SQL, conn);
cmd.Parameters.AddWithValue("#Surname", lblSurname.Text);
cmd.Parameters.AddWithValue("#[Other Names]", lblOtherNames.Text);
cmd.Parameters.AddWithValue("#mobileno", lblPhone.Text);
cmd.Parameters.AddWithValue("#date", lblDate.Text);
cmd.Parameters.AddWithValue("#email", lblEmail.Text);
cmd.Parameters.AddWithValue("#faculty", lblFaculty.Text);
cmd.Parameters.AddWithValue("#dept", lblDept.Text);
cmd.Parameters.AddWithValue("#[Registration Number]", lblRegNo.Text);
cmd.Parameters.AddWithValue("#session", lblSession.Text);
cmd.Parameters.AddWithValue("#thesis", lblThesis.Text);
cmd.Parameters.AddWithValue("#yearGrad", lblGradYr.Text);
cmd.Parameters.AddWithValue("#tellerno", lblTeller.Text);
cmd.Parameters.AddWithValue("#amount", lblAmount.Text);
cmd.Parameters.AddWithValue("#address", lblAdd.Text);
cmd.Parameters.AddWithValue("#question", lblQue.Text);
conn.Open();
// verify if the ID entered by the visitor is numeric
cmd.ExecuteNonQuery();
conn.Close();
//reload page if query executed succesfully
Response.Redirect("thanks.aspx");
}
}
Error message is:
Server Error in '/TranscriptReloaded' Application.
Incorrect syntax near 'nvarchar'.
Must declare the scalar variable "#date".
"date" is a SQL reserved word, so the translation to SQL may be having a problem with it. Generally speaking you should avoid using the word date on its own as column names or as parameters.
Personally I would start by losing the #[two word] variable names (which you also use as [#two word] elsewhere). I don't know if this is the cause, but I have never seen this usage personally, and I'm dubious. Fine for column names (and table names), but variables? Not so sure. Changing the variable names is local to this code, so shouldn't cause any side-effects.

Categories