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)
Related
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.
I'm trying to insert date time picker value into a DATETIME column in my database.
Here's my code..
myconstr = "Data Source=wind;Initial Catalog=TestDB;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False";
myquery = "INSERT INTO DateTimeTB(MyDate) VALUES (#mydate)";
using (SqlConnection connection = new SqlConnection(myconstr))
{
SqlCommand cmd = new SqlCommand(myquery);
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.Add(new SqlParameter("#mydate", SqlDbType.DateTime).Value = MyDTP01.Value);
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
It gives me the following error..
The SQL parameter collection only accepts non-null SqlParameter type objects, not date time objects.
How can I fix this..?
Your code is equivalent to:
var parameter = new SqlParameter("#mydate", SqlDbType.DateTime);
var value = MyDTP01.Value;
parameter.Value = value;
cmd.Parameters.Add(value);
You want to add the parameter, not the value. So:
cmd.Parameters.Add(new SqlParameter("#mydate", SqlDbType.DateTime)).Value = MyDTP01.Value;
Note the location of the brackets.
This can be simplified, however - you don't need to call the SqlParameter constructor yourself - you can just pass the name and the type to Add:
cmd.Parameters.Add("#mydate", SqlDbType.DateTime).Value = MyDTP01.Value;
Using Enterprise Library, This is how I do it
var db = EnterpriseLibraryContainer.Current.GetInstance<Database>();
using( DbCommand command = db.GetStoredProcCommand("Your Stored proc name"))
{
db.AddInParameter(command, "#mydate", DbType.DateTime, DateTime.Now.Date); // Replace with MyDTP01.Value
db.ExecuteNonQuery(command);
}
I'm having an issue with an update query in C#. It's odd to me that I'm having an issue with update, but select, delete, and insert work.
public void updateTeacherInfo(string SSN, string Classroom, string salary, string tenured, string phone)
{
OracleConnection conn = new OracleConnection("myconnectionstring;");
conn.Open();
OracleCommand cmd = new OracleCommand("Update Teachers Set classroom_number = :TRM, Salary = :TSALARY, Tenured = :TTENURE, Phone_numer = :TPHONE Where SSN = :TSSN", conn);
OracleCommand commit = new OracleCommand("COMMIT", conn);
cmd.Parameters.Add(new OracleParameter(":TSSN", SSN));
cmd.Parameters.Add(new OracleParameter(":TRM", Classroom));
cmd.Parameters.Add(new OracleParameter(":TSALARY", salary));
cmd.Parameters.Add(new OracleParameter(":TTENURE", tenured));
cmd.Parameters.Add(new OracleParameter(":TPHONE", phone));
int i = cmd.ExecuteNonQuery();
int k = commit.ExecuteNonQuery();
MessageBox.Show(i + " rows affected");
MessageBox.Show(k + " rows affected");
conn.Close();
}
Edit* the rest of the method to clear things up, and also, it is not throwing any errors, but does not update the database.
Put the Parameters.Add in proper sequence. In your update query
"Update Teachers Set classroom_number = :TRM, Salary = :TSALARY, Tenured = :TTENURE, Phone_numer = :TPHONE Where SSN = :TSSN"
:TRM is occuring first and likewise. So keep the Parameters.Add also in same sequence. It will work. The sequence will be:
cmd.Parameters.Add(new OracleParameter(":TRM", Classroom));
cmd.Parameters.Add(new OracleParameter(":TSALARY", salary));
cmd.Parameters.Add(new OracleParameter(":TTENURE", tenured));
cmd.Parameters.Add(new OracleParameter(":TPHONE", phone));
cmd.Parameters.Add(new OracleParameter(":TSSN", SSN));
string con = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
SqlConnection cn = new SqlConnection(con);
string insert_jobseeker = "INSERT INTO JobSeeker_Registration(Password,HintQuestion,Answer,Date)"
+ " values (#Password,#HintQuestion,#Answer,#Date)";
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = insert_jobseeker;
cmd.Parameters.Add(new SqlParameter("#Password", SqlDbType.VarChar, 50));
cmd.Parameters["#Password"].Value = txtPassword.Text;
cmd.Parameters.Add(new SqlParameter("#HintQuestion", SqlDbType.VarChar, 50));
cmd.Parameters["#HintQuestion"].Value = ddlQuestion.Text;
cmd.Parameters.Add(new SqlParameter("#Answer", SqlDbType.VarChar, 50));
cmd.Parameters["#Answer"].Value = txtAnswer.Text;
**cmd.Parameters.Add(new SqlParameter("#Date", SqlDbType.DateTime));
cmd.Parameters["#Date"].Value = System.DateTime.Now**
I got error that
"SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and
12/31/9999 11:59:59 PM."
What's the solution for this ?
Try changing the Type of #Date on the SQL Server side to DATETIME2(7)
Then in your code use this line instead:
cmd.Parameters.Add(new SqlParameter("#Date", SqlDbType.DateTime2));
Your code looks okay as shown but possibly something is going on with the conversion due to a localization issue or something wrong with your Region/Time settings so see if this works.
If you are working with SQL Server 2008 and above, you can do this:
Step 1: Change your #Date datatype from DATETIME to DATETIME2(7)
Step 2: In your codebehind, use this:
SqlDbType.DateTime2
"Date" is a keyword, do not use it as a column name.
If you have to, enclose it in [] in your insert statement: [Date]
But it would be better to change it to something else, for example "RegistrationDate".
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;