protected void Button1_Click(object sender, EventArgs e)
{
if(FileUpload1.HasFile)
{
int Id = Convert.ToInt32(Request.QueryString["Id"]);
String fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("~/Order/" + fileName));
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ToString());
con.Open();
String Update =("Update Order set DesignedImage=#DesignedImage where Id=#Id");
SqlCommand cmd = new SqlCommand( Update , con);
cmd.Parameters.AddWithValue("#DesignedImage", "Order/" + fileName);
cmd.Parameters.AddWithValue("#Id", + Id);
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = "OK";
}
I want to update table Order.
this code is giving me syntax error near keyword Order
Order is a reserved keyword in T-SQL. You need use it with square brackets as [Order].
As a best practice, change it to non-reserved word.
It would be better to use using statement to dispose your connection and command automatically instead of calling Close or Dispose methods manually.
Also don't use AddWithValue as much as you can. It may generate unexpected and surprising results sometimes. Use Add method overload to specify your parameter type (SqlDbType) and it's size.
As a last thing, Open your connection just before you execute your command.
You cannot have Order as your table name since it is reserved keyword on sql queries.
Rename the table and try.
Related
How would I delete a row from a sql database, either with stored procedures or without, right now I have tried without, using a button press.
This is what I have so far, _memberid has been sent over from a differnt form from the database(For context).
private void btnDelete_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = Lib.SqlConnection;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Delete * From Members where MemberId = " + _memberId;
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.DeleteCommand = cmd;
adapter.Fill(MembersDataTable); // Im fairly sure this is incorrect but i used it from old code
DialogResult = DialogResult.OK;
}
If you're trying to do a simple ADO.Net-based delete, then it would be somehting like his:
private void DeleteById(int memberId)
{
// or pull the connString from config somewhere
const string connectionString = "[your connection string]";
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var command = new SqlCommand("DELETE FROM Members WHERE MemberId = #memberId", connection))
{
command.Parameters.AddWithValue("#memberId", memberId);
command.ExecuteNonQuery();
}
}
Use parameter to prevent SQL injection.
There are essentially three main things I'm seeing...
One
You don't need the * in the query. DELETE affects the whole row, so there's no need to specify columns. So just something like:
DELETE FROM SomeTable WHERE SomeColumn = 123
Two
There's no need for a SqlDataAdapter here, all you need to do is execute the query. For example:
cmd.ExecuteNonQuery();
The "non query" is basically a SQL command which doesn't query data for results. Inserts, updates, and deletes are generally "non queries" in this context. What it would return is simply the number of rows affected, which you can use to double-check that it matches what you expect if necessary.
Three
Don't do this:
cmd.CommandText = "Delete From Members where MemberId = " + _memberId;
This kind of string concatenation leads to SQL injection. While it looks intuitively like you're using _memberId as a query value, technically you're using it as executable code. It's less likely (though not impossible) to be a problem for numeric values, but it's a huge problem for string values because it means the user can send you any string and you'll execute it as code.
Instead, use query parameters. For example, you might do something like this:
cmd.CommandText = "Delete From Members where MemberId = #memberId";
cmd.Parameters.Add("#memberId", SqlDbType.Int);
cmd.Parameters["#memberId"].Value = _memberId;
This tells the database engine itself that the value is a value and not part of the executing query, and the database engine knows how to safely handle values.
You could use a DataAdapter, but since you aren't using a datatable, it's just easier to do it without like this:
var sql = "DELETE FROM Members WHERE MemberId=#MemberId";
using(var cmd = new SqlCommand(sql, Lib.SqlConnection))
{
cmd.Connection.Open();
cmd.Parameters.Add("#MemberId",SqlDbType.Int).Value = _memberId;
cmd.ExecuteNonQuery();
}
And if you are using Dapper, you can do this:
Lib.SqlConnection.Execute("DELETE FROM Members WHERE MemberId=#MemberId", new {MemberId=_memberId});
If you are still using DataTables, I would highly recommend you look into using this (or something like this) to simplify your database accesses. It'll make CRUD logic on a database a breeze, and your code will me a lot more maintainable because you can get rid of all the odd needs to do casting, boxing/unboxing, and reduce the chances of runtime bugs because of the use of magic strings that happens so often with DataTables (column names). Once you start working with POCO classes, you'll hate having to use DataTables. That said, there are a few places where DataTables are a better solution (unknown data structures, etc), but those are usually pretty rare.
I am trying to work with a contact list and want to remove all of the info on a person when I type in their name. I am using a sql table -named Contact- that contains the Name, Email and Address of a contact. I have the following code:
protected void Delete_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnect"].ConnectionString);
con.Open();
string delete = "DELETE FROM Contact WHERE Name =" + NameToDelete.Text;
SqlCommand cmd = new SqlCommand(delete, con);
try
{
cmd.Parameters.AddWithValue("#Name", delete);
cmd.ExecuteNonQuery();
Response.Redirect("ViewContacts.aspx");
}
catch(Exception ex)
{
Response.Write(ex);
}
}
When I use this, it seems to be comparing the column Name to the name I am putting in. So the name Bill is being compared against the column header Name instead of what is in the name.
You need to use single quotes around the values with var(char) types. If you don't use quotes it will think that you are referencing a column name instead of value.
It's valid for all databases, following is from oracle docs:
character literals are enclosed in single quotation marks, which
enable Oracle to distinguish them from schema object names.
https://docs.oracle.com/cd/A87860_01/doc/server.817/a85397/sql_elem.htm
string delete = "DELETE FROM Contact WHERE Name ='" + NameToDelete.Text + "'";
Actually what you are trying to do is using sqlcommand parameter, then you need to use parameter name using #[ParameterName] in sql statement.
string delete = "DELETE FROM Contact WHERE Name = #Name";
Seems that your problem is that you are using the variable delete in two instances. First for create the command that is fine and second as the parameter value, which is wrong. In the parameter value probably you must use the value tthat you want to delete.
You have several serious problems with your code.
Your connection is never closed or disposed. Use Using blocks which will close and dispose of database objects even if there is an error.
You are concatenating a string to get your Sql statement risking Sql injection and damage to your database.
You are adding a parameter to your command when there are no parameters in your Sql statement.
You are using .AddWithValue which takes the parameter name and the parameter value as arguments. You have provided your entire Sql statement as the value of #Name. This should be NameToDelete.Text.
Do not use .AddWithValue. Use .Add(parameter Name, Sql data type).Value = value of parameter. This can speed up queries and avoids type mismatches in the database.
If name is your Primary Key, you are OK, but if not you should delete by the primary key or send all values in the Where clause.
protected void Delete_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnect"].ConnectionString))
{
string delete = "DELETE FROM Contact WHERE Name = #Name;"; //no single quotes to worry about
using (SqlCommand cmd = new SqlCommand(delete, con))
{
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = NameToDelete.Text; //just guessed at the VarChar - check your database for type
try
{
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("ViewContacts.aspx");
}
catch (Exception ex)
{
Response.Write(ex.Message); //ex by itself, will get you nothing but the fully qualified name of Exception
}
}
}
}
Background
I am trying to retrieve the count of occurrences of a user in the database at the same time as returning the data set. How do I accomplish this? My code is below of what I have so far.
If I hard code the username, for the row, I get the expected output. However, I am having problems declaring a parameterized query variable with this code. Any help would be appreciated. I have been working on this for quite some time now.
protected void Page_Load(object sender, EventArgs e)
{
string ConnStr = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(ConnStr))
{
string Command = "SELECT TOP 3 *, Counter = (select Count(User) from Projects where [User]='jmoore00' AND Account = 'ACTIVE') FROM Projects";
using (SqlCommand comm = new SqlCommand(Command, conn))
{
conn.Open();
SqlDataReader rdr = comm.ExecuteReader();
ListView.DataSource = rdr;
ListView.DataBind();
rdr.Close();
}
}
}
Above, 'jmoore00' should be scalar variable #User but how do I appropriately declare and use the variable with value equaling rdr["user"] if I am using the code the way it is?
I think you should use Stored Procedure in you sql.as a specific user try to retrieve its data, do add number of this occurrence to a field in your sql.
each user has a unique field which can be in access with their users or userID.
but i think it will increase transaction time .
hope it would be helpful
Hi guys I have got a simple insert statement, I know something is missing as when I click the button to insert the data it dose not insert.
any ideas?
protected void saveyear_Click(object sender, EventArgs e)
{
OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\ASPNetDB.mdb;Persist Security Info=True");
OleDbDataAdapter da = new OleDbDataAdapter();
da.InsertCommand = new OleDbCommand("INSERT INTO DVD_Infomation (Year) VALUES (#Year)", connection);
{
da.InsertCommand.Parameters.AddWithValue("#Year", Year.Text);
}
connection.Open();
da.InsertCommand.ExecuteNonQuery();
connection.Close();
}
YEAR is a reserved keyword for MS-Access Jet.
If you want to use it as name of your column you should enclose it in square brackets
da.InsertCommand = new OleDbCommand("INSERT INTO DVD_Infomation ([Year]) VALUES (#Year)", connection);
{
da.InsertCommand.Parameters.AddWithValue("#Year", Year.Text);
}
If it is still possible, I suggest to change the name of that column. It will be annoying to stump on this error every time you try to use that column in your statements
As a side note, I would write the code above as
using(OleDbConnection connection = new OleDbConnection(.....))
using(OleDbCommand cmd = new OleDbCommand("INSERT INTO DVD_Infomation ([Year]) VALUES (#Year)", connection))
{
cmd.Parameters.AddWithValue("#Year", Year.Text);
connection.Open();
cmd.ExecuteNonQuery();
}
Adding the using statement around the creation of the connection and the command will ensure a proper closing and disposing of these objects also in case of exceptions and keep your program more resource usage friendly
Never use a Reserved word in your tables, if you can help it. Since YEAR is a Reserved word, you need to use brackets around the name. Preferrably, change the field name in your table to avoid that issue in the future. Similarly, using field names with spaces in them is also frowned upon as it, too, creates problems when referencing them.
private void button14_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string c = openFileDialog1.FileName;
string connString = "Server=Localhost;Database=test;Uid=root;password=root;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = ("Insert into data (path) values('" + c + "')");
conn.Open();
command.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Success");
}
}
This code works for me, but unfortunately, the path stored in database is not right .. the stored path is like this (C:Users hesisDesktopREDEFENSEResourcesImagesRED1f.png) where it supposed to be like this (C:P/Users/thesis/Desktop..../1f.png).
But when I checked the "sr" value with this code.. the msgbox show just right..
private void button14_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
MessageBox.Show(openFileDialog1.FileName);
}
}
why is it happening then?
Perhaps MySQL thinks that the "\" character is an escape, so that's why it does not contain it in the string. Try
c.Replace(#"\", #"\\")
when you insert, so the escape character will be escaped.
EDIT: For example, replace the command text initializing line like this. Also add an escape for single quotes.
string escapedPath = c.Replace(#"\", #"\\").Replace("'", #"\'");
command.CommandText = ("Insert into data (path) values('" + escapedPath + "')");
EDIT: See #Matthew's answer for an even more "best practice" solution, using parameterized queries.
This is due to the way you're writing your query. In MySQL, the backslash character \ (which is present in file paths) has special meaning, which is to escape the next character. You need to encode these, many different DBMS's have patterns to do this.
Other than that, your code is susceptible to SQL injection.
To fix both these problems, you can use parametrized queries.
public void InsertPath(string path)
{
string connString = "Server=Localhost;Database=test;Uid=root;password=root;";
using (var connection = new MySqlConnection(connString))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO data(path) VALUES(?path)";
command.Parameters.AddWithValue("?path", path);
command.ExecuteNonQuery();
}
}
}
This answer might not be 100% accurate, because I don't have MySQL on my computer, but hopefully if it doesn't work, it should at least give you some information about how to approach this problem.
Why aren't you using a parameterized query? You can avoid most of the trouble with escaping strings, prevent a whole class of security risks, and gain a tiny bit of performance from query caching if you do.
Normally, it looks something like this:
cmd.CommandText = "INSERT INTO data (path) values(?path)";
cmd.Prepare();
cmd.Parameters.AddWithValue("?path", c);
It's been long enough since I've written any explicity C# query code (6 months or so) that I can't remember if this is exactly right, and I know the MySql provider uses a slightly different parameterization convention than MSSQL for named parameters (which uses #path instead of ?path), but that should get you on the right path. See C# MySqlParameter problem for a little more guidance that might be relevant to you.