inserted values on updated database are not correct - MVC - c#

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.

Related

insert value from TextBox into sql

I'm getting this error message: Cannot insert the value NULL into column 'id', table ''; column does not allow nulls. INSERT fails. thanks in advance
protected void AddItem(object sender, EventArgs e)
{
string insertCmd = "INSERT INTO Picture (Album, id) VALUES (#Album, #id)";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
// Create parameters for the SqlCommand object
// initialize with input-form field values
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
myCommand.Parameters.Add("#id", SqlDbType.Int).Direction = ParameterDirection.Output;
myCommand.ExecuteNonQuery();
int id = (int)myCommand.Parameters["#id"].Value;
}
}
I suppose that ID is an IDENTITY column. Its value is generated automatically by the database engine and you want to know what value has been assigned to your record.
Then you should change your query to
string insertCmd = #"INSERT INTO Picture (Album) VALUES (#Album);
SELECT SCOPE_IDENTITY()";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
int newID = Convert.ToInt32(myCommand.ExecuteScalar());
}
The query text now contains a second instruction SELECT SCOPE_IDENTITY() separated from the first command by a semicolon. SCOPE_IDENTITY returns the last IDENTITY value generated for you by the database engine in the current scope.
Now the command is run using the ExecuteScalar to get back the single value returned by the last statement present in the query text without using any output parameter
I would think that ID is identity. You don't have to add this value. I would try the following code and check the database if you get automatically an ID.
string insertCmd = "INSERT INTO Picture (Album) VALUES (#Album)";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
// Create parameters for the SqlCommand object
// initialize with input-form field values
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
myCommand.ExecuteNonQuery();
}
I case you want to set the id yourself(withoud automatic increment from the db), you should change the schema of the database removing identity from ID as shown below:
I hope this helps
If you need to stay this column empty you can try to replace to ' '(blank). This will work if you column is not "Key"
Or try to use:
substitute a value when a null value is encountered
NVL( string1, replace_with )
You can do this using stored procedure. Below is the script for Create stored procedure.
CREATE PROCEDURE [dbo].[InsertIntoPicture]
#Album varchar(500)=null,
#id int=0 output
AS
BEGIN
insert INTO Picture(Album)VALUES(#Album)
SET #id=##IDENTITY
END
Below is the code for call stored procedure with C# .
string insertCmd = "InsertIntoPicture";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
myCommand.Parameters.Add("#id", SqlDbType.Int).Direction = ParameterDirection.Output;
myCommand.ExecuteNonQuery();
int id = (int)myCommand.Parameters["#id"].Value;
}
Using above code you can insert a date from TextBox and also get last inserted record ID as an output variable as per your requirement.
Thanks .

Inserting value into database

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.

hebrew from the Connection

I am trying with oracle database to Insert and select Hebrew letters
and it not working well.
I tried
Insert into mytable values ('היי');
and the result is ??? and not היי
can someone help me with that
Edit:
Now after i ask from DBA for hebrew option i can write in Hebrew from the sqlplus
but now from my project it still write ???
my code is
OleDbConnection conn = Connect();
conn.Open();
OleDbCommand com = new OleDbCommand("Insert into mytable values ('היי')", conn);
com.ExecuteNonQuery();
and still the result is ???
I can't really test this because I don't know anything about your database (not even your column names), but you should do that command with parameters:
var testString = "היי"; // Do be aware that Visual Studio displays Hebrew text right-to-left, so the actual string is reversed from what you see.
using (OleDbConnection conn = Connect())
{
conn.Open();
using (OleDbCommand com = conn.CreateCommand())
{
// OleDbCommand com = new OleDbCommand("Insert into mytable values ('היי')", conn);
com.CommandText = "Insert into mytable values (?)";
com.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.VarWChar }).Value = testString;
com.ExecuteNonQuery();
}
}
Also, don't forget to dispose your disposables via a using statement.
Relatedly, here is a report that using a parameterized query fixed a similar problem with OracleCommand.

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

OleDbDataAdapter Update To dbf [Free Table] -Syntax Error()

When I insert through the OleDbCommand with direct values no problem, it's working fine
OleDbCommand OleCmd1 = new OleDbCommand("Insert into My_Diary (sl_no,reminder) values("+a1+",'CHECK VALUE')", OleCon1);
OleCmd1->ExecuteNonQuery();
But when I like to update through parameter its showing "Syntax Error"....I can't identify my mistake...
string MyConStr = "Provider=VFPOLEDB.1; Data Source='C:\\For_Dbf'; Persist Security Info=False";
InsSavDiaryCmd = "Insert into My_Table1 (sl_no,reminder) values (#sl_no,#reminder) ";
VFPDAp=gcnew OleDbDataAdapter();
VFPDApMy_Table1InsertCommand = gcnew OleDbCommand(InsSavDiaryCmd, OleCon1);
WithInsVar = VFPDAp.InsertCommand.Parameters;
WithInsVar.Add("#sl_no", OleDbType.Integer, 10, "sl_no");
WithInsVar.Add("#reminder", OleDbType.Char, 250, "reminder");
OleCon1.ConnectionString = MyConStr;
OleCon1.Open();
OleDbTransaction Trans=OleCon1.BeginTransaction();
//VFPDAp.DeleteCommand.Transaction = Trans;
//VFPDAp.UpdateCommand.Transaction = Trans;
VFPDAp.InsertCommand.Transaction = Trans;
VFPDAp.Update(MyDataTbl);
Trans.Commit();
OleCon1.Close();
The OleDbCommand doesn't use named parameters. You need to change the insert statement so that it uses questions.
InsSavDiaryCmd = "Insert into My_Table1 (sl_no,reminder) values (?, ?) ";
You need to make sure that you have a parameter for each question mark and make sure that the parameters are inserted in order of their use in the insert statement.
** If you'd like to use name parameters... you can try using VfpClient which is a project that I'm working on to make data access a little nicer from .Net.

Categories