Trying to update db - no errors but no update either - c#

I have a problem in trying to update a database using SQL update command and DataGridView.
Int16 ID, An;
// update db using sql command, the code does not update the database
SqlCommand cmd = new SqlCommand("update filme set ID = #ID, Nume = #Nume, Gen = #Gen, Descriere = #Descriere, Actori = #Actori, An = #An, Rating = #Rating, Pret = #Pret where ID = #ID");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#ID", SqlDbType.SmallInt).Value = Int16.TryParse("#ID", out ID);
cmd.Parameters.AddWithValue("#Nume", SqlDbType.NVarChar).Value = "#Nume";
cmd.Parameters.AddWithValue("#Gen",SqlDbType.NVarChar).Value = "#Gen";
cmd.Parameters.AddWithValue("#Descriere", SqlDbType.NVarChar).Value = "#Descriere";
cmd.Parameters.AddWithValue("#Actori", SqlDbType.NVarChar).Value = "#Actori";
cmd.Parameters.AddWithValue("#An", SqlDbType.SmallInt).Value = Int16.TryParse("#An", out An) ;
cmd.Parameters.AddWithValue("#Rating", SqlDbType.NVarChar).Value = "#Rating";
cmd.Parameters.AddWithValue("#Pret",SqlDbType.Money).Value = "#Pret";
connection.Open();
cmd.ExecuteNonQuery();
This code does not produce any errors, but does not update the database. Something is wrong but I don't know what.
I use Visual Studio Community and SQL Server 2012. The information from database are displayed in a DataGridView.
Thank you !

You set the #ID parameter with this line
Int16.TryParse("#ID", out ID);
what do you expect to be the result of converting the string #ID to an integer?
And Int16.TryParse returns a boolean, true if the conversion succeed, false otherwise.
Then you use
cmd.Parameters.AddWithValue("#ID", SqlDbType.SmallInt).Value = .....
The second parameter of AddWithValue is the Value to give to the parameter, not the type.
The remainder follows the same pattern and so this code will never work.
As an example, you should write:
SqlCommand cmd = new SqlCommand(#"update filme set Nume = #Nume, Gen = #Gen,
Descriere = #Descriere, Actori = #Actori,
An = #An, Rating = #Rating, Pret = #Pret
where ID = #ID", connection);
cmd.Parameters.Add(new SqlParameter
{ ParameterName = #Nume,
SqlDbType = SqlDbType.Int,
Value = Convert.ToInt32(someTextBox.Text) // Or some datagridview cell...
};
...and so on for the other parameters...
Notice also that I have removed the part about SET ID = #ID because this makes no sense. If you use the ID field as your search condition then updating it with the value that you are searching for could only lead, in the best situation, at no change for the ID field and in the worst situation to changing a different record from the intended one.

The way you use the .AddWithValue is all wrong .....
You have
cmd.Parameters.AddWithValue("#ID", SqlDbType.SmallInt).Value = Int16.TryParse("#ID", out ID);
but you're really defining the parameter name and datatype (which is a good thing!) and then you use the .Value = ... to handle the value assignment.
These lines of code should really be:
cmd.Parameters.Add("#ID", SqlDbType.SmallInt).Value = Int16.TryParse("#ID", out ID);
I bet using this approach, your code will work just fine.

Related

How to make a parameterized SELECT query in C#?

I'm trying to display data from a table in database using DataGridView and a parameterized query in C# and SQL Server.
So far, I have tried this code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=.\SQLEXPRESS01;Initial Catalog=Vagtplan;Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT Ansatte.ansatID = #ansat, Ansatte.Navn = #navn, Ansatte.Efternavn = #efternavn, Ansatte.Adresse = #adresse, Ansatte.Postnummer = #postnummer, Ansatte.Bynavn = #bynavn, Ansatte.Email = #email, Ansatte.Mobilnr = #mobilnr, Login_data.Brugertype = #brugertype FROM Ansatte INNER JOIN Login_data ON Ansatte.ansatID = Login_data.ansatID", con);
cmd.Parameters.Add("#ansat", SqlDbType.Int);
cmd.Parameters.Add("#navn", SqlDbType.VarChar);
cmd.Parameters.Add("#eftervavn", SqlDbType.VarChar);
cmd.Parameters.Add("#adresse", SqlDbType.VarChar);
cmd.Parameters.Add("#postnummer", SqlDbType.Int);
cmd.Parameters.Add("#bynavn", SqlDbType.VarChar);
cmd.Parameters.Add("#email", SqlDbType.VarChar);
cmd.Parameters.Add("#mobilnr", SqlDbType.Int);
cmd.Parameters.Add("#brugertype", SqlDbType.VarChar);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView2.DataSource = dt;
}
But I get the following error:
Incorrect syntax near '='
How to fix it so I can select data using a parameterized query? Expected result is, that data will be displayed in a DataGridView.
You have a few things going on here, and I'll try to break down for you. Working with a database, you typically do a "select...from..." to get data and "insert into..." to add records to the tables.
Next, your query. A shortened version of yours.. The problem here is you are trying to assign the #ansat PARAMETER value INTO the Ansatte.ansatID field which is incorrect syntax context to begin with, but review on regardless.
SqlCommand cmd = new SqlCommand(
#"SELECT
Ansatte.ansatID = #ansat,
Ansatte.Navn = #navn,
Ansatte.Efternavn = #efternavn,
Ansatte.Adresse = #adresse...
FROM
Ansatte
INNER JOIN Login_data
ON Ansatte.ansatID = Login_data.ansatID", con);
and then adding the parameters...
cmd.Parameters.Add("#ansat", SqlDbType.Int);
cmd.Parameters.Add("#navn", SqlDbType.VarChar);
cmd.Parameters.Add("#eftervavn", SqlDbType.VarChar);
cmd.Parameters.Add("#adresse", SqlDbType.VarChar);
Good you are using parameters, but you just DECLARED the parameters, you never assigned any actual values to them, which in essence is resulting in the following getting passed to the engine
SELECT
Ansatte.ansatID = ,
Ansatte.Navn = ,
Ansatte.Efternavn = ,
Ansatte.Adresse =
FROM
Ansatte
INNER JOIN Login_data
ON Ansatte.ansatID = Login_data.ansatID
Hence probably your error for no value for the = sign. Now, to actually add the "Value" to your parameter... Your declaration appeared ok, just finish it with a value that could be a fixed value, from a window entry, config setting, whatever...
cmd.Parameters.Add("#ansat", SqlDbType.Int).Value = 123;
cmd.Parameters.Add("#navn", SqlDbType.VarChar).Value = "test";
cmd.Parameters.Add("#eftervavn", SqlDbType.VarChar).Value = "more";
cmd.Parameters.Add("#adresse", SqlDbType.VarChar).Value = "done";
which would result in a protected (non-sql-injection)
Now, what you might really be looking for. You have a table in your database that you want to pull information from. In this case, select the columns you WANT, not the values you want to SET. Just query. Ex:
SqlCommand cmd = new SqlCommand(
#"SELECT
Ansatte.ansatID,
Ansatte.Navn,
Ansatte.Efternavn,
Ansatte.Adresse,
Ansatte.Postnummer,
Ansatte.Bynavn,
Ansatte.Email,
Ansatte.Mobilnr,
Login_data.Brugertype
FROM
Ansatte
INNER JOIN Login_data
ON Ansatte.ansatID = Login_data.ansatID", con);
If you run the above query, it will return all records that are in the database that have a matching ID between each respective table.
Now, tack on parameters to a SQL-SELECT query. Say you only wanted all names within a given PostNumber area. Add a WHERE condition for such field and parameterized value such as
FROM
Ansatte
INNER JOIN Login_data
ON Ansatte.ansatID = Login_data.ansatID
where
Ansatte.Postnummer = #MyPostCriteria", con );
cmd.Parameters.Add("MyPostCriteria", SqlDbType.Int).Value = 11223;
Now, if you are trying to ADD a record TO the database, that would be an insert, and you can only do an insert into a single table at a time and might be something like below. You identify the table and columns you want to insert, and then the values in the same sequence as their corresponding sequence as added in parenthesis list at the top.. Then parameterize
SqlCommand cmd = new SqlCommand(
#"INSERT INTO Ansatte
( Navn,
Efternavn,
Adresse
)
values
( #parmForNavn,
#parmForEfternavn,
#parmForAdresse
)", con);
cmd.Parameters.Add("parmForNavn", SqlDbType.VarChar).Value = "test";
cmd.Parameters.Add("parmForEfternavn", SqlDbType.VarChar).Value = "blah";
cmd.Parameters.Add("parmForAdresse", SqlDbType.VarChar).Value = "123 some street";
Hopefully this can jump-start you into what you are trying to accomplish from either pulling data down from a database, or insert into.

retrieve updated parameter value on asp.net with sqlcommand

I'm using a query to update a column value on table and also retrieve the updated value using the following way on the ASP.NET site. Is there any way to use single query instead of double queries as below?
using (SqlConnection connection = new SqlConnection(connStr)){
string updateUserQuery = "Update user_master set login_failed_attempts = login_failed_attempts + 1 where id = #id; Select #login_failed = login_failed_attempts from user_master where id = #id";
SqlCommand cmd = new SqlCommand(updateUserQuery, connection);
cmd.Parameters.Add("#id", SqlDbType.Int).Value = user_id;
SqlParameter outputIdParam = new SqlParameter("#login_failed", SqlDbType.Int)
{
Direction = ParameterDirection.Output
};
cmd.Parameters.Add(outputIdParam);
cmd.ExecuteNonQuery();
int loginFailedAttempts = int.Parse(outputIdParam.Value.ToString());
}
Updated code is given below after Matthew's answer.
string updateUserQuery = "Update user_master set login_failed_attempts = login_failed_attempts + 1 OUTPUT INSERTED.login_failed_attempts where id = #id";
SqlCommand cmd = new SqlCommand(updateUserQuery, connection);
cmd.Parameters.Add("#id", SqlDbType.Int).Value = user_id;
int loginFailedAttempts = (int)cmd.ExecuteScalar();
Use an OUTPUT clause.
UPDATE user_master
SET login_failed_attempts = login_failed_attempts + 1
OUTPUT INSERTED.login_failed_attempts
WHERE id = #id
Then change your ExecuteNonQuery to an ExecuteScalar and use the result from that accordingly.
You could also change it to an ExecuteReader and pull back multiple records, but given your use of #id I'm assuming you don't want that.

MySql Adding value on update

I have this update:
sql = "UPDATE table SET prioridade = #prioridade, situacao = #sit , responsavel = #resp , previsao_termino = #previsao, chamado_designado = #designado WHERE id = #id";
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new MySqlParameter("#prioridade", MySqlDbType.Int32)).Value = ch.Prioridade_ID;
cmd.Parameters.Add(new MySqlParameter("#sit", MySqlDbType.Int32)).Value = ch.Situacao_ID;
cmd.Parameters.Add(new MySqlParameter("#resp", MySqlDbType.Int32)).Value = ch.Responsavel_ID;
cmd.Parameters.Add(new MySqlParameter("#previsao", MySqlDbType.Date)).Value = ch.Previsao_Termino;
cmd.Parameters.Add(new MySqlParameter("#designado", MySqlDbType.Int32)).Value = ch.Chamado_Designado;
cmd.Parameters.Add(new MySqlParameter("#id", MySqlDbType.Int32)).Value = ch.ID;
_dal.Executar(cmd);
the value of ch.Previsao_Termino is equal to 31/05/2013 the field previsao_termino is a date type. When it will make the update it throws me an error saying that:
Wrong Value for the field previsao_termino 0031-05-2013.
Where did that 00 came from ? Maybe the connector ? I updated my connector to a new version, also i updated my VisualStudio 2010 to VisualStudio 2012 and sinced I changed that, i've got a lot of problems u.u.
Answer provided by #EdGibbs
When working with MySqlCommand.Parameters the variable you are passing as its value, MUST be the same type that you set the parameter. e.g
MySqlCommand.Parameter.Add(new MySqlParameter("#ParamName", MySqlDataType.DateTime)).value = dtValue
the varaible dtvalue MUST BE DATETIME TYPE, if like me you are using string, then you should use the following conversion.
DateTime.ParseExact(ch.Previsao_Termino, 'dd/MM/yyyy', null)

C# update a boolean value in an Access database

I have made a program in C# and now I want to update a boolean value in my Access database. This boolean value will always be updated to false. I have absolutely tried everything and there is no change in my value. Please help.
Here is my code :
The [In mail] column is my boolean value. I have tried this query in Access and it works perfectly there.
String query = "UPDATE Ontwikkeldossier SET Ontwikkeldossier.[In mail] = #fals WHERE (((Ontwikkeldossier.[OntwikkeldossierID])=#ontwikkeldossierid));";
using(OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.Add("#fals", OleDbType.Boolean, 1, "[In mail]").Value = false;
cmd.Parameters.Add("#ontwikkeldossierid", OleDbType.Numeric).Value = Convert.ToInt32(newrow.Cells[0].Value.ToString());
cmd.ExecuteNonQuery();
}
Thanks in advance.
updateCmd.Parameters.Add("#3", OleDbType.Boolean).Value = "true";
this worked for me! I have "Yes/No" column in Access. Update command is:
OleDbCommand updateCmd = new OleDbCommand("UPDATE email SET server = #1, port = #2, ssl = #3, utilizator = #4, parola = #5, subiect = #6, email = #7 WHERE ID = #8", connection);
For what it's worth, I just tested the following code and it works for me:
using (var conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\__tmp\testData.accdb;"))
{
conn.Open();
using (var cmd = new OleDbCommand(
"UPDATE Ontwikkeldossier SET [In mail]=? WHERE OntwikkeldossierID=?",
conn))
{
cmd.Parameters.AddWithValue("?", false);
cmd.Parameters.AddWithValue("?", 1);
cmd.ExecuteNonQuery();
}
conn.Close();
}
Should this:
cmd.Parameters.Add("#fals", OleDbType.Boolean, 1, "[In mail]").Value = false;
Instead be:
cmd.Parameters.Add("#fals", OleDbType.Boolean).Value = false; //or zero, since it's an object, the DB might care...
Is the source an issue? If you're supplying the value, why do you want a source for the value?
Of course, since it's always false for you, you could simply change the query and eliminate the parameter altogether:
String query = "UPDATE Ontwikkeldossier SET Ontwikkeldossier.[In mail] = 0 WHERE (((Ontwikkeldossier.[OntwikkeldossierID])=#ontwikkeldossierid));";

Adding more number of parameters to sqlparameter class

I have to call a stored procedure but i am having more number of parameters is there any simple way to do this? or simply adding every parameter to sqlparameter class?? like below
SqlCommand command = new SqlCommand("inserting", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#Firstname", SqlDbType.NVarChar).Value = TextBox1.Text;
Be aware that Paramters.Add has an overload that takes in a string and a DbType, so you don't have to call the Parameter constructor. You could replace the line you are currently using to add a new parameter:
command.Parameters.Add(new SqlParameter("#Firstname", SqlDbType.NVarChar)).Value = TextBox1.Text;
with the following shorter (but functionally equivalent) line:
command.Parameters.Add("#Firstname", SqlDbType.NVarChar).Value = TextBox1.Text;
If you want to add more parameters, you would simply add them to the Parameters property of your command, like so:
SqlCommand command = new SqlCommand("inserting", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Firstname", SqlDbType.NVarChar).Value = TextBox1.Text;
command.Parameters.Add("#Lastname", SqlDbType.NVarChar).Value = TextBox2.Text;
Aside from that, have you tried using Parameters.AddWithValue? You can use this if the data type of your column maps to the type of your value in C#. You can find a mapping of C# to SQL Server data typse here.
You would use it like so:
// Assume your sproc has a parameter named #Age that is a SqlInt32 type
int age = 5;
// Since age is a C# int (Int32), AddWithValue will automatically set
// the DbType of our new paramter to SqlInt32.
command.Parameters.AddWithValue("#Age", 5);
If you need to specify the SqlDbType, AddWithValue returns the parameter you just added, so it's as simple as adding an extra statement to set the DbType property at the end, although at this point, you're better off just using the original .Add function and setting the value.
command.Parameters.AddWithValue("#Firstname", TextBox1.Text).DbType = SqlDbType.NVarChar;
Use Array of type SqlParameter and insert that into SqlCommand
SqlCommand Comm = new SqlCommand("Command text", new SqlConnection("Connection String");
SqlParameter[] param = {new SqlParameter("#Name","Value"),
new SqlParameter("#Name","Value"),
........
};
Comm.Parameters.AddRange(param);
Just call the command.Parameters.Add method multiple times:
SqlCommand command = new SqlCommand("inserting", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#Firstname", SqlDbType.NVarChar, 100).Value = TextBox1.Text;
command.Parameters.Add("#Lastname", SqlDbType.NVarChar, 100).Value = TextBox2.Text;
command.Parameters.Add("#City", SqlDbType.NVarChar, 100).Value = TextBox3.Text;
command.Parameters.Add("#ID", SqlDbType.Int).Value = Convert.ToInt32(TextBox4.Text);
....... and so on .....
You may use like it
return new SqlParameter[]
{
new SqlParameter("#Firstname", SqlDbType.VarChar)
{
Value = Firstname.Text
},
new SqlParameter("#Lastname", SqlDbType.VarChar)
{
Value = Lastname.Text
},
};
You can use dapper-dot-net
sample code:
var dog = connection.Query<Dog>("select Age = #Age, Id = #Id", new { Age = (int?)null, Id = guid });
Insert example:
connection.Execute(#"insert MyTable(colA, colB) values (#a, #b)",
new[] { new { a=1, b=1 }, new { a=2, b=2 }, new { a=3, b=3 } }
).IsEqualTo(3); // 3 rows inserted: "1,1", "2,2" and "3,3"
The command.Parameters.Add is deprecated. Rather use command.Parameters.AddWithValue .
For this, you would call it many times for each parameter.
// Mention size of the nvarchar column , here i give 500 , you can use its length for #Firstname as you mention in database according to your database
SqlCommand command = new SqlCommand("inserting", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#Firstname", SqlDbType.NVarChar,500).Value = TextBox1.Text;

Categories

Resources