datofreg is of type datetime
my command is
SqlCommand cmd = new SqlCommand("insert into stud(datofreg) values('"+DateTime.Now+"'",conn);
when i execute it says Incorrect syntax near '1/6/2014 12:45:17 AM'.
Your problem is you are missing ) at the end of your query but don't use this way..
"insert into stud(datofreg) values('" + DateTime.Now + "')"
^^here
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
For example;
SqlCommand cmd = new SqlCommand("insert into stud(datofreg) values(#date)", conn);
cmd.Parameters.AddWithValue("#date", DateTime.Now);
cmd.ExecuteNonQuery();
Related
This is the error message
MySql.Data.MySqlClient.MySqlException: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 1'
this is my query
MySqlCommand cmd = new MySqlCommand("insert into subject(id, code, title, unit) values('" + textBox1.Text + "',''" + textBox2.Text + "',''" + textBox3.Text + "',''" + textBox4.Text + "')", conn);
I've been looking over at it for over an hour now and I still get this error.
It is recommended to use Parameterized Query.
UPDATED: As suggested by #CodeCaster for the concerns mentioned in Stop Using AddWithValue() article, I switch all the AddWithValue() to Add("#Parameter", SqlDbType).Value.
MySqlCommand cmd = new MySqlCommand("insert into subject(id, code, title, unit) values(#ID, #Code, #Title, #Unit)", conn);
cmd.Parameters.Add("#ID", SqlDbType.int).Value = textBox1.Text;
cmd.Parameters.Add("#Code", SqlDbType.Varchar, 10).Value = textBox2.Text;
cmd.Parameters.Add("#Title", SqlDbType.NVarchar, 50).Value = textBox3.Text;
cmd.Parameters.Add("#Unit", SqlDbType.Varchar).Value = textBox4.Text;
And also be sure that the value you pass with the SqlDbType must match the data type as respective database table column.
The reasons to use Parameterized Query are:
It simplifies the query in passing the parameters and makes the query become more readable.
Prevent SQL Injection.
Reference: Prepare MySQL Statement
The format in the database for date column is yyyymmdd but my code in aspx.cs passes the parameter value as yyyy-mm-dd. How can I convert yyyy-mm-dd to yyyymmdd in the WHERE clause if my select statement?
aspx.cs code:
adapter.SelectCommand = new SqlCommand("select distinct a.e_id from tenter where (date='" + Convert(DateTime.Value.ToString()) + "')", myConn);
Please don't save your DateTime values as a character.
Type your date column as a datetime or datetime2 and pass your DateTime.Now value directly to your parameterized queries. Otherwise, it will be open for SQL Injection attacks.
Read: Bad habits to kick : choosing the wrong data type
As an example;
using(var myConn = new SqlConnection(conString))
using(var cmd = myConn.CreateCommand())
{
cmd.CommandText = "select distinct a.e_id from tenter where date = #date";
cmd.Parameters.Add(#date, SqlDbType.DateTime2).Value = DateTime.Now;
using(var adapter = new SqlDataAdapter(cmd))
{
// Do your operations.
}
}
Also date might reserved word in future releases of SQL Server. You might need to use it as [date] as well.
It may helps you
You can use this logic and work on your query
declare #a date= '2014/2/3'
select replace(#a,'-','')
use SQL CAST()
SqlCommand cmd=new SqlCommand();
cmd.Connection=con;
cmd.CommandText="select distinct a.e_id from tenter where cast(date as date)=cast(#date as date)";
cmd.Paramenter.AddWithValue("#date",Convert.ToDateTime(DateTime.Value));
adapter.SelectCommand = new SqlCommand ("select distinct a.e_id from tenter where (date='" + DateTime.ParseExact(("2015-03-18"), "yyyy-MM-dd", null).ToString("yyyyMMdd") + "')", myConn);
Thank you very much to all of you.
The best answer for me like this:-
adapter.SelectCommand = new SqlCommand ("select distinct a.e_id from tenter where (date='" + startdate.Value.ToString().Replace("-",string.Empty) + "')", myConn);
Maybe simply : DateTime.Value.ToString().Replace("-",string.empty)
for mysql you can try this :
where date_format(date,'%Y%m%d') = '20150318'
#+jef
So im having problem gettin some data in to the database.. Im really stuck, im quite new to c# and have not learned all keywords yet, im not getting any errors just some nothing adds to my database.
textBox2.Text = myPWD;
MySqlConnection conn = new MySqlConnection("test")
string Query = "INSERT INTO `users`.`coffekeys` (`koffekeys`) VALUES ('values = #val')";
MySqlCommand data = new MySqlCommand(Query, conn);
MySqlDataReader myReader;
conn.Open();
SelectCommand.Parameters.AddWithValue("#val", this.textBox2.Text);
conn.Closed()
Manipulate the concatenation of value in passing of parameters. Don't do it inside sql statement.
string Query = "INSERT INTO `users`.`coffekeys` (`koffekeys`) VALUES (#val)";
// other codes
SelectCommand.Parameters.AddWithValue("#val", "values = " + this.textBox2.Text);
the reason why the parameter is not working is because it was surrounded by single quotes. Parameters are identifiers and not string literals.
The next problem is you did not call ExecuteNonQuery() which will execute the command.
Before closing the connection, call ExecuteNonQuery()
// other codes
data.ExecuteNonQuery();
conn.Close();
You should Google around and you will receive lots of content
You need to run ExecuteNonQuery
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlCommand cmd = new SqlCommand(
"insert into st (ID,Name) values ('11','seed');", con);
cmd.ExecuteNonQuery();
cmd.Close();
i want to insert to a sql table a string that might contain ' character.
what is my best way to do so ?
should i insert a \ before the ' ?
here's my command in a c# code:
SqlCommand myCommand = new SqlCommand(
String.Format(
"insert into ACTIVE.dbo.Workspaces_WsToRefile values({0},'{1}',getdate())",
folderId,
NewWorkspaceName),
myConnection);
where NewWorkspaceName might contain ' character, so the insert will cause an exception at the moment.
thanks in advanced, hadas.
You should be using SqlParameter. http://msdn.microsoft.com/en-us/library/yy6y35y8.aspx
string query = "insert into ACTIVE.dbo.Workspaces_WsToRefile values(#folderID, #newWorkSpace, #createDate)";
using(SqlCommand cmd = new SqlCommand(query, SqlConnection))
{
SqlParameter param = new SqlParameter("#folderID", folderId);
param.SqlDbType = SqlDbType.Int;
cmd.Parameters.Add(param);
.....
}
You have only one option, forget everything else. Use Parametrized queries like this
SqlCommand myCommand = new SqlCommand("insert into ACTIVE.dbo.Workspaces_WsToRefile" +
" values(#id, #space, getDate()", myConnection);
myCommand.Parameters.AddWithValue("#id", folderId);
myCommand.Parameters.AddWithValue("#space", NewWorkspaceName);
myCommand.ExecuteNonQuery();
folderID and NewWorkspaceName, are passed to the Sql Engine inside parameters.
This will take care of special characters like quotes.
But you gain another benefit using parametrized queries. You avoid Sql Injection Attacks
NewWorkspaceName= NewWorkspaceName.Replace("\'","\'\'");
'' is a ' in sql
You can try this:
string stringToDatabase=Server.HtmlEncode("կҤїАͻBsdҤїА");
This saves 'stringToDatabase' in your database
. Then while retreiving
string OriginalText=Server.HtmlDecode(stringFromDatabase);
What are the disadvantages of this code :
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=.\sqlExpress;Initial Catalog=Learn;Integrated Security=True";
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Insert Into tblUser(name,family,tel)Values('" + txtName.Text + "','" + txtFamily.Text + "','" + txtTel.Text + "')";
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
You mean besides the fact that the SqlConnection won't be disposed, and that the SqlCommand is written in such a way as to invite a SQL Injection attack?
Relevant XKCD comic:
http://xkcd.com/327/
One major disadvantage is that you don't quote your strings or use parameterized queries, so somebody who inputs O'Brien for their last name will get an exception.
Of course, that also means that somebody can enter arbitrary SQL into a text box and have you execute it for them. That's bad.
Related to secure coding....
Your code is vulnerable to SQL Injection attacks since you are directly using txtName.text in the code to form a query. Parameterized queries should be used. Additionally, you should validate the txtName.txt before using it. That is it.