I have problem with the query to delete a row from table(I am using MySQL lite), I'm using data bound comobox to select what to delete but I get this error {"Invalid column name 'Football'."} on executing the command
con.Open();
SqlCommand cm = new SqlCommand("DELETE FROM Sports WHERE Sport = " + cbSelectSport.Text + "", con);
cm.ExecuteNonQuery();
MessageBox.Show("Done");
con.Close();
String concatenation should be avoided in almost every case. You should use parameterized queries whenever possible. You avoid conversions, SQL injection attacks and the code is typically faster because the server can reuse execution plans
Writing a parameterized query is also easier:
using(var con=new SqlConnection(...))
{
con.Open();
var cm = new SqlCommand("DELETE FROM Sports WHERE Sport = #sports", con);
var parameter=cm.Parameters.AddWithValue("#sports",cbSelectSport.Text);
cm.ExecuteNonQuery();
MessageBox.Show("Done");
};
This way the parameter values are passed out of band (ie outside the query) without converting to text. This is extremely useful when you want to pass decimal or date values.
Most people would warn against using AddWithValue because it makes too many assumptions based on its input value that can hurt performance. In this case you can use Add to create the parameter, then set its value, size, precision etc:
var parameter=cm.Parameters.Add("#sports",SqlDbType.NVarChar);
parameter.Size=20;
parameter.Value=cbSelectSport.Text;
Be careful with you syntax.
I don't know the type of the sport column, but I think need to enclose your value in quotes( single or double).
new SqlCommand("DELETE FROM Sports WHERE Sport = \"" + cbSelectSport.Text + "\", con);
or
new SqlCommand("DELETE FROM Sports WHERE Sport = '" + cbSelectSport.Text + "', con);
You must specify textvalue in single quotation marks ''.
SqlCommand cm = new SqlCommand("DELETE FROM Sports WHERE Sport = '" + cbSelectSport.Text + "'", con);
You might want to add the single quote:
SqlCommand cm = new SqlCommand("DELETE FROM Sports WHERE Sport = '" + cbSelectSport.Text + "'", con);
You should use parametrized query to prevent SQL Injection attack. Also it will solve your problem. By the way you can just add single quotes to your query.
"DELETE FROM Sports WHERE Sport = '" + cbSelectSport.Text + "'"
Related
I'm using a a multiple query with insert and update statement together.
The problem is that if query will not be completed(for some reason e.x bad internet connection) my SQL Server table keeps rubbish.
Example of query:
SqlCommand cmd = new SqlCommand("INSERT INTO CustomerTrans (TableName, UserID, UserName, SumQuantity, SumPrice, SumRealPrice, SumExtrasPrice, SumTotal, SumDiscountTotal, DateTime) SELECT " + Connection.TableName + ",' " + Connection.UserID + "', '" + Connection.Username + "',Sum(Quantity),Sum(Price),Sum(RealPrice),Sum(ExtrasPrice), Sum(Quantity * Price),Sum(Quantity * DiscountPrice),'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' from InventoryTransTemp where active=1 and TableName=" + Connection.TableName + ";update InventorytransTemp set TrnDocumentID=(select max(TrnDocumentID) from CustomerTrans where UserID='" + Connection.UserID + "'),Active=0 where TableName=" + Connection.TableName + " and Active=1", con);
cmd.ExecuteNonQuery();
Take a photo from a query which has not be completed properly look query 2989 it has NULL values. I want to avoid inserting something if query is not be completed properly.
Sorry for my previous Question it was Unclear
Try it like this:
string sql =
"INSERT INTO CustomerTrans" +
" (TableName, UserID, UserName, SumQuantity, SumPrice, SumRealPrice, SumExtrasPrice, SumTotal, SumDiscountTotal, DateTime)" +
" SELECT #TableName, #UserID, #Username, Sum(Quantity), Sum(Price), Sum(RealPrice), Sum(ExtrasPrice), Sum(Quantity * Price), Sum(Quantity * DiscountPrice), current_timestamp" +
" FROM InventoryTransTemp" +
" WHERE active=1 and TableName= #TableName;\n" +
"SELECT #TranID = scope_identity;\n"
"UPDATE InventorytransTemp" +
" SET TrnDocumentID=#TranID ,Active=0" +
" WHERE TableName= #Tablename and Active=1;";
using (var con = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand(sql, con))
{
//I'm guessing at exact column types/lengths here.
// You should update this to use your exact column types and lengths.
// Don't let ADO.Net try to guess this for you.
cmd.Parameters.Add("#TableName", SqlDbType.NVarChar, 20).Value = Connection.TableName;
cmd.Parameters.Add("#UserID", SqlDbType.Int).Value = Connection.UserID;
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 20).Value = Connection.Username;
cmd.Parameters.Add("#TranID", SqlDbType.Int).Value = 0; //placeholder only
con.Open();
cmd.ExecuteNonQuery();
}
Note the improved formatting of the query, the use of scope_identity() to get the new identity value rather than a nested select statement that might not be atomic, that I avoided ALL uses of string concatenation to substitute data into the query, that I avoided the AddWithValue() method entirely in favor of an option that doesn't try to guess at your parameter types, and the use of using blocks to be sure the SqlClient objects are disposed properly.
The only thing I'm still concerned about is if your INSERT/SELECT operation might create more than one new record. In that case, you'll need to handle this a different way that probably involves explicit BEGIN TRANSACTION/COMMIT statements, because this code only gets one #TranID value. But in that case, the original code was broken, too.
Hi and thank you in advance for any help.
I have a problem with reading from a SQL database.
The command works 100% if i specify the column name
SqlCommand com = new SqlCommand("Select * From Stock where Fuad > 0 ", con);
but the problem is that my program tracks stock movement, between users, and i need to use a command similar to
String currentuser = //(current user logged in, passed when logged in)
SqlCommand com = new SqlCommand("Select * From Stock where '" + currentuser + "' > 0 ", con);
but when i run this code i get an error: "Conversion failed when converting varchar value 'Fuad' to datatype int." Now i know my column in sql is set to Int. but how does that affect the column name?
i can go and write this out for every user, but that would be pointless in the long run as for every new staff member i will have to write a update. is there a way to use a generic caller ie: currentuser to help with this.
the SQL database is setup with int columns, each column has the technicians/staff members name, and tracks how many of each part he currently has booked out.
i just cant figure out how to call the column name if its an Int, because any string that i use will be varchar.
the full code for loading this is
SqlConnection con = new SqlConnection(Connectstring)
con.Open();
SqlCommand com = new SqlCommand("Select * From Stock where '" + currentuser + "' > 0 ", con);
try
{
SqlDataReader dr = com.ExecuteReader();
while (dr.Read())
{
ListViewItem item = new ListViewItem(dr["ItemName"].ToString());
item.SubItems.Add(dr["ItemCode"].ToString());
item.SubItems.Add(dr[currentuser].ToString());
listView1.Items.Add(item);
}
dr.Close();
and as said earlier this works 100% if i replace the "currentuser" with the column name. is it possible to call it with a string, if not i will have to find another way to do this.
Try using [Fieldname] this way:
String currentuser = //(current user logged in, passed when logged in)
SqlCommand com = new SqlCommand("Select * From Stock where [" + currentuser + "] > 0 ", con);
String currentuser = //(current user logged in, passed when logged in)
SqlCommand com = new SqlCommand("Select * From Stock where " + currentuser + " > 0 ", con);
Just don't use that single brackets for column name "'".
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.
I'm making a management program with C# & SQL Server 2008. I want to search records using Blood Group, District & Club Name wise all at a time. This is what is making prob:
SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Table2
WHERE #Blood_Group =" + tsblood.Text + "AND #District =" + tsdist.Text +
"AND Club_Name =" + tscname.Text, Mycon1);
Can anyone tell me what is the correct syntax? Tnx in advance. :)
The correct syntax is to use parametrized queries and absolutely never use string concatenations when building a SQL query:
string query = "SELECT * FROM Table2 WHERE BloodGroup = #BloodGroup AND District = #District AND Club_Name = #ClubName";
using (SqlDataAdapter sda = new SqlDataAdapter(query, Mycon1))
{
sda.SelectCommand.Parameters.AddWithValue("#BloodGroup", tsblood.Text);
sda.SelectCommand.Parameters.AddWithValue("#District", tsdist.Text);
sda.SelectCommand.Parameters.AddWithValue("#ClubName", tscname.Text);
...
}
This way your parameters will be properly encoded and your code not vulnerable to SQL injection attacks. Checkout bobby tables.
Also notice how I have wrapped IDisposable resources such as a SqlDataAdapter into a using statement to ensure that it is properly disposed even in case of an exception and that your program will not be leaking unmanaged handles.
You forgot an AND (and possible an # in front of Club_Name?):
String CRLF = "\r\n";
String sql = String.Format(
"SELECT * FROM Table2" + CRLF+
"WHERE #Blood_Group = {0}" + CRLF+
"AND #District = {1} " + CRLF+
"AND Club_Name = {2}",
SqlUtils.QuotedStr(tsblood.Text),
SqlUtils.QuotedStr(tsdist.Text),
SqlUtils.QuotedStr(tscname.Text));
SqlDataAdapter sda = new SqlDataAdapter(sql, Mycon1);
Can someone let me know what is wrong with my SQL Statement and how I can improve it?
da = new SqlDataAdapter("SELECT * FROM Guests"+" WHERE Students.name='" +
byNametextBox.Text + "'", MyConn);
An EXISTS predicate is slightly more efficient than a JOIN if you want only columns from one of the tables. Additionaly - never inject strings into SQL statements like that - you're just begging for SQL Injection attacks, or related crashes errors (Yes, I know it's a Forms application, but the same holds true. If you're searching for a name like "O'Leary", you'll get a crash).
SqlCommand cmd = new SqlCommand("SELECT * FROM Guests WHERE EXISTS (SELECT Id FROM Students WHERE Guests.StudentId = Students.Id And Students.name= #name)", MyConn);
cmd.Parameters.Add("#name", SqlDbType.VarChar, 50).Value = byNametextBox.Text;
SqlDataAdapter adapt = new SqlDataAdapter(cmd);
Note: Some people may argue that "SELECT *" is bad, and that you should consider specifying individual column names
You need to worry about SQL Injection. Put simply, SQL Injection is when a user is able to put arbitrary SQL statements into your query. To get around this, either use a Stored Procedure or a Parametrized SQL Query. An Example of a Parametrized SQL query is below:
SqlConnection conn = null;
SqlDataReader reader = null;
//Connection string goes here
string studentName = byNametextBox.Text;
SqlCommand cmd = new SqlCommand(
"SELECT * FROM Guests "+" WHERE Students.name = #name", conn);
SqlParameter param = new SqlParameter("#name", SqlDbType.NVarChar, 50);
param.Value = studentName;
cmd.Parameters.Add(param);
reader = cmd.ExecuteReader();
//Do stuff with reader here
SqlDataAdapter("SELECT Guests.* FROM Guests,Students WHERE Guest.StudentId = Student.Id and Students.name='" + byNametextBox.Text + "'", MyConn);`
You need an Inner Join. I think it would be something like this:
SELECT Guests.* FROM Guests INNER JOIN Students ON Students.name = Guests.name WHERE Students.name = '" + byNametextBox.Text + "'"
Try it:
"SELECT g.*
FROM Guests g
INNER JOIN Students s ON g.StudentId = s.StudentId
WHERE Students.Name = '" + byNametextBox.Text + '"'
Assuming that the field wich relates both tables is StudentId.
Beware that SQL is not the same between different Servers. This statement will work on Sql Server, I don't know in others. Also, beware that you aren't protecting yourself on SQL Injection attacks. You should perform your query with parameters, instead of concatenating strings in the way you are doing it.
This is a simple query that you should know by yourself. You can search for tutorials on Google, but here is a generic introduction.