how to insert the current time using ado.net sql command. getting error saying The "conversion of a varchar data type to a datetime data type resulted in an out-of-range value."
code
DateTime NowTime = DateTime.Now;
string usecase = "manhole";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
con.Open();
SqlCommand cmdInsert = new SqlCommand("insert into sms values('" + usecase + "','" + smsbody + "','" + NowTime + "')", con);
try
{
cmdInsert.ExecuteNonQuery();
}
columns
updtd_date is datetime
query
INSERT INTO sms (usecase, sms, updtd_date)
VALUES ('manhole','level is low at : 22/01/2018 15:56:20','22/01/2018 16:18:28');
You should use a parametized query instead of concatenating strings, what you are doing is asking for an SQL Injection. Also, you should dispose commands and connections after use them in order to release memory.
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString))
{
using (var command = new SqlCommand("insert into sms (col1) values(#col1"))
{
command.Parameters.AddWithValue("#col1", DateTime.Now);
con.Open();
command.ExecuteNonQuery();
}
}
Use The Function GETDATE() To Get the System Date and Time.
Change NowTime
"insert into sms values('" + usecase + "','" + smsbody + "','" + NowTime + "')"
To This
"insert into sms values('" + usecase + "','" + smsbody + "',GETDATE())"
Executing the SQL Statements Like this Can Cause SQL Injection, So I Recommend using Parameter may Be Something Like this
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("insert into sms values(#usecase,#smsbody,GETDATE())", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#usecase", SqlDbType.VarChar).Value = usecase;
cmd.Parameters.Add("#smsbody", SqlDbType.VarChar).Value = smsbody;
con.Open();
cmd.ExecuteNonQuery();
}
}
I think you need to be specific with the date format in SQL if you inserting a date if you not using paramater:
string nowDate = DateTime.Now.ToString("dd MMM yyy HH:mm:ss");
string sql = "insert into #dateT values('"+nowDate+"')";
This results to this in my pc
insert into #dateT values('22 Jan 2018 13:27:04');
Related
When I Using this command to insert data, it's totally working..
using (con = new OleDbConnection(#"PROVIDER=Microsoft.Jet.OLEDB.4.0;" + #"DATA SOURCE=C:\Users\ABDUL MALEK\Documents\Visual Studio 2010\WebSites\WebSite1\App_Data\Database.mdb"))
{
cmd = new OleDbCommand();
cmd.CommandText = "insert into Customer(Customer_Phone,Customer_Name) VALUES('"+tb_CustNum.Text+"','"+tb_CustName.Text+"')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Visible= true;
}
But, after I add or replace this command, "Syntax error in FROM clause" shows up..
cmd.CommandText = "insert into Transaction(Product_Code,Date,Quantity,Total,Customer_Phone) values('" + ddl_PizzaCode.SelectedItem + "','" + DateTime.Now.ToString("dddd, dd MMMM yyyy") + "','" + tb_Quan.Text + "','" + Lb_Price.Text + "','" + tb_CustNum.Text + "')";
This is full code-behind:
public partial class _Default : System.Web.UI.Page
{
OleDbConnection con;
OleDbCommand cmd;
int Quan;
double TotalPrice;
//int i = 0;
string Date = DateTime.Now.ToString("dddd, dd MMMM yyyy");
protected void Page_Load(object sender, EventArgs e)
{
Lb_Date.Text = Date;
}
protected void bt_Calc_Click(object sender, EventArgs e)
{
Quan = Convert.ToInt32(tb_Quan.Text);
TotalPrice = Convert.ToDouble(Lb_Price.Text) * Quan;
Lb_TotalPrice.Text = TotalPrice.ToString();
}
protected void ddl_PizzaCode_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dt = new DataTable();
string strquery = "SELECT * FROM Product WHERE ID = " + ddl_PizzaCode.SelectedValue;
using (con = new OleDbConnection(#"PROVIDER= Microsoft.Jet.OLEDB.4.0;" + #"DATA SOURCE =C:\Users\ABDUL MALEK\Documents\Visual Studio 2010\WebSites\WebSite1\App_Data\Database.mdb"))
{
using (cmd = new OleDbCommand(strquery, con))
{
OleDbDataAdapter Da = new OleDbDataAdapter(cmd);
Da.Fill(dt);
}
Lb_PizzaName.Text = dt.Rows[0]["Product_Name"].ToString();
Lb_Price.Text = dt.Rows[0]["Price_per_Unit"].ToString();
}
}
protected void btn_Save_Click(object sender, EventArgs e)
{
using (con = new OleDbConnection(#"PROVIDER=Microsoft.Jet.OLEDB.4.0;" + #"DATA SOURCE=C:\Users\ABDUL MALEK\Documents\Visual Studio 2010\WebSites\WebSite1\App_Data\Database.mdb"))
{
cmd = new OleDbCommand();
cmd.CommandText = "insert into Transaction(Product_Code,Date,Quantity,Total,Customer_Phone) values('" + ddl_PizzaCode.SelectedItem + "','" + DateTime.Now.ToString("dddd, dd MMMM yyyy") + "','" + tb_Quan.Text + "','" + Lb_Price.Text + "','" + tb_CustNum.Text + "')";
cmd.CommandText = "insert into Customer(Customer_Phone,Customer_Name) VALUES('"+tb_CustNum.Text+"','"+tb_CustName.Text+"')";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Label1.Visible= true;
}
BindUserDetails();
}
protected void BindUserDetails()
{
DataSet ds = new DataSet();
DataSet ds2 = new DataSet();
string strquery = "SELECT * FROM Customer";
string strquery2 = "SELECT * FROM Transaction";
using (con = new OleDbConnection(#"PROVIDER=Microsoft.Jet.OLEDB.4.0;" + #"DATA SOURCE=C:\Users\ABDUL MALEK\Documents\Visual Studio 2010\WebSites\WebSite1\App_Data\Database.mdb"))
{
using (cmd = new OleDbCommand(strquery, con))
{
OleDbDataAdapter Da = new OleDbDataAdapter(cmd);
Da.Fill(ds);
}
using (cmd = new OleDbCommand(strquery2, con))
{
OleDbDataAdapter Da = new OleDbDataAdapter(cmd);
Da.Fill(ds2);
}
}
}
}
The word DATE is a keyword in SQL Server, and thus needs to be in square brackets when you are using it as a field name in C#. This line should work:
cmd.CommandText = "insert into Transaction(Product_Code, [Date], Quantity, Total, Customer_Phone) values('" + ddl_PizzaCode.SelectedItem + "','" + DateTime.Now.ToString("dddd, dd MMMM yyyy") + "','" + tb_Quan.Text + "','" + Lb_Price.Text + "','" + tb_CustNum.Text + "')";
have you ever heard of SQL-Injection.... you are WIDE OPEN to exposure.
ALL your queries should have data cleaned and parameterized. Never concatenate what you can't control from the web.
Using parameters in your commands basically means using the proper character identifier indicating a parameter. In SQL and Access, you should be good with the "#" sign. Other databases use different parameters. VFP uses "?" as a place-holder, SAP Advantage Database uses ":".
Change your commands (all of them select, insert, update, delete) to something like..
cmd.CommandText =
#"insert into Customer
( Customer_Phone, Customer_Name )
VALUES
( #parmCustomerPhone, #parmCustomerName)";
cmd.Parameters.AddWithValue( "#parmCustomerPhone", tb_CustNum.Text );
cmd.Parameters.AddWithValue( "#parmCustomerName", tb_CustName.Text );
Then you should be good. Concatenation can fail if someone puts in a quote ' as part of a name, such as "O'Mally". The quote would mis-balance your quotes and cause failure.
If your columns are of numeric or date data types, make sure the parameter you are sending is of that type via the AddWithValue() call.
Additionally, for clarification, I am explicitly calling the values in the insert statement as "#parmSomething" so you know it is the parameter value, not the actual column name and avoiding confusion... especially as a beginner for web and querying.
Finally as noted by other. Be careful about reserved words such as date, time, and other sql clauses. These should be qualified or wrapped in brackets such as [Date] or Date
As for your multiple insert statements, SQL typically uses a semi-colon to identify the end of one statement and allow there to be multiple in a single call such as
cmd.CommandText =
#"insert into Transaction
( Product_Code,
[Date],
Quantity,
Total,
Customer_Phone )
values
( #parmPizza,
#parmNow,
#parmQty,
#parmPrice,
#parmPhone );
insert into Customer
( Customer_Phone,
Customer_Name )
VALUES
( #parmCustPhone,
#parmCustName ) ";
// NOW, add all the parameters...
cmd.Parameters.AddWithValue( "#eachParmAbove", respectiveTextDateNumericValue );
...
...
...
THEN execute it. Hopefully the readability of these samples helps you too.
Not able to insert date into datetime column in sql server.
While debugging after the first executeNonQuery() statement debugger jumps to catch block
and it's displaying the following message in sqlError parameter in catch block:
'Incorrect Syntax near 12'
public ActionResult AddStudentData(StudentDetails sd)
{
SqlConnection db = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\StudentDB.mdf;Integrated Security=True;User Instance=True");
SqlTransaction transaction;
db.Open();
transaction = db.BeginTransaction();
SqlCommand cmd = db.CreateCommand();
try
{
**cmd.CommandText = "insert into StudentDetails(StudentName, DOB, Description, Gender) values ('" + sd.StudentName + "'," +sd.DOB + ",'" + sd.Description + "','" + sd.Gender + "')";
cmd.Transaction = transaction;
cmd.ExecuteNonQuery();**
cmd.CommandText = "select max(StudentID) from StudentDetails";
int id = (int)cmd.ExecuteScalar();
cmd.CommandText = "insert into Qualification (StudentID, Qualification, POY) values ("+id+",'"+sd.Qualification+"',"+sd.POY+")";
cmd.Transaction = transaction;
cmd.ExecuteNonQuery();
transaction.Commit();
}
catch (SqlException sqlError)
{
string s = sqlError.Message.ToString();
transaction.Rollback();
}
db.Close();
return View("SuccessAddStudentData");
}
Thank You
Dilipkumar
Note that date values (DOB) must also contain single quotes.
cmd.CommandText = "insert into StudentDetails(StudentName, DOB, Description, Gender)
values ('" + sd.StudentName + "','" +sd.DOB + "','" +
sd.Description + "','" + sd.Gender + "')";
Also, keep in mind the date format based on SQL Server.
And lastly as other posts mentioned, use bind parameters to prevent SQL injection.
You should ALWAYS use parameterized queries when accessing a SQL database, otherwise your application might be vulnerable to SQL injection. You also should use using when dealing with objects for database access. For example, when the using block is left, the connection will be closed no matter if an exception was thrown or not.
try
{
using (var db = new SqlConnection("connection string"))
using (var transaction = db.BeginTransaction())
using (var cmd = db.CreateCommand())
{
cmd.Transaction = transaction;
db.Open();
cmd.CommandText = "insert into StudentDetails(StudentName, DOB, Description, Gender) values(#name, #dob, #desc, #gender)";
cmd.Parameters.AddWithValue("#name", sd.StudentName);
cmd.Parameters.AddWithValue("#dob", sd.DOB);
cmd.Parameters.AddWithValue("#desc", sd.Description);
cmd.Parameters.AddWithValue("#gender", sd.Gender);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
// other queries
transaction.Commit();
}
}
catch (SqlException ex)
{
string s = ex.Message.ToString();
}
I am trying to insert into a SQL Server database using a C# application.
In C# I am using datetime.now to get the current datetime:
order.PendingDateTime = DateTime.Now;
This gives me 25/07/2014 11:30:17.
In the SQL Server table the datatype is datetime. Which holds the data as 2014-07-23 14:54:01.607 for example.
However running the value 25/07/2014 11:30:17 using a normal insert script it inserts into the SQL Server table fine but displays in the table as 2014-07-25 11:30:17. (This is ok)
However when I use SqlConnection
using (con)
{
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = #sql;
cmd.ExecuteScalar();
}
}
It fails, it says
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.
I think this is because Visual Studio 2010 and SQL Server uses a different datetime format to each other.
How do I fix this?
Current Code:
string sql = "INSERT INTO Order ([LedgerNumber], [OrderNumber], [OrderDate], [PendingDateTime], [EmailAddress]) VALUES (1, '" + rec.OrderNumber + "', CONVERT(datetime, '" + rec.OrderDate + "', 120), CONVERT(datetime, '" + rec.PendingDateTime + "', 120), '" + rec.EmailAddress + "')";
try
{
SqlConnection con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OrderContext"].ConnectionString);
using (con2)
{con2.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con2;
cmd.CommandText = #sql;
cmd.Parameters.AddWithValue("rec.PendingDateTime", DateTime.Now);
cmd.Parameters.AddWithValue("rec.OrderDate", rec.OrderDate);
cmd.ExecuteScalar();
}
Always use sql-parameters instead of string-concatenation. It prevents you from such issues and - more important - from sql-injection:
string sql = #"INSERT INTO Order ([LedgerNumber], [OrderNumber], [OrderDate], [PendingDateTime], [EmailAddress])
VALUES (1, #OrderNumber, #OrderDate, #PendingDateTime, #EmailAddress)";
using (var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OrderContext"].ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("#OrderNumber", rec.OrderNumber);
cmd.Parameters.AddWithValue("#OrderDate", rec.OrderDate);
cmd.Parameters.AddWithValue("#PendingDateTime", rec.PendingDateTime);
cmd.Parameters.AddWithValue("#EmailAddress", rec.EmailAddress);
con.Open();
cmd.ExecuteNonQuery();
}
You: "if I wasn't using datetime.now and get a datetime from a value entered by user. Say '24/07/2014 10:30' how do I use the AddWithValue to achieve this?"
You have to parse the input to DateTime first. Therefore use DateTime.Parse or DateTime.TryParse, DateTime.ParseExact or DateTime.TryParseExact. The TryParse-methods enable you to check if the input is a valid DateTime.
For example:
DateTime pendingDateTime;
if(!DateTime.TryParse(TxtPendingDateTime.Text, out pendingDateTime))
{
MessageBox.Show("Please enter a valid Pending-Date in the format: yourformat");
return;
}
// here you can go on with the code above
Hello I want to store datetimepicker value into mysql database my code is given below
dtpDate = datetimepicker1.value.date;
dtpTime = datetimepicker2.value.Timeofday;
MySqlCommand cmd = new MySqlCommand("INSERT INTO schedule_days(schedule_name,start_time,status,days,start_date,connector_id) VALUES ('" + name + "','" + dtpTime + "','" + s + "','" + day + "','"+dtpDate+"','" + chkArray[i].Tag + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
but no value is being stored at database
and at that place there is unable to read data comes.
what may be the problem?
The Value is not being entered at MySQL database because there is mistake in your query at dtpTime and dtpDate fields.
you shout replace it whith dtpTime.Value.TimeofDay and dtpDate.Value.Date ane new query will be like this
dtpDate = datetimepicker1.value.date;
dtpTime = datetimepicker2.value.Timeofday;
MySqlCommand cmd = new MySqlCommand("INSERT INTO schedule_days(schedule_name,start_time,status,days,start_date,connector_id) VALUES ('" + name + "','" + dtpTime.Value.TimeofDay + "','" + s + "','" + day + "','"+dtpDate.Value.Date.ToString("yyyy-MM-dd HH:mm")+"','" + chkArray[i].Tag + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Well, it may not be the cause of the problem (are there any exceptions? What does ExecuteNonQuery return?) but you should definitely not be building up your SQL like this. It leads to SQL injection attacks, as well as data conversion problems.
Instead, you should use parameterized SQL:
using (MySqlConnection conn = new MySqlConnection(...))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(
"INSERT INTO schedule_days(schedule_name,start_time,status,days,start_date,connector_id) " +
"VALUES (#name, #time, #status, #days, #date, #connector)", conn))
{
cmd.Parameters.Add("#name", MySqlDbType.VarChar).Value = name;
cmd.Parameters.Add("#time", MySqlDbType.Time).Value = dtpTime;
cmd.Parameters.Add("#status", MySqlDbType.VarChar).Value = s;
cmd.Parameters.Add("#days", MySqlDbType.Int32).Value = day;
cmd.Parameters.Add("#date", MySqlDbType.Date).Value = dtpDate;
cmd.Parameters.Add("#connector", MySqlDbType.VarChar).Value = chkArray[i].Tag;
int insertedRows = cmd.ExecuteNonQuery();
// TODO: Validate that insertedRows is 1?
}
}
I've guessed at the data types - please check them against your actual database.
Using NuGet Package MySql.Data 6.6.4.
Currently MySqlParameter does not support unnamed parameters. Parameters must begin with with a ?.
Example:
command.Parameters.AddWithValue("?Parameter", value);
Something like this should work. Avoid string concatenation with Sql because that can lead to security risks.
dtpDate = datetimepicker1.value.date.ToString("yyyy-MM-dd HH:mm"); //Formatted Date for MySql
dtpTime = datetimepicker2.value.Timeofday;
using(var connection = new MySqlConnection(connectionString))
{
using(var command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO schedule_days(schedule_name,start_time,status,days,start_date,connector_id) VALUES ( ?ScheduleName, ?StartTime, ?Status, ?Days, ?StartDate, ?ConnectorId )";
command.Parameters.AddWithValue("?ScheduleName", name);
command.Parameters.AddWithValue("?StartTime", dtpTime);
command.Parameters.AddWithValue("?Status", s);
command.Parameters.AddWithValue("?Days", day);
command.Parameters.AddWithValue("?StartDate", dtpDate);
command.Parameters.AddWithValue("?ConnectorId", chkArray[i].Tag);
connection.Open();
command.ExecuteNonQuery();
}
}
I have a Form where I am inserting a record into the database. There are two tables, table_1 is called members, and table_2 is called Amount.
I am using two SQL INSERT statements to send records to database , because that’s the way I have figured out -- there might be other ways, which I don’t know.
When I insert the record I get a message that it is inserted successfully, but when I check the database the inserted record replaces the one present , so I have last record in the DB repeated several times. Please assist.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CemiyetAidatSistem
{
public partial class AddMember : Form
{
public AddMember()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("Data Source=My-PC\\SQLSERVER;Initial Catalog=FredericiaDernek;Integrated Security=True");
private void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
string Sql = "INSERT INTO Uyeleri ( dID, FullName, Address, Mobile, Email, Comments ) VALUES ('" + txtdID.Text + "', '" + txtAdiSoyadi.Text + "','" + txtAddress.Text + "','" + txtMobile.Text + "','" + txtEmail.Text + "','" + txtComments.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "INSERT INTO Aidat (dID Year, Amount ) VALUES ('"+ txtdID.Text +"','" + txtYear.Text + "','" + txtAmount.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
MessageBox.Show("Data Added Scuessfully");
}
}
}
I have rewritten your code to correct errors and bad practices
string connString = "Data Source=My-PC\\SQLSERVER;Initial Catalog=FredericiaDernek;Integrated Security=True";
private void btnInsert_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(connString))
{
con.Open();
string Sql = "INSERT INTO Uyeleri (dID, FullName, Address, Mobile, Email, Comments ) " +
"VALUES (#id, #name, #address, #mobile, #email, #comments");
using(SqlCommand cmd = new SqlCommand(Sql, con))
{
cmd.Parameters.AddWithValue("#id", txtdID.Text);
cmd.Parameters.AddWithValue("#name", txtAdiSoyadi.Text);
cmd.Parameters.AddWithValue("#address", txtAddress.Text);
cmd.Parameters.AddWithValue("#mobile", txtMobile.Text);
cmd.Parameters.AddWithValue("#email", txtEmail.Text);
cmd.Parameters.AddWithValue("#comments", txtComments.Text);
cmd.ExecuteNonQuery();
Sql = "INSERT INTO Aidat (dID, [Year], Amount ) VALUES " +
"(#id, #year, #amount)";
cmd.Parameters.Clear();
cmd.CommandText = Sql; // <- missing this in the previous version.....
cmd.Parameters.AddWithValue("#id", txtdID.Text);
cmd.Parameters.AddWithValue("#name", txtYear.Text);
cmd.Parameters.AddWithValue("#amount", txtAmount.Text);
cmd.ExecuteNonQuery();
}
}
What I have changed:
The second insert statement is wrong. Missing a comma between first
and second column
Removed the creation of the SqlConnection at the global level
Added appropriate using statement to dispose the SqlConnection and
SqlCommand also in case of exceptions
Used parameters for the two insert statements
Added square brackets around Year field (Year is a reserved keyword
in T-SQL)
Creating a SqlConnection at the global level is bad, because you grab system resources and you don't dispose them for the lifetime of your application. And the situation could be out of control in case of exceptions not correctly handled.
Now I have some doubt about your tables. The fields dID (both tables) and Amount are of text type (varchar,nvarchar)?. If they are of numeric type it is necessary to add a conversion before adding the values to the Parameters collection
I would also suggest changing your for loop to clear the controls replace this
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
with the following code using linq.
this.Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear());
keep in mind that 'this' will refer to the name of your Form
so it would be
(YourWinFormsName).Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear());