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 "'".
Related
I'm writing a program using MySQL and WinForm. In my program there's an option to select a VAT Number from a combobox that is retrieve from a table in database. After selecting a VAT Number user have to enter 2 different values into 2 different textbox. After entering those values, the sql query will execute. And show the result in another textbox.
Application form
My sql queries are working fine.
using(MySqlConnection con = new MySqlConnection(cs))
{
con.Open();
//string command;
string command = #"SELECT * FROM `db_liq_blnd_calc_sys`.`tbl_vat_12_spirit_sa` WHERE DIP = '" + txt_Calc_BULK_DIP.Text + "' AND SLIDE = '" + txt_Calc_BULK_SLIDE.Text + "'";
MySqlDataAdapter da = new MySqlDataAdapter(command, con);
DataTable dtable = new DataTable();
DataSet ds = new DataSet();
da.Fill(ds);
DataRow[] returnrow = ds.Tables[0].Select("DIP = '" + txt_Calc_BULK_DIP.Text + "' AND SLIDE = '" + txt_Calc_BULK_SLIDE.Text + "'");
int result = returnrow.Length;
DataRow dr = returnrow[0];
txt_Calc_BULK_BULK.Text = (dr["BULK"].ToString());
con.Close();
}
What I wanna do is, there are 15 table in my database that has same table structure but different data in it. I want to change the sql query that execute by selecting different VAT Number from the combobox.
Since all tables have the same structure, I recommend making one big table for them all and add a VAT Number column to it. Then, to set the values in your combobox, select distinct VAT Numbers from this table. Finally, add the a VAT Number condition to your query.
On a side note, use "Parameterized Query" instead of concatenating values to your query, this would help against SQL Injection Attacks.
This is my first time creating a web api from scratch and I'm trying to get a selected value in a drop down bow to trigger an sql search and make the appropriate item appear in a text box. below is the relevant code
protected void btnRetrieve_Click(object sender, EventArgs e)
{
try
{
string pNameTemp = DropDownList1.SelectedValue;
myConnection.Open();
string query = ("SELECT sName from [dbo].[Table] WHERE (pName LIKE " + pNameTemp + ")");
SqlCommand sqlCmd = new SqlCommand(query, myConnection);
txtSkill.Text = sqlCmd.ExecuteScalar().ToString();
myConnection.Close();
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
it seems to search the correct name but when it comes to updating the txtSkill, I get the exception 'invalid column name' pop up, are there any obvious reasons as to why this is happening that i'm missing? any advice would be appreciated
In fact, you are missing '' for the parameter of the query.
Try to use this query.
SqlCommand sqlCmd = new SqlCommand(#"SELECT sName from [dbo].[Table] WHERE pName LIKE '{pNameTemp}'", myConnection);
But I recommend you to use SqlParameter in C# to avoid SQL Injection
SqlCommand com = new SqlCommand("SELECT sName from [dbo].[Table] WHERE pName LIKE #field", myConnection);
myConnection.Parameters.AddWithValue("#field", pNameTemp);
But normally, when we use LIKE, we should put in % because it gives all results contains keyword. LIKE without % doesn't make sense. So :
SqlCommand com = new SqlCommand("SELECT sName from [dbo].[Table] WHERE pName LIKE #field", myConnection);
command.Parameters.AddWithValue("#field", "'%" + pNameTemp + "%'");
There are some options in the LIKE clause:
%: The percent sign represents zero, one, or multiple characters
_ The underscore represents a single character
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.
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 + "'"
I have in the DB Sid and password and it contain the Sid=senan and the password=pass1234
when I enter this details into my login screen always I get fail messagebox
SqlDataAdapter cmd = new SqlDataAdapter("select Count(*) from [user] where Sid=' " + textBox1.Text + " ' and password='" + textBox2.Text + "'", cnn);
DataTable dt = new DataTable();
cmd.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
MessageBox.Show("pass");
else
MessageBox.Show("fail");
The error arises from a simple typo. You have spaces added to the value passed for the Sid condition.
However your query should be rewritten in this way
string cmdText = "select Count(*) from [user] where Sid=#sid and password=#pwd";
SqlCommand cmd = new SqlCommand(cmdText, cnn)
cmd.Parameters.AddWithValue("#sid", textBox1.Text);
cmd.Parameters.AddWithValue("#pwd", textBox2.Text);
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count > 0)
MessageBox.Show("pass");
else
MessageBox.Show("fail");
This approach uses a parameterized query to avoid Sql Injection, and uses directly an SqlCommand without building the SqlDataAdapter and a DataTable. The SqlCommand.ExecuteScalar is the correct method to use when you need to retrieve simply the first column of a single row or call a scalar T-SQL function like COUNT()
As a side note, keep in mind that storing passwords in clear text in your database is a big security concern. Whoever has access to the database will be able to read the passwords of every user. The passwords should be stored as a computed hash and checked repeating the hashing algorithm on the user entered data.