Sql to select the prerequisite of a certain course - c#

I have a table that has courses details as follows:
And, in the Windows, form I placed a textBox and a button, when a student writes the name of the course to see the prerequisite requirement of that course as follows:
So I tried using the following code:
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select Name from Courses where (Name = '" + textBox2.Text + "') and Preq = Code";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView3.DataSource = dt;
conn.Close();
textBox2.Text = "";
However, the code gives me the name column without any data as follows:
Also, is there a way to show a message when the course does not have any requirement such as " this course has no prerequisite requirement " something like that?

your query is wrong , the below query returns the list of courses that are requirement for the given course name :
select Name from Courses
where code IN ( select PREQ from Courses where
Name = '" + textBox2.Text + "')
also It would be easier to handle showing a message in your c# code to show if there is no preq.you can checking if dt is null or not .

Related

How to make insert operation using MySqlDataAdapter in ASP.NET

I am able to perform insert using the code which I've made comments here. How to achieve the same using MySqlDataAdapter ? The code I've written isn't working.
string sid, sname;
sid = Request.QueryString["StudentId"].ToString();
sname = Request.QueryString["StudentName"].ToString();
MySqlDataAdapter da = new MySqlDataAdapter("insert into tblStudent (StudentId, StudentName) values ('" + sid.ToString() + "', '" + sname.ToString() + "')", con);
// con.Open();
// MySqlCommand cmd = con.CreateCommand();
// cmd.CommandType = CommandType.Text;
// cmd.CommandText = "insert into tblStudent (StudentId, StudentName) values('" + sid.ToString() + "', '" + sname.ToString() + "')";
// cmd.ExecuteNonQuery();
// con.Close();
Help with suggestions.
To insert a single record you could simply use the MySqlCommand instead of a MySqlDataAdapter. MySqlDataAdapter has many functionality and allows you to execute Insert, Update and Delete actions on your data but you first need to reach the server to fill a DataTable, then add a new record to the datatable and finally call Update. Not worth the effort if you just need to insert a single record
However if you really want to try to use an DataAdapter then you need this code
string sid, sname;
sid = Request.QueryString["StudentId"].ToString();
sname = Request.QueryString["StudentName"].ToString();
string selectText = "SELECT studentID, StudentName FROM tblStudent WHERE 1=0";
using(MySqlDataAdapter da = new MySqlDataAdapter(selectText, con))
{
MySqlCommandBuilder bd = new MySqlCommandBuilder(da);
DataTable dt = new DataTable();
da.Fill(dt);
// This is important, because Update will work only on rows
// present in the DataTable whose RowState is Added, Modified or Deleted
dt.Rows.Add(sid, sname);
da.Update(dt);
}

How can i get the value of column field base on another column field

Im using Visual Studio C# and using Access as my database. I have two columns, ItemCode and ProductName. I want to auto input of the productname on its textbox whenever its itemcode was selected. how can I do this?
some codes:
try
{
con.Open();
OleDbCommand command = new OleDbCommand(#"Select * from TblInventory where ItemCode='" + txtItem.Text + "'");
command.Connection = con;
command.Parameters.AddWithValue("itemcode", txtItem.Text);
OleDbDataReader reader = command.ExecuteReader();
if (reader.Read())//Update Item Code is already exist
{
.........
Feel free to edit my question and please be kind. thank you guys
Try this .
text_box.Text=reader["ProductName"].ToString();
You are filtering the rows by specifying the ItemCode in the Where clause, So The reader will contains the corresponding row/s that matches the specified code. What you need to do is Access the required column value by specifying the name as like the above snippet.
For extracting data from database, I prefer that use OleDbDataAdapter.
You can simply use:
string command = #"Select * from TblInventory where ItemCode='" + txtItem.Text + "'";
OleDbDataAdapter da = new OleDbDataAdapter(command, con);
DataTable dt = new DataTable();
da.Fill(dt);
Now, use dt :
if (dt.Rows.Count == 0)
//Error Message
else
cmbTreatyTitle.Text = dt.Rows[0]["ProductName"].ToString();
I hope this is helpful.

Searching using like

When I'm searching my datagrid, it should be always the first word to type. If i type the next word or consecutive letter it contains, it doesn't show.
Example:
I'm going to search Welcome Back. If i type "Elcome" or "back", it doesn't show.
Here is my code...
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * From books where Author like ('" + textBox1.Text + "%')";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
It is because you are telling the database to select rows that starts with textBox1.Text followed by anything else (%) you should change it to
"Select * From books where Author like ('%" + textBox1.Text + "%')";
this will find all books that their authors have textBox1.Text somewhere in their value.
In like command % can be replaced by zero or more character.
Also try using parameterized queries, your code is vulnerable to SQL injection.

C# App SQL Query

Okay basically I have a SQL Server database that has details in it.
Column names: Student_Id, Student_name, Unit_number, Unit_grade
I would like to query this database using two textboxes where you enter the id and unit_number and it will return the results in a message box when a button is clicked.
Where the question marks in the code are is where I am unsure of how to display a message box with the result. Unless this is completely the wrong way of doing things, I am only starting out with SQL in C#
I shouldn't be prone to SQL Injection using parameters as far as I know?
try
{
string str = "SELECT * FROM Students WHERE (Student_Id, Unit_number LIKE '%' + #search + '%')";
SqlCommand command = new SqlCommand(str, connect);
command.Parameters.Add("#search", SqlDbType.NVarChar).Value = textBox1.Text;
command.Parameters.Add("#search", SqlDbType.NVarChar).Value = textBox2.Text;
connect.Open();
command.ExecuteNonQuery();
SqlDataAdapter dataAdapt = new SqlDataAdapter();
dataAdapt.SelectCommand = command;
DataSet dataSet = new DataSet();
dataAdapt.Fill(dataSet, "Student_Id, Unit_number");
//?
//?
connect.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Your SQL is wrong in that your WHERE clause is syntactically incorrect. You probably want something like:
string str = "SELECT * FROM Students WHERE Student_ID = #id AND " +
"Unit_number LIKE #search";
This assumes that Student_ID is a text type. The syntax would be slightly different if it was a number.
You are trying to add the same parameter to the query twice, which you won't want. Instead you'd want two parameters to match with the new SQL definition:
command.Parameters.Add("id", SqlDbType.NVarChar).Value =
textBox1.Text;
command.Parameters.Add("search", SqlDbType.NVarChar).Value =
"%" + textBox2.Text + "%";
Running ExecuteNonQuery on the SqlCommand object doesn't do much for you as it is a query and you're not asking for the result back.
If you're only expecting one table back from your query, you'd probably be better off with a DataTable rather than a DataSet (the DataSet can contain many tables which is overkill for what you need).
try
{
string str = "SELECT * FROM Students WHERE Student_Id = #id AND " +
"Unit_number LIKE #search";
connect.Open();
SqlCommand command = new SqlCommand(str, connect);
command.Parameters.Add("id", SqlDbType.NVarChar).Value =
textBox1.Text;
command.Parameters.Add("search", SqlDbType.NVarChar).Value =
"%" + textBox2.Text + "%";
SqlDataAdapter dataAdapt = new SqlDataAdapter();
dataAdapt.SelectCommand = command;
DataTable dataTable = new DataTable();
dataAdapt.Fill(dataTable);
// At this point you should have a DataTable with some results in it.
// This is not going to be the best way of displaying data,
// but it should show you _something_
// It just iterates through the rows showing the columns
// which you've shown as being in your data.
foreach (DataRow dr in dataTable.Rows)
{
MessageBox.Show(String.Format("{0} - {1} - {2} - {3}",
dr["Student_Id"], dr["Student_name"],
dr["Unit_number"], dr["Unit_grade"]));
}
connect.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
EDITED to change the parameter handling as it didn't quite do what was needed. The % symbols are not part of the parameter rather than the SQL string.

asp.net - searching for a data containing an apostrophe in the database

Good day! I am having a hard time fixing this problem. I've been searching the answer for this but seemed to be very very hard to look for the most fitting answer.
i use this query to search for a tenant's name based on what the user inputs in the txtSearchRP textbox, it works very well to data with no apostrophe in it, however when the user searches for a name containing ' , it does not function well.
example: user inputs MAX'S to search MAX'S RESTAURANT
SELECT * from tenant WHERE (name LIKE '%" + txtSearchRP.Text + "%')
Thanks for your help in advance!
edit for more information:
I am actually passing the query to sqlDataSource to bind the gridview automatically after the user click THE BUTTON.
SqlDataSource3.SelectCommand = SELECT * from tenant WHERE (name LIKE '%" + txtSearchRP.Text + "%')
Try this
conn = new
SqlConnection("ConnectionString");
conn.Open();
SqlCommand cmd = new SqlCommand(
"SELECT * from tenant WHERE (name LIKE #tenant)", conn);
SqlParameter param = new SqlParameter();
param.ParameterName = "#tenant";
param.Value = "%" + txtSearchRP.Text + "%"; // you can use any wildcard operator
cmd.Parameters.Add(param);
SqlDataReader reader = cmd.ExecuteReader();
In addition to the answers already given, in some applications, you might need to consider escaping wildcards such as % in the input string provided by the user.
For example, if the user enters "25%", then matching on "%25%%" will return values that contain "25", rather than restricting to values that contain "25%".
You can escape wildcards as follows (for SQL Server):
string value = ... value entered by user;
value = value.Replace("[", "[[]");
value = value.Replace("_", "[_]");
value = value.Replace("%", "[%]");
Better way create storedprocedure
SP :
Create proc sp_Search( #txtSearch nvarchar(150))
as begin
SELECT * from tenant WHERE name like #txtSearch+'%'
end
Code behind :
string txtSearch = txtSearchRP.Text;
SqlDataReader dr;
using (SqlConnection conn = new SqlConnection(cn.ConnectionString))
{
using (SqlCommand cmdd = new SqlCommand())
{
cmdd.CommandType = CommandType.StoredProcedure;
cmdd.CommandText = "sp_Search";
cmdd.Parameters.AddWithValue("#txtSearch", txtSearch);
cmdd.Connection = conn;
conn.Open();
dr = cmdd.ExecuteReader(CommandBehavior.CloseConnection);
if (dr.HasRows)
{
while (dr.Read())
{
var name = dr["name"].ToString();
var location = dr["location"].ToString();
}
} dr.Close();
conn.Close();
}
}
Updated:
Write a function which returns datatable so that we can bind it to our gridview control as i did in code below
public DataTable bindGridView()
{
string txtSearch = txtSearchRP.Text;
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(cn.ConnectionString))
{
SqlCommand cmdd = new SqlCommand();
cmdd.CommandType = CommandType.StoredProcedure;
cmdd.CommandText = "sp_Search";
cmdd.Parameters.AddWithValue("#txtSearch", txtSearch);
cmdd.Connection = con;
con.Open();
SqlDataAdapter dap = new SqlDataAdapter(cmdd);
DataSet ds = new DataSet();
dap.Fill(ds);
dt = ds.Tables[0];
con.Close();
}
return dt;
}
On Button click : Call bindGridView() function for binding Gridview control
GridView1.DataSource = bindGridView();
GridView1.DataBind();
thanks to all who shared their knowledge and effort, finally got the answer through the String replace method
HERE'S THE 3-LINED CODE
string value = txtSearchRP.Text;
value = value.Replace("'", "['']");
sqlDataSource3.SelectCommand = "SELECT * from tenant WHERE (name LIKE '%" + value.ToString() +"%')";
through the joined effort, answers you posted here, we solve the problem in the simplest form :)

Categories

Resources