sqldatetime overflow exception c#.NET - c#

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".

Related

How to fix "System.Data.SqlClient.SqlException: 'Column name or number of supplied values does not match table definition.'" in asp.net

I'm trying to connect my SQL Server with ASP.NET, and when I run my insert function, it displays an error.
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Insert into Table1 values('"+firstname.Text+"','"+lastname.Text+"','"+city.Text+"')";
cmd.ExecuteNonQuery();
firstname.Text = "";
lastname.Text = "";
city.Text = "";
I expect to show the inserted values but it displays this error:
System.Data.SqlClient.SqlException: 'Column name or number of supplied values does not match table definition.'
Where Id is auto incremented.
You need urgently research about SQL injection, and STOP USING string concatenation for building your SQL insert statement RIGHT NOW.
You need to use the proper technique - parametrized queries -- always - NO exceptions!
And also, it's a commonly accepted Best Practice to list the columns in your INSERT statement, to avoid trouble when tables change their columns (read more about this here: Bad habits to kick: using SELECT * / omit the column list ).
Use this code as a sample/template:
string insertQuery = #"INSERT INTO dbo.Table1 (FirstName, LastName, City)
VALUES (#FirstName, #LastName, #City);";
using (SqlCommand cmd = new SqlCommmand(insertQuery, con))
{
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar, 50).Value = firstname.Text;
cmd.Parameters.Add("#LastName", SqlDbType.VarChar, 50).Value = lastname.Text;
cmd.Parameters.Add("#City", SqlDbType.VarChar, 50).Value = city.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close()
}
You should specify the columns names. For example:
cmd.CommandText = $"Insert into Table1 ({ColumnName of firstname}, { ColumnName of lastname}, { ColumnName of city})
values({firstname.Text}, {lastname.Text}, {city.Text})";
You can better use a stored procedure - something like that:
cmd.CommandText = "your SP name";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = firstName.Text;
cmd.Parameters.Add("#LastName", SqlDbType.VarChar).Value = lastName.Text;
etc...

Incorrect syntax near keyword 'desc'

help me please. I don't know what went wrong. It's saying that I have an incorrect syntax near the keyword 'desc' but I don't see anything wrong with this one.
Dim ms As New MemoryStream
pbMainImage.Image.Save(ms, pbMainImage.Image.RawFormat)
Dim sql As String = "insert into contestants(lName,fName,mName,age,gender,address,college,desc,const_num,image_main) values(#lname,#fname,#mname,#age,#gender,#address,#college,#descr,#num,#image)"
Dim cmd As New SqlCommand(sql, constring)
cmd.Parameters.Add("#lname", SqlDbType.VarChar).Value = tbLName.Text
cmd.Parameters.Add("#fname", SqlDbType.VarChar).Value = tbFName.Text
cmd.Parameters.Add("#mname", SqlDbType.VarChar).Value = tbMName.Text
cmd.Parameters.Add("#age", SqlDbType.TinyInt).Value = Convert.ToInt32(tbAge.Text)
cmd.Parameters.Add("#gender", SqlDbType.VarChar).Value = cmbGender.SelectedItem
cmd.Parameters.Add("#address", SqlDbType.VarChar).Value = tbAddr.Text
cmd.Parameters.Add("#college", SqlDbType.VarChar).Value = cmbDept.SelectedItem
cmd.Parameters.Add("#descr", SqlDbType.VarChar).Value = tbDesc.Text.Trim()
cmd.Parameters.Add("#num", SqlDbType.TinyInt).Value = Convert.ToInt32(tbNumber.Text)
cmd.Parameters.Add("#image", SqlDbType.Image).Value = ms.ToArray()
OpenConnection()
Try
cmd.Connection = constring
cmd.ExecuteNonQuery()
cmd.Dispose()
constring.Close()
MsgBox("Added New Contestant.")
Catch ex As Exception
MsgBox("Error at " & ex.ToString)
End Try
desc is a reserved keyword - it means "descending" in order by clauses. So: you need to escape that column to [desc] or "desc" (depending on the database) to tell it you mean the column name.
You are using a keyword for a column name so it must be quoted. But, based on your parameter name, you probably meant descr instead of desc, anyway.

Is it possible to see "text" version of NpgSqlCommand before execution?

I want to see a text version of the command I am about to execute that was created using parameters.add - is there a way to do this? (See commented out line below.)
NpgsqlConnection conn = new NpgsqlConnection(connstring);
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("insert into \"Min_Bar_Price_Data\" values(:SEC_ID, :PX_OPEN, :PX_HIGH, :PX_LOW, :PX_LAST, :PX_VOLUME, :Date)", conn);
cmd.Parameters.Add(new NpgsqlParameter("SEC_ID", DbType.Int32));
cmd.Parameters.Add(new NpgsqlParameter("PX_OPEN", DbType.Double));
cmd.Parameters.Add(new NpgsqlParameter("PX_HIGH", DbType.Double));
cmd.Parameters.Add(new NpgsqlParameter("PX_LOW", DbType.Double));
cmd.Parameters.Add(new NpgsqlParameter("PX_LAST", DbType.Double));
cmd.Parameters.Add(new NpgsqlParameter("PX_VOLUME", DbType.Double));
cmd.Parameters.Add(new NpgsqlParameter("Date", DbType.DateTime));
cmd.Parameters["SEC_ID"].Value = sec_ID;
cmd.Parameters["PX_OPEN"].Value = 0.0;
cmd.Parameters["PX_HIGH"].Value = 0.0;
cmd.Parameters["PX_LOW"].Value = 0.0;
cmd.Parameters["PX_LAST"].Value = d.Close;
cmd.Parameters["PX_VOLUME"].Value = 1.0;
cmd.Parameters["Date"].Value = d.DT;
//Console.WriteLine("Created command: " + cmd.????);
cmd.ExecuteNonQuery();
The entire idea of prepared statements is that parameters are transmitted out-of-band, as opposed to being "substituted" into the SQL statement. This is done to prevent SQL injection attacks and for optimization purposes.
If only for debugging purposes, you can replace parameter names with appropriate values manually, with a simple regex.

Insert date time value into SQL Server database

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);
}

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)

Categories

Resources