Insert datetime from C# into SQL Server database - c#

when I try to insert datetime value into a SQL Server database I get this error:
Conversion failed when converting date and/or time from character string
Code:
connection.Open();
SqlCommand command = new SqlCommand("insert into table values(#time)", connection);
command.Parameters.AddWithValue("#time", DateTime.Now);
command.ExecuteNonQuery();
connection.Close();
Table table has 1 datetime column called time.
Edit:
my table created in msSQL 2012: http://i.imgur.com/TJ3t3y7.png
my real code is:
public void vytvorDotaz(String uzivatel, DateTime cas, String nazev, String dotaz)
{
int id = getMaxID() + 1;
connection.Open();
SqlCommand command = new SqlCommand("insert into otazky values('" + id + "', '" + uzivatel + "', '0','0','0','#cas','" + nazev + "','" + dotaz + "')", connection);
command.Parameters.AddWithValue("#cas", DateTime.Now);
command.ExecuteNonQuery();
connection.Close();
}

The actual problem here is that you're writing the parameter inside quotes:
... ,'0','#cas',' ...
^ ^
This will not use #cas as a parameter, you're actually trying to insert the string "#cas" into that column, not the contents of the parameter #cas.
Remove the quotes and that part should work.
Additionally, don't use string concatenation to build up the SQL, use parameters for everything, save you some headache from SQL injection attacks or quotes or whatnot. This is related to the "id", "uzivatel", "nazev", and "dotav" parameters you're using (method parameters that is).

Looks like you need:
insert into table values(#time)
Without the single character quote.

Try System.Data.SqlTypes.SqlDateTime Also when storing dates please consider storing them as UTC to prevent confusion.

Related

execute sql command in asp.net

I have a problem with executing a sql command to the DB. The command should add a new user to the 'users' table.
But when I run the code, I get this Exception on:
command.ExecuteNonQuery();
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.OleDb.OleDbException: Syntax error in INSERT INTO statement.
this is the code of the page - GetSignIn.cshtml :
#{
string Uname = Request["name"];
string userName = Request["userName"];
string pass = Request["passWord"];
string pic = Request["pic"];
string privacy = Request["privacy"];
if(pic == null)
{
pic = "Shared/defaultPic.jpg";
}
System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Etay\Documents\Visual Studio 2012\WebSites\Josef\Shared\users.mdb";
try
{
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
connection.Open();
command.CommandText = "INSERT INTO users (userName,passWord,Uname,pic) VALUES ('" + userName + "', '" + pass + "', '" + Uname + "', '" + pass + "', " + pic + ")";
command.ExecuteNonQuery();
Response.Redirect("../HtmlPage.html");
}
finally
{
connection.Close();
}
}
What should I change in my code? Why is it happening? Where is the syntax error in the INSERT INTO?
Use parameterized queries. Here is your statement rewritten to make use of them.
I replaced your try/finally with a using block although your try/finally was acceptable.
Parameterized queries prevent errors and Sql Injection Attacks. An error could occur in your existing code if I were to submit a tick as a part of my user name or password. In the current form this would result in an exception. This is because the tick character is used to quote strings in sql syntax.
using (System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection())
{
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Etay\Documents\Visual Studio 2012\WebSites\Josef\Shared\users.mdb";
using (System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand())
{
command.Connection = connection;
command.CommandText = "INSERT INTO users (userName,passWord,Uname,pic) VALUES (?,?,?,?)";
command.Parameters.Add(userName);
command.Parameters.Add(pass);
command.Parameters.Add(Uname);
command.Parameters.Add(pic);
connection.Open();
command.ExecuteNonQuery();
}
}
About parameters for an OleDb connection from OleDbCommand.Parameters
Remarks
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.
What should I change in my code?
Change to parameters (that also fixes the problem that you don;t have quotes around the pic value)
Remove the second instance of pass in your values
command.CommandText = "INSERT INTO users (userName,passWord,Uname,pic) VALUES (#userName, #pass, #Uname, #pic)";
command.Parameters.Add("#userName").Value = userName;
.. etc.
It's unclear what the type if pic is - you are passing a string but I can;t tell of the column stores a file path or if you are indending to serialize the file and store it in a pinary field.
You set 4 fields after the "INTO" clause, however you're passing 5 parameters:
"INSERT INTO users (userName,passWord,Uname,pic) VALUES ('" + userName + "', '" + pass + "', '" + Uname + "', '" + pass + "', " + pic + ")";
Just add the fifth field, or remove one parameter from the VALUES part
Please check take a look at your Insert statement, it looks like that you provided password value twice.
The number of query values and the destination fields should be same in an INSERT statement.
You have the wrong number parameters in your insert statement. For clarity, why not use string.Format to keep everything uniform? (Assuming these are all string types)
var rawSql = #"Insert INTO Users (userName,passWord,Uname,pic) VALUES ('{0}','{1}','{2}','{3}')";
command.CommandText = string.Format(rawSql, userName, pass, Uname, pic);
command.ExecuteNonQuery();
However, it also looks like you probably want to include that 5th parameter as well - just extend the format :
var rawSql = #"Insert INTO Users (userName,passWord,Uname,pic, privacy) VALUES ('{0}','{1}','{2}','{3}','{4}')";
command.CommandText = string.Format(rawSql, userName, pass, Uname, pic, privacy);
command.ExecuteNonQuery();
Since most of the answers failed to address the SQL Injection vulnerability, here's an example with parameterized queries. In addition to preventing SQL Injection attacks, it also makes it easier to troubleshoot these types of issues, and you don't need to worry about quoting or not quoting parameters.
System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Etay\Documents\Visual Studio 2012\WebSites\Josef\Shared\users.mdb";
try
{
System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand();
command.Connection = connection;
connection.Open();
command.CommandText = "INSERT INTO users (userName, passWord, Uname, pic, privacy) VALUES (?, ?, ?, ?, ?)";
command.Parameters.Add(userName);
command.Parameters.Add(pass);
command.Parameters.Add(name);
command.Parameters.Add(pic);
command.Parameters.Add(privacy);
command.ExecuteNonQuery();
Response.Redirect("../HtmlPage.html");
}
finally
{
connection.Close();
}
Tnx 4 the help
It happend to be a problem with the database - you can not apply a INSERT INTO statement where the column name is "password". "password" is a Reserved word
in SQL.
Tnx again,
Etay

save a decimal value in database c#

I am trying to save a value from text box into sql database. I am having the error as shown on the picture. my code below:
public void datastore()
{
string Blerje, Shitje, Data;
Blerje = usdollar_buy.Text;
Shitje = usdollar_sell.Text;
Data = dateTimePicker.Text;
try
{
string constring = "Data Source=DELL;Initial Catalog=login_register;Integrated Security=True";
/* Declaring Connection Variable */
SqlConnection con = new SqlConnection(constring);
String sql = "INSERT into [login_register].[dbo].[BlerjeShitje] values ('" + Blerje + "','" + Shitje + "','" + Data + "')";
/* Checking Connection is Opend or not If its not open the Opens */
if (con.State != ConnectionState.Open)
con.Open();
SqlCommand cmd = new SqlCommand(sql, con);
/* Executing Stored Procedure */
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Te dhenat u ruajten ne databaze");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
1. You might be having more columns in your table than mentioned values(3) in your query.
so it is always good to specify the column names in your query for which columns you are inserting the values.
Try This:
INSERT INTO [TableName](COL1,COl2,COL3)
Values(Value1,Value2,Value3);
2. As you mentioned your columsn are decimals, you are inserting them as as strings by enclosing the values within single quotes.
You should not enclose the decima values within single quotes.
Suggestion : Your query is open to SQL Injection Attacks.
I Would suggest you to use the Parameterised queries to avoid them.
You are missing the fields in your insert statement.
The database will try to determine the right columns and their order, but if you don't deliver all fields in the appropriate order, your query will fail.
So in short:
Deliver all fields in the correct order;
Or: add the fields you want to fill in the insert.
Sample:
String sql = "INSERT into [login_register].[dbo].[BlerjeShitje] (Blerje, Shitje, Data) values ('" + Blerje + "','" + Shitje + "','" + Data + "')";
change the datatype to (18,6) or so, whichever is suitable for you,
The second part of decimal data type shows how many digits do you require after the 'point'. In your case it's '0', so db is rounding it to nearest integer.
Source: http://msdn.microsoft.com/en-us/library/ms187746.aspx

Syntax error in UPDATE statement OleDb Exception

I check my SQL Statement many times and it seems that my SQL Statement is Error. I don't why it doesn't work. My SQL Statement is correct and It resulted to this OleDBException "Syntax error in UPDATE statement.".
Here is the code
OleDbConnection CN = new OleDbConnection(mysql.CON.ConnectionString);
CN.Open();
cmd1 = new OleDbCommand("Update Mosque Set Name='" + txtNAME.Text + "', No='" + Convert.ToInt32(txtNO.Text) + "', place='" + txtPlace.Text + "', group='" + txtGroup.Text + "', description='" + txtdec.Text + "' where id='" + txtID.Text + "'", CN);
cmd1.ExecuteNonQuery();
CN.Close();
need help please to know what is the error here
I don't know what database are you using, but I am sure that GROUP is a reserved keyword in practically any existant SQL database. This word cannot be used without some kind of delimiter around it. The exact kind of delimiter depend on the database kind. What database are you using?
Said that, please do not use string concatenation to build sql commands, but use always a parameterized query. This will allow you to remove any possibilities of Sql Injection and avoid any syntax error if one or more of your input string contains a single quote somewhere
So, supposing you are using a MS Access Database (In Access also the word NO is a reserved keyword and the delimiters for reserved keywords are the square brakets) you could write something like this
string commandText = "Update Mosque Set Name=?, [No]=?, place=?, " +
"[Group]=?, description=? where id=?"
using(OleDbConnection CN = new OleDbConnection(mysql.CON.ConnectionString))
using(OleDbCommand cmd1 = new OleDbCommand(commandText, CN))
{
CN.Open();
cmd1.Parameters.AddWithValue("#p1",txtNAME.Text);
cmd1.Parameters.AddWithValue("#p2",Convert.ToInt32(txtNO.Text));
cmd1.Parameters.AddWithValue("#p3",txtPlace.Text);
cmd1.Parameters.AddWithValue("#p4",txtGroup.Text);
cmd1.Parameters.AddWithValue("#p5",txtdec.Text);
cmd1.Parameters.AddWithValue("#p6",txtID.Text);
cmd1.ExecuteNonQuery();
}
Instead for MySQL you have to use the backticks around the GROUP keyword
string commandText = "Update Mosque Set Name=?, No=?, place=?, " +
"`Group`=?, description=? where id=?"
Hard to tell without knowing the values of the texboxes, but I suspect that one of them has an apostrophe which is causing an invalid syntax.
I recommend using parameters instead:
cmd1 = new OleDbCommand("Update Mosque Set [Name]=#Name, [No]=#No, [place]=#Place, [group]=#Group, [description]=#Description WHERE id=#ID", CN);
cmd1.Parameters.AddWithValue("#Name",txtNAME.Text);
cmd1.Parameters.AddWithValue("#No",Convert.ToInt32(txtNO.Text));
// etc.

Casting datareader values to integer in insert statement

I am building an insert statement with data from an excel file using data reader values. The excel file datareader always only has one record. There are two columns in the destination table, first of type int and second column of varchar.
while (dr.Read())
{
string insertstring = #"insert into configtest values
('" + dr.GetValue(0) + "','"
+ dr.GetValue(1) + "')";
}
SqlCommand commandInsert = new SqlCommand(insertstring, conn);
commandInsert.ExecuteNonQuery();
I get error
"Error converting varchar type to numeric.
I tried casting the first value to type int and get a
"Specified cast is not valid"
error. Please help with this.
If the first column in the destination table is an integer column you should not pass a string.
In your concatenation command you put single quotes around the first parameter and this means you try to pass a string. Thus the error.
However you should always write a parameterized query, not try to build a sql command using string concatenation
string insertstring = #"insert into configtest values (#p1, #p2)";
while (dr.Read())
{
SqlCommand commandInsert = new SqlCommand(insertstring, conn);
if(dr.IsDBNull(0))
commandInsert.Parameters.AddWithValue("#p1", DBNull.Value);
else
commandInsert.Parameters.AddWithValue("#p1", Convert.ToInt32(dr[0]));
if(dr.IsDBNull(1))
commandInsert.Parameters.AddWithValue("#p2", DBNull.Value);
else
commandInsert.Parameters.AddWithValue("#p2", dr[1].ToString());
commandInsert.ExecuteNonQuery();
}
This approach will keep you safe from Sql Injection and from syntax error triggered if your string values contain single quotes.
As a final note, keep in mind that when a DataReader is open you cannot use its connection for other activities (ExecuteNonQuery) unless you use the MultipleActiveResultSets=True in your connection string
Replace your string with following (assuming your dr.GetValue(0) is int.)
string insertstring = #"insert into configtest values
(" + dr.GetValue(0) + ",'"
+ dr.GetValue(1) + "')";
Just removed quotes around dr.GetValue(0). As it is of type int it does not require quotes.
EDIT:
To insert null values, you can check for null values in query itself-
string insertstring = #"insert into configtest values
(" + (dr.GetValue(0) == null ? System.Data.SqlTypes.SqlInt32.Null : dr.GetValue(0)) + ",'"
+ (dr.GetValue(1) == null ? string.Empty : dr.GetValue(1)) + "')";
Though this is not the perfect solution but can do a workaround !!!!

"Out-of-range value" error when converting a varchar to datetime

I have this code
datecreation = todaydate.Substring(6, 4) + todaydate.Substring(3, 2) +
todaydate.Substring(0, 2)
string sql = "insert into Usertable ";
sql += "values(" + mVendid + ", '" + usrname + "','" + usrpass + "', cast('" +
datecreation + "'as DATETIME),'" + createdby + "')";
The problem is whenever it is running in server it is giving error. In Local host or in SQL server management it is working fine.
What the heck is it not working whenever it is in the web
The error is The conversion of a varchar data type to a datetime data
type resulted in an out-of-range value. The statement has been
terminated.
Never concatenate string to form SQL queries, always use parameterized query. For your code you can use SqlParameter, with your command. There instead of Converting DateTime to string and then casting it back DateTime in INSERT query , simply add the value of DateTime object in parameter. This will not only save you from Sql Injection but also resolves issues like the one you are having.
Something like:
using(SqlConnection conn = new SqlConnection("Connectionstring"))
using (SqlCommand cmd = new SqlCommand())
{
string sql = "insert into Usertable ";
sql += "values(#mVendid, #usrname, #usrpass, #datecreation, #createdby)";
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#mVendid", mVendid);
cmd.Parameters.AddWithValue("#usrname", username);
cmd.Parameters.AddWithValue("#usrpass", userpass);
cmd.Parameters.AddWithValue("#datecreation", Convert.ToDateTime(datecreation));
cmd.Parameters.AddWithValue("#createdby", createdby);
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
}
if datecreation is coming from a DateTime object then add that directly, otherwise you can parse it to DateTime object and let SQL server handle the rest for you.
The problem is that probably you server has different language settings that your machine.
To make sure that converting is working you Convert function. Full tutorial is here: http://www.sqlusa.com/bestpractices/datetimeconversion/
BTW constructing queries like concatenate string is very dangerous way. Instead of this use SqlParamerts. Moreover advantage using this approach is that .NET will do conversion for you.
First of all user parameters (better, clearer and safer!). Second this error happens due to format issues.
datecreation = todaydate.Substring(6, 4) + todaydate.Substring(3, 2) +
todaydate.Substring(0, 2)
string date = DateTime.Parse(datecreation);
string sql = "insert into Usertable values(#mvendid, #username, #usrpass, #date, #createdby)";
var con = new SqlConnection(""); // your connection string
var cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#mvendid", mVendid);
...
cmd.Parameters.AddWithValue("#date", date);
First of all its really a bad query and quite hacky, you shouldn't be writing query like this
string sql = "insert into Usertable ";
sql += "values(" + mVendid + ", '" + usrname + "','" + usrpass + "', cast('" +
datecreation + "'as DATETIME),'" + createdby + "')";
*Always use Paramaterised Queries *
Error might be there because you are converting some text to datetime. Possible reasons Datetime not well formed
Dateimte doesn't matches to your server datetime
Try to print out the exact value what its creating
cast('" +
datecreation + "'as DATETIME)
Check the time zone of the server. Likely that it is a different time zone to your local machine. You can avoid the issue by using parameters.
string sql = #"
INSERT INTO Usertable
VALUES (#Parameter1, #Parameter2, #Parameter3, #Parameter4, #Parameter5)";
(using SqlCommand command = new SqlCommand(sql, myConnection))
{
command.Parameters.AddWithValue("#Parameter1", mVendid);
command.Parameters.AddWithValue("#Parameter2", usrname);
command.Parameters.AddWithValue("#Parameter3", usrpass);
command.Parameters.AddWithValue("#Parameter4", todaydate);
command.Parameters.AddWithValue("#Parameter5", createdBy);
command.ExecuteNonQuery();
}

Categories

Resources