Another shorten SQL string? c# - c#

Some may already be noticing this and I would like to confirm it, I am really inexperienced with complex SQL strings. I only know simple SELECT , INSERT , UPDATE and DELETE statements. And to achieve my purpose I often use 2 SELECT statements, like this one :
con.Open();
string cmdstr = "SELECT UNIQUE FROM recipeList WHERE `stock_ID` = '" + stockIDTxtbox.Text + "'";
cmd = new MySqlCommand(cmdstr, con);
dr = cmd.ExecuteReader();
string menuID = "";
while (dr.Read())
{
menuID = (dr["menu_ID"].ToString());
}
dr.Close();
con.Close();
con.Open();
string cmdstr = "SELECT `menu_name` FROM recipedb WHERE `menu_ID` = '" + menuID + "'";
cmd = new MySqlCommand(cmdstr, con);
dr = cmd.ExecuteReader();
string menuName = "";
while (dr.Read())
{
menuName = (dr["menu_name"].ToString());
this.listView1.Items.Add(new ListViewItem(new string[]{ menuName }))
}
dr.Close();
con.Close();
Any ideas how to shorten this? o.O

You may write an SQL as:
string queryString = "SELECT r2.menu_name "+
"FROM recipelist rl "+
"INNER JOIN recipedb r2 "+
"ON rl.menu_ID = r2.menu_ID "+
"WHERE r1.stock_ID = '" + stockIDTxtbox.Text + "'";

Haven't written SQL in a while but it should be a join, so something like the following:
select rdb.menu_name
from recipedb rdb,
recipelist rl
where rl.menu_ID = rdb.menu_ID and
rl.stock_ID = * insert your stockIDTxtbox.Text in here without the stars *

Here is a short one:
con.Open();
string cmdstr = "SELECT menu_name FROM recipedb WHERE menu_ID in (SELECT UNIQUE menu_id from recipeList WHERE stock_ID = '" + stockIDTxtbox.Text + "')";
cmd = new MySqlCommand(cmdstr, con);
dr = cmd.ExecuteReader();
string menuName = "";
while (dr.Read())
{
menuName = (dr["menu_name"].ToString());
this.listView1.Items.Add(new ListViewItem(new string[]{ menuName }))
}
dr.Close();
con.Close();

Related

Retreive last record inserted

I want to retrieve the last record of data inserted. I researched and learn't I must use SELECT LAST_INSERT_ID(). I have tried and not working. So I have provided my code below
//Inserting into Student Table
string query = "INSERT INTO student(name) Values('" + txtboxname.Text + "' )";
// query= "SELECT LAST_INSERT_ID()";
// query += " SELECT SCOPE_IDENTITY()";
//Inserting into course table
string query1 = "INSERT INTO course(title) Values('" + txttitle.Text + "')";
// query1 = " SELECT LAST_INSERT_ID()";
//Execute Insert Statement queries
MySqlCommand command = new MySqlCommand(query, con);
command.ExecuteNonQuery();
command = new MySqlCommand(query1, con);
command.ExecuteNonQuery();
//Close and dispose off connections
command.Dispose();
con.Close();
//Preview page
string query1 = "SELECT (name) FROM student WHERE ID = id";
string query2 = "SELECT (title) FROM course WHERE ID = id";
MySqlCommand command = new MySqlCommand(query1, con);
lblname.Text = command.ExecuteScalar().ToString();
command = new MySqlCommand(query2, con);
lbltitle.Text = command.ExecuteScalar().ToString();
con.Close();
if you have set the table id to auto-increment then find the max id from the table that will be your last insert as per my knowledge if it works.
In your Code change as follows,
line no: 3 query="set #std_id=last_insert_id();"
line no: 7 query1="set #title_id=last_insert_id();"
Preview Page:
string query1 = "SELECT (name) FROM student WHERE ID = query";
string query2 = "SELECT (title) FROM course WHERE ID = query1";

How to search over whole cities in combobox

I inserted about 18 cities in government field and I can search over each city I want by ID, but now I want to search over all of the cities by ID when I do not select any thing in combobox.
string c = "%";
c = comboBox1.Text;
int a;
a = Convert.ToInt32(textBox1.Text);
a = int.Parse(textBox1.Text);
SqlCommand cmd = new SqlCommand("select * from Person where ( PER_ID = '" + a + "' and GOV_NAME_AR = '" + c + "') ", con);
cmd.CommandTimeout = 600;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows)
{
// MessageBox.Show("Successfully found Data");
// SqlDataReader DR = cmd.ExecuteReader();
BindingSource source = new BindingSource();
dataGridView1.DataSource = source;
}
else
{
MessageBox.Show("data not found");
}
con.Close();
You could change the statement in case of "nothing selected"
if (ComboBox.Text == string.Empty)
{
cmd.CommandText = "select * from Person where ( PER_ID = '" + a + "')";
}
Remarks:
use variable names like string sCity = "%"; instead of string c = "%";
use parameters for your sql statements where ( PER_ID = #Person) and cmd.Parameters.Add("#Person", SqlDbType.Int32).Value = int.Parse(textBox1.Text);
If I get you correctly, you don't want where clause on GOV_NAME_AR when combobox1 is not selected.
if( ComboBox.SelectedItem == null ) {
cmd.CommandText = "select * from Person where ( PER_ID = '" + a + "')";
}
You could do a check on the ComboBox.SelectedText like this:
if (comboBox1.SelectedText=="")
{
//SQL statement should not restrict on the c value
}
else
{
//Use your regular SQL query here.
}

How can I save a variable from a database and use it in C#?

I am changing a program and I need some help because I don't know C#. I change things with:
strSQL = "UPDATE materials SET ";
strSQL = strSQL + "Dscr = 'concrete', ";
strSQL = strSQL + "width=50 ";
strSQL = strSQL + " WHERE ID=385";
objCmd = new OleDbCommand(strSQL, db_def.conn);
objCmd.ExecuteNonQuery();
There is a case where I need to find an ID, store it and then use it again. So I use select
OleDbCommand cmd = new OleDbCommand("SELECT ID FROM materials WHERE Type=1", db_def.conn);
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
var result = reader.GetInt32(0);
}
strSQL = "UPDATE materials SET ";
strSQL = strSQL + "Dscr = 'concrete', ";
strSQL = strSQL + "width=50 ";
strSQL = strSQL + " WHERE ID=result";
objCmd = new OleDbCommand(strSQL, db_def.conn);
objCmd.ExecuteNonQuery();
But I get an error:
No value given for one or more required parameters.
you can try this and tell me if it works
OleDbCommand cmd = new OleDbCommand("SELECT ID FROM materials WHERE Type=1", db_def.conn);
OleDbDataReader reader = cmd.ExecuteReader();
int result=-1 ;
if (reader.HasRows)
{
reader.Read();
result = reader.GetInt32(0);
}
if (result != -1)
{
strSQL = "UPDATE materials SET ";
strSQL = strSQL + "Dscr = 'concrete', ";
strSQL = strSQL + "width=50 ";
strSQL = strSQL + " WHERE ID="+result;
objCmd = new OleDbCommand(strSQL, db_def.conn);
objCmd.ExecuteNonQuery();
}
Although your code that you're working on is less than desirable, I'll just provide the fix you require at this point:
Change your code to :
OleDbCommand cmd = new OleDbCommand("SELECT ID FROM materials WHERE Type=1", db_def.conn);
OleDbDataReader reader = cmd.ExecuteReader();
int result=0;
if (reader.HasRows)
{
reader.Read();
result = reader.GetInt32(0);
}
strSQL = "UPDATE materials SET ";
strSQL = strSQL + "Dscr = 'concrete', ";
strSQL = strSQL + "width=50 ";
strSQL = strSQL + " WHERE ID=" + result;
objCmd = new OleDbCommand(strSQL, db_def.conn);
objCmd.ExecuteNonQuery();
You need to provide the value of the result variable outside the SQL string - the database will not know the value of 'result' in its own context.
EDIT: the result variable was declared within the if statement, therefore not available further down for assigning.

Advance search using dropdown list C#

I an doing an advance search code .. I have 6 drop-down lists , the user can choose one or more value from one or all the drop downs or choose the "-" value which means no value selected .. My code is working and the result is the union of all the values .. how can I find only the intersect ?
I mean if I choose (Asia) from the first drop-down and (Arabic) from the second ,, my result is all the countries in Asia and all the countries that have Arabic language..
how can I have only the Asian countries that talks Arabic >> the intersect ?
if (!Class1.Search_Continent.Equals("-"))//DropDownList1.SelectedValue.ToString();
{
sunc.conn.Open();
SqlCommand cmd1 = new SqlCommand("Select Country_name FROM Country WHERE Continent_name='" + DropDownList1.SelectedValue + "'", sunc.conn);
SqlDataReader dr1;
dr1 = cmd1.ExecuteReader();
while (dr1.Read())
{DropDownList9.Items.Add(dr1["Country_name"].ToString());}
sunc.conn.Close();
if (!Class1.Search_Country.Equals("-"))//DropDownList2.SelectedValue.ToString();
{
RemoveDuplicateItems(DropDownList9);
sunc.conn.Open();
SqlCommand cmd2 = new SqlCommand("Select Country_name FROM Country WHERE Country_name='" + DropDownList2.SelectedValue + "'", sunc.conn);
SqlDataReader dr2;
dr2 = cmd2.ExecuteReader();
while (dr2.Read())
{DropDownList9.Items.Add(dr2["Country_name"].ToString());}
sunc.conn.Close();
if (!Class1.Search_City.Equals("-"))//DropDownList3.SelectedValue.ToString();
{
RemoveDuplicateItems(DropDownList9);
sunc.conn.Open();
SqlCommand cmd3 = new SqlCommand("Select Country_name FROM City WHERE City_name='" + DropDownList3.SelectedValue + "'", sunc.conn);
SqlDataReader dr3;
dr3 = cmd3.ExecuteReader();
while (dr3.Read())
{
DropDownList9.Items.Add(dr3["Country_name"].ToString());
}
//dr3.Close();
//conn3.Close();
sunc.conn.Close();
if (!Class1.Search_Religion.Equals("-"))//DropDownList4.SelectedValue.ToString();
{
RemoveDuplicateItems(DropDownList9);
//SqlConnection conn4 = new SqlConnection(#"Data Source=AK-PC\MSSQLSERVER1;Initial Catalog=DB;Integrated Security=True");
//conn4.Open();
sunc.conn.Open();
SqlCommand cmd4 = new SqlCommand("Select Country_name FROM Religion WHERE Religion_name='" + DropDownList4.SelectedValue + "'", sunc.conn);
SqlDataReader dr4;
dr4 = cmd4.ExecuteReader();
while (dr4.Read())
{
DropDownList9.Items.Add(dr4["Country_name"].ToString());
}
//dr4.Close();
//conn4.Close();
sunc.conn.Close();
if (!Class1.Search_Type.Equals("-"))//DropDownList5.SelectedValue.ToString();
{
RemoveDuplicateItems(DropDownList9);
//SqlConnection conn5 = new SqlConnection(#"Data Source=AK-PC\MSSQLSERVER1;Initial Catalog=DB;Integrated Security=True");
//conn5.Open();
sunc.conn.Open();
SqlCommand cmd5 = new SqlCommand("Select Country_name FROM Country WHERE Type_of_government='" + DropDownList5.SelectedValue + "'", sunc.conn);
SqlDataReader dr5;
dr5 = cmd5.ExecuteReader();
while (dr5.Read())
{
DropDownList9.Items.Add(dr5["Country_name"].ToString());
}
//dr5.Close();
//conn5.Close();
sunc.conn.Close();
if (!Class1.Search_Language.Equals("-"))//DropDownList6.SelectedValue.ToString();
{
RemoveDuplicateItems(DropDownList9);
//SqlConnection conn6 = new SqlConnection(#"Data Source=AK-PC\MSSQLSERVER1;Initial Catalog=DB;Integrated Security=True");
//conn6.Open();
sunc.conn.Open();
SqlCommand cmd6 = new SqlCommand("Select Country_name FROM Language WHERE Language_name='" + DropDownList6.SelectedValue + "'", sunc.conn);
SqlDataReader dr6;
dr6 = cmd6.ExecuteReader();
while (dr6.Read())
{
DropDownList9.Items.Add(dr6["Country_name"].ToString());
}
//dr6.Close();
//conn6.Close();
sunc.conn.Close();
if (DropDownList1.SelectedValue.Equals("-") && DropDownList2.SelectedValue.Equals("-") &&
DropDownList3.SelectedValue.Equals("-") && DropDownList4.SelectedValue.Equals("-") &&
DropDownList5.SelectedValue.Equals("-") && DropDownList6.SelectedValue.Equals("-"))
{
Button2.Enabled = false;
Label1.Text = "you have to choose from the dropdown list";
}
else if (DropDownList9.SelectedValue.Equals("-"))
{
Button2.Enabled = false;
Label1.Text = "No result ";
}
}
}
}
}
}
}
I would alter your code so that it creates one query based on the different options, then returns just the result of that query.
For example:
string query = "Select Country_name FROM Country WHERE Continent_name='" + DropDownList1.SelectedValue + "'";
if (!Class1.Search_Country.Equals("-"))
query+= " and Country_name='" + DropDownList2.SelectedValue + "'";
SqlCommand cmd1 = new SqlCommand(query, sunc.conn);
Generally you want to do this in a single query like:
SELECT Country_Name
FROM Country C
INNER JOIN City CTY on (CTY.Country_Name = C.Country_Name)
INNER JOIN Religion R on (R.Country_Name = C.Country_Name
WHERE ((#City ='') or (CTY.City_Name = #City))
AND ((#Religion ='') or (R.Religion_Name = #Religion))
AND ((#Government = '') or (C.Type_of_Government = #Government))
You would then pass #City, #Religion and #Government as parameters to the query. If any individual parameter is passed in then the WHERE clause would filter on it; or ignore if that parameter was blank.
You have to modify the query something like below.
SqlCommand cmd1 = new SqlCommand("Select Country_name FROM Country WHERE (Continent_name='" + DropDownList1.SelectedValue + "' or Continent_name=Continent_name) AND (Country_name='" + DropDownList2.SelectedValue + "' OR Country_name=Country_name) AND (City_name='" + DropDownList3.SelectedValue + "' OR City_name=City_name) AND (Religion_name='" + DropDownList4.SelectedValue + "' OR Religion_name=Religion_name) AND (Type_of_government='" + DropDownList5.SelectedValue + "' OR Type_of_government=Type_of_government) AND (Language_name='" + DropDownList6.SelectedValue + "' OR Language_name=Language_name)", sunc.conn);
Hope this Helps!!

Getting Data from Access into a text box in C# by clicking a button

I have a table in MS Access that contain: (FoodID, FoodName, Price).
In C# I have three text boxes (txtId, txtName, txtPrice) and a button (btnSearch).
My question is that, In C# I just type FoodID in (txtId) and then click on button Search It'll display FoodName and Price ( from table access) in txtName and txtPrice by itself. I got the source code from you but it error on (OleDbDataReader dr = cmd.ExecuteReader();) its message is "Data type mismatch in criteria expression" .
Please solve this problem for me. This is the whole source code that I got for you.
System.Data.OleDb.OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "your connection string";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + txtId + "' ";
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();//error this line!
while(dr.Read())
{
txtName.Text = dr["FoodName"].ToString();
txtPrice.Text = dr["Price"].ToString();
}
dr.Close();
conn.Close();
I assume FoodID is int. You should remove single quotes in this case
cmd.CommandText = "select FoodName, Price from tablename where FoodID = " + txtId;
Even better - use parameters:
using (var connection = new OleDbConnection("your connection string"))
using (var command = connection.CreateCommand())
{
command.CommandText = "select FoodName, Price from tablename where FoodID = #FoodID";
command.Parameters.AddWithValue("FoodID", int.Parse(txtId.Text));
connection.Open();
var reader = command.ExecuteReader();
while (reader.Read())
{
txtName.Text = reader["FoodName"].ToString();
txtPrice.Text = reader["Price"].ToString();
}
}
I think the FoodId is of Integer type in the database but over here in the query you have passed as string so convert the string to integer.
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + int.Parse(txtId.Text) + "' " ;
There seems to be no problem with this line of code :
OleDbDataReader dr = cmd.ExecuteReader();// correct way
I think the problem is in:
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + txtId + "' ";
You need to use the .Text Propertie of the Textbox
cmd.CommandText = "select FoodName, Price from tablename where FoodID = '" + txtId.Text + "' ";

Categories

Resources