SQL Query Error in C# - c#

I am new to SQL Queries, I want to load "PSX LAGA" Value from SettlementTypeSetup (Table) where Settlement Type is equals to Regular/BO and Sale / Purchase is equals to "Purchase";
below is my code and this is my table
private void Load_Settlement_Type()
{
SqlCeConnection conn = null;
SqlCeCommand cmd = null;
SqlCeDataReader rdr = null;
try
{
conn =
new SqlCeConnection(
#"Data Source=|DataDirectory|\Database.sdf;Persist Security Info=False");
conn.Open();
cmd = new SqlCeCommand("SELECT PSXLaga FROM SettlementTypeSetup where SettlementType=BO/REGULAR;" , conn);
rdr = cmd.ExecuteReader();
if (rdr == null)
{
MessageBox.Show("Reader is null");
}
else
{
while (rdr.Read())
{
PSXLAGATEXT = rdr["PSXLaga"].ToString();
}
rdr.Close();
cmd.Dispose();
}
}
finally
{
conn.Close();
PSXLagaTextBox.Text = PSXLAGATEXT;
}
}
****It gives me error: Column Name: BO/REGULAR not found, whereas BO/REGULAR is not a column name, BO/REGULAR is a value of a SettlementType (Column), The condition should be as follows.**
Give me PSX Laga Value where SettlementType(Column) value is
BO/REGULAR and Sale/Purchase(Column) is Purchase.
**

You need write your value in '' because it is a string. Other way is to do it using parameters.
cmd = new SqlCeCommand("SELECT PSXLaga FROM SettlementTypeSetup where SettlementType=#Type" , conn);
cmd.Parameters.AddWithValue("#Type", "BO/REGULAR");

This query means you want to retrieve PSXLaga from your SettlementTypeSetup table, where SettlementType equals to a given value. In your case this is BO/REGULAR. If your SettlementType is a string, you'll have to put quotes around your value like this: 'BO/REGULAR'
So your correct query would look like this:
"SELECT PSXLaga FROM SettlementTypeSetup WHERE SettlementType = 'BO/REGULAR';"
Edit: I see you also wanted to check if sale/purchase is equals to "Purchase". You can do this by adding this to your query: (I'm unsure if it likes the / in your table name though..)
"AND Sale/Purchase = 'Purchase'"
I suggest using mybirthname's answer though. It's objectively better than the query above.
Second edit: You forgot the quotes again. Incorrect:
"SELECT PSXLaga FROM SettlementTypeSetup where SettlementType="+settlementTypeComboBox.Text + " AND [Sale/Purchase]='Purchase'"
Correct:
"SELECT PSXLaga FROM SettlementTypeSetup WHERE SettlementType = '" + settlementTypeComboBox.Text + "' AND [Sale/Purchase] = 'Purchase';"
But again, try to write your code like mybirthname has shown. I don't have a lot of experience with queries in C# code.

Related

C# : querying multiple columns into textboxes

This is my code, and I want to be able to search for a name, and then pull from the database the name, status, member_id into the textboxes in my form.
I got the name to work but how do I get the other columns and parse the output into the textboxes with the additional columns (member_id, status)? Let's say the other textboxes have the standard name such as textbox2, 3, 4...
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
string sql1 = null;
SqlDataReader dataReader;
connetionString = "Data Source=......"
sql = "SELECT NAME FROM Test_Employee WHERE Name LIKE '" + textBox1.Text.ToString() + "%'";
connection = new SqlConnection(connetionString);
{
connection.Open();
command = new SqlCommand(sql, connection);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
textBox9.Text = dataReader[0].ToString();
textBox7.Text = dataReader[0].ToString();
}
connection.Close();
}
Are the fields Member_Id and Status also in the table Test_Employee? You can add them in your Select statement and get them from your SqlReader, like the code below (assuming you are using c#7 and below). You may copy and paste this code.
var connectionString = "";
var sql = #"SELECT TOP 1 Name, Member_Id, Status
FROM Test_Employee
WHERE Name LIKE #name + '%'";
using (var connection = new SqlConnection(connectionString))
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("name", SqlDbType.NVarChar, 100).Value = textBox1.Text.ToString();
connection.Open();
var reader = command.ExecuteReader();
if (reader.Read())
{
textBox9.Text = dataReader["Name"].ToString();
textBox7.Text = dataReader["Name"].ToString();
textBox2.Text = dataReader["Member_Id"].ToString();
textBox3.Text = dataReader["Status"].ToString();
}
}
You will notice that instead of including the Textbox1.Text's value in your Select statement, it is added as a parameter in the SQLCommand object's Parameters. In this way your query is protected from SQL Injection. If you want to learn more, you can search c# sqlcommand parameters and why it is very important to build data access code this way.
Also, notice that I added Top 1 in your Select statement, and instead of using while, I am using if. This is because a textbox can only hold 1 result at a time in a comprehensible way. If you meant to show multiple results clearly, you need to use a different control other than a TextBox.
The using statements allow you to dispose the connection, so you don't have to call connection.Close().

C# Check if value is returned from database

SqlCeConnection sqlCnn = new SqlCeConnection("Data Source=" + Application.StartupPath + "\\mainDB.sdf");
SqlCeCommand sqlCmd = new SqlCeCommand("SELECT * FROM Accounts WHERE (username = #user AND password = #pass)", sqlCnn);
sqlCmd.Parameters.Add("#user", textBox1.Text);
sqlCmd.Parameters.Add("#pass", textBox2.Text);
sqlCnn.Open();
SqlCeDataReader reader = sqlCmd.ExecuteReader();
while (reader.Read())
{
// Some code ...
}
I have this code that reads some values from a database but I want to check if any value is returned from the database. I want to check if the username and password from the database is equal to textBox1 and textBox2 and if not, return a failure message.
Simply use the code like this:
if(reader.Read()){
//your code
}else {
//Show message notifying failure
}
//remember to close your reader
reader.Close(); //or use using statement for convenience.
However DataReader is used mainly for reading a set of data (just 1 record is a little overkill). You can try modifying your query a little such as by using If Exists(...)... and use ExecuteScalar() to get the return result. If it's not null then it's OK.
//the modified query
If Exists(SELECT * FROM Accounts WHERE (username = #user AND password = #pass))
SELECT 1 ELSE SELECT 0
var r = sqlCmd.ExecuteScalar();
if(r == null || (int)r == 0){
//failure...
}
I would "select count(*) from ..."
Then do ExecuteScalar() instead. This will return an int.
SqlCeConnection sqlCnn = new SqlCeConnection("Data Source=" + Application.StartupPath + "\\mainDB.sdf");
SqlCeCommand sqlCmd = new SqlCeCommand("SELECT count(*) FROM Accounts WHERE (username = #user AND password = #pass)", sqlCnn);
sqlCmd.Parameters.Add("#user", textBox1.Text);
sqlCmd.Parameters.Add("#pass", textBox2.Text);
sqlCnn.Open();
int recordCount = (int)sqlCmd.ExecuteScalar();
if (recordCount > 0)
{
//dostuff
}
Check if your Datateader has rows with reader.HasRows.
See this SO post How to check if SQLDataReader has no rows for more info.

loop through all values in sql table using sql data reader

I want to fetch all rows that related to the query below, my problem that only one row retrived not all rows , iam using asp.net with c# and ado.net and my code logic is
if (!IsPostBack)
{
string username = Session["username"].ToString();
con.Open();
string strqryScript = "select * from dbo.teachers where user_id = '" + username + "'";
SqlCommand cmd = new SqlCommand(strqryScript, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
string name = rdr["teach_id"].ToString();
rdr.Close();
string query = "select * from dbo.teacher_classes where teach_id = '" + name + "' ORDER BY class_id";
SqlCommand cmd2 = new SqlCommand(query, con);
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
SqlDataReader rdr2 = cmd2.ExecuteReader();
while (rdr2.Read())
{
classname.Text = rdr2["class_id"].ToString();
}
con.Close();
}
extra note that i can use gridview to bind data but i want to fill my table with custom information from many tables , so i want to use an html table and fill it with my custom data. any help please! and thanks ..
While looping on the second reader, you write the value extracted from the reader on the Text property of the classname label. This will overwrite the previous text and leave you with the name of the last teacher retrieved. You need to add to the previous text or use a List.
classname.Text += rdr2["class_id"].ToString();
Said that, let me point you to a big problem in your code. String concatenation is really bad when you build sql commands. It gives you back syntax errors (if your input text contains single quotes) or Sql Injection as explained here
You should use parameterized queries like this (just for your first command)
string strqryScript = "select * from dbo.teachers where user_id = #id";
SqlCommand cmd = new SqlCommand(strqryScript, con);
cmd.Parameters.AddWitValue("#id", username);
....
This is the issue you need to fix:
classname.Text = rdr2["class_id"].ToString(); <== always setting the same text!!
You need to make sure, you fill a list, a dataset or whatever, when reading the data!

How to make a filtration by a parameter in CommandText in C#?

I would like to fill a ComboBox but I want to sort data by one parameter called “id_group”.
I wrote a code but it does not work.
In this line happens an exception which says “incorrect syntax” :
SqlDataReader sd = sc.ExecuteReader();
This is all my code:
int id_group=5;
SqlConnection conn = new SqlConnection();
SqlCommand sc = conn.CreateCommand();
sc.CommandText = "SELECT STUDENT FROM FACULTY WHERE ID_GROUP '" + id_group + "'";
conn.Open();
SqlDataReader sd = sc.ExecuteReader(); //this happens exception - "incorrect syntax"
while (sd.Read())
{
string graduate = (string)sd["STUDENT"];
Student_comboBox.Items.Add(graduate);
}
conn.Close();
How to make it work?
Is there other ways to filter data by a parameter?
actually you are missing = on your query, so this should looked like this,
sc.CommandText = "SELECT STUDENT FROM FACULTY WHERE ID_GROUP = '" +
id_group + "'";
but please do parameterize it to avoid SQL Injection
sc.CommandText = "SELECT STUDENT FROM FACULTY WHERE ID_GROUP = #groupID";
sc.Parameters.AddWithValue("#groupID", id_group);
SOURCE
AddWithValue
Add (recommended to use)

Dynamically passing a value inside a query?

I have two columns syntax and query in my table Table1. Syntax contains data called po and a query called select * from po_pomas_pur_order_hdr where pomas_pono =. I got this query value by using
SqlDataAdapter da = new SqlDataAdapter("select query from Table1 where syntax = '" + textBox1.Text + "'", conn);
And my problem is that I need to dynamically pass another value inside the query which I retrived using dataadapter like this:
SqlDataAdapter da1 = new SqlDataAdapter(da.tostring() +"'"+ textBox1.Text +"'", conn)
The resulting query should be like this:
select * from po_pomas_pur_order_hdr where pomas_pono = '2PO/000002/09-10'
But it is not possible. How to get a query like this? Any suggestion?
SqlDataAdapter is used to fill datasets and datatables. You cannot obtain the result of a query with ToString(). I think you want to use SqlCommand to execute your first query to retrieve the actual query to run from the database like this:
string query = null;
using (var command = new SqlCommand("select query from Table1 where syntax = #Syntax", conn))
{
command.Parameters.AddWithValue("#Syntax", textBox1.Text);
query = command.ExecuteScalar(); // this assumes only one query result is returned
}
Then you can use the data adapter to fill it:
SqlDataAdapter da1 = new SqlDataAdapter(query +"'"+ textBox1.Text +"'", conn);
Although I would suggest to use parameters for that as well.
in this way is more safe: dotnetperls
He check the "'" and the "\", check the type of the fields etc...
Code from the example above (is the same for insert delete and update):
using (SqlCommand command = new SqlCommand("SELECT * FROM Dogs1 WHERE Name LIKE #Name", connection))
{
//
// Add new SqlParameter to the command.
//
command.Parameters.Add(new SqlParameter("Name", dogName));
//
// Read in the SELECT results.
//
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
int weight = reader.GetInt32(0);
string name = reader.GetString(1);
string breed = reader.GetString(2);
Console.WriteLine("Weight = {0}, Name = {1}, Breed = {2}", weight, name, breed);
}
}
I suggest you to use SqlParameters. Here is example how to use DataAdapter and parameters.
Provided that you have a DataSet you intend to fill using the adapter and that you adjust the queries to use parameters in order to avoid sql injection you should be able to use something like this:
string query;
using(var sqlCommand = new SqlCommand(
"select query from Table1 where syntax=#syntax", conn))
{
sqlCommand.Parameters.AddWithValue("syntax", textBox1.Text);
query = (string)sqlCommand.ExecuteScalar();
}
using(var dataAdapter = new SqlDataAdapter())
using(var dataCommand = new SqlCommand(query, conn))
{
dataCommand.Parameters.AddWithValue("parameter", poNumber);
dataAdapter.SelectCommand = dataCommand;
dataAdapter.Fill(myDataSet);
}

Categories