Hello I want to delete a row from my table , I have 3 tables for Recipe , Ingredient and i'm using the 3rd table to combine the Recipe and Ingredient tables,
my question I can add a row but I don't know how to delete a row I really dont have an idea how to do it .
the code down plz help ^^"
private void btnAddToRecpie_Click(object sender, EventArgs e)
{
string query = "INSERT INTO RecpieIngredient VALUES (#RecpieId,#IngredientId)";
using (connection = new SqlConnection(connectionString))
using (SqlCommand cmnd = new SqlCommand(query, connection))
{
connection.Open();
cmnd.Parameters.AddWithValue("#RecpieId", lstRecpie.SelectedValue);
cmnd.Parameters.AddWithValue("#IngredientId",lstAllIngredient.SelectedValue);
cmnd.ExecuteScalar();
}
PopulateRecpie();
}
private void butToDelete_Click(object sender, EventArgs e)
{
string query = "DELETE FROM RecpieIngredient WHERE (#RecpieId , #IngredientId)=#RecpieId , #IngredientId ";
// a.Name FROM Ingredient a INNER JOIN RecpieIngredient x ON a.Id = x.IngredientId INNER JOIN Recpie m ON m.Id=x.RecpieId WHERE m.Id=" + index;
using (connection = new SqlConnection(connectionString))
using (SqlCommand cmnd = new SqlCommand(query, connection))
{
connection.Open();
cmnd.Parameters.AddWithValue("#RecpieId", lstRecpie.SelectedValue);
cmnd.Parameters.AddWithValue("#IngredientId", lstAllIngredient.SelectedValue);
cmnd.ExecuteNonQuery();
}
PopulateRecpie();
}
This:
INSERT INTO RecpieIngredient VALUES (#RecpieId,#IngredientId)
Is really shorthand for:
INSERT INTO RecpieIngredient (RecpieId, IngredientId) VALUES (#RecpieId, #IngredientId)
The DELETE statement does not have such a shorthand variant, and requires you to mention the column names explicitly:
DELETE FROM RecpieIngredient WHERE RecpieId = #RecpieId AND IngredientId = #IngredientId
You came pretty close in fixing the problem yourself though :)
You delete statement is wrong. It should be
string query = "DELETE FROM RecpieIngredient
WHERE RecpieId = #RecpieId
AND IngredientId = #IngredientId";
Related
I am trying to update a databse entry under a specific id in my table when the users enter their ID number in a textBox.
At the moment it updates but updates all entries in my table except the entry containing the users ID number.
This is the code I am currently using:
private void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=DEVELOPMENT\ACCESSCONTROL;Initial Catalog=ACCESSCONTROL;User ID=sa;Password=P#55w0rd123");
SqlCommand check_User_Name = new SqlCommand("SELECT Id FROM NewVisitor WHERE (IDNumber = #IDNumber)", con);
check_User_Name.Parameters.AddWithValue("#IDNumber", idNumber_TxtBox.Text);
con.Open();
int UserExist = (int)check_User_Name.ExecuteScalar();
if (UserExist > 0)
{
var connetionString = #"Data Source=DEVELOPMENT\ACCESSCONTROL;Initial Catalog=ACCESSCONTROL;User ID=sa;Password=P#55w0rd123";
var sql = "UPDATE NewVisitor SET PersonVisit = #PersonVisit, PurposeVisit = #PurposeVisit, Duration = #Duration, Disclaimer = #Disclaimer";
try
{
using (var connection = new SqlConnection(connetionString))
{
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#PersonVisit", SqlDbType.NVarChar).Value = personVisiting_TxtBox.Text;
command.Parameters.Add("#PurposeVisit", SqlDbType.NVarChar).Value = purposeOfVisit_CMBox.SelectedItem;
command.Parameters.Add("#Duration", SqlDbType.Date).Value = duration_dateTimePicker1.Value.Date;
command.Parameters.Add("#Disclaimer", SqlDbType.NVarChar).Value = disclaimer_CHKBox.Checked;
connection.Open();
command.ExecuteNonQuery();
}
}
}
The whole table has many more fields but would like to just update the above fields within that specific ID.
Thanks
You forgot the WHERE clause on the UPDATE statement, telling it specifically which records to update. It sounds like you just want to add the exact same WHERE clause that you have on your SELECT:
var sql = "UPDATE NewVisitor SET PersonVisit = #PersonVisit, PurposeVisit = #PurposeVisit, Duration = #Duration, Disclaimer = #Disclaimer WHERE (IDNumber = #IDNumber)";
And don't forget to add the paramter for it:
command.Parameters.Add("#IDNumber", SqlDbType.Int).Value = idNumber_TxtBox.Text;
You may need to convert the input value to an integer first, I'm not 100% certain (it's been a while since I've had to use ADO.NET directly). Something like this:
if (!int.TryParse(idNumber_TxtBox.Text, out var idNumber))
{
// input wasn't an integer, handle the error
}
command.Parameters.Add("#IDNumber", SqlDbType.Int).Value = idNumber;
im writing a library database program. It can insert books, but I have a problem in making a reference between book and a person which rents it. I can't get a last inserted id from a rents table to put it to the compilation table to assign book to a person who rents it. I've tried SCOPE_IDENTITY() but it doesn't works for me. Here's the code:
private void addRentButton_Click(object sender, EventArgs e) {
elibrary f1 = new elibrary();
string query = "INSERT INTO rents VALUES (#renterName, #rentStartDate, #rentEndDate)";
using(f1.Connection = new SqlConnection(f1.connectionString))
using(SqlCommand command = new SqlCommand(query, f1.Connection)) {
f1.Connection.Open();
command.Parameters.AddWithValue("#renterName", rentNameBox.Text);
command.Parameters.AddWithValue("#rentStartDate", DateTime.Now);
command.Parameters.AddWithValue("#rentEndDate", rentEndDatePicker.Value);
command.ExecuteScalar();
}
rentEndDatePicker.Value = DateTime.Now;
string Compilationquery =" INSERT INTO compilation VALUES (#bookId, SELECT SCOPE_IDENTITY())";
using(f1.Connection = new SqlConnection(f1.connectionString))
using(SqlCommand command = new SqlCommand(Compilationquery, f1.Connection)) {
f1.Connection.Open();
command.Parameters.AddWithValue("#bookId", f1.listBook.SelectedValue);
command.ExecuteScalar();
Actually, you are not retrieving the last inserted ID value from the first query, since the SCOPE_IDENTITY() is wrongly placed and you are not assigning the ExecuteScalar() return value anywhere:
String query = "INSERT INTO rents VALUES (#renterName, #rentStartDate, #rentEndDate); SELECT CONVERT(INT, SCOPE_IDENTITY())"; // "SELECT CAST(SCOPE_IDENTITY() AS INT)" can also be an option
Int32 lastId = 0;
using (f1.Connection = new SqlConnection(f1.connectionString))
using (SqlCommand command = new SqlCommand(query, f1.Connection))
{
f1.Connection.Open();
command.Parameters.AddWithValue("#renterName", rentNameBox.Text);
command.Parameters.AddWithValue("#rentStartDate", DateTime.Now);
command.Parameters.AddWithValue("#rentEndDate", rentEndDatePicker.Value);
lastId = (Int32)command.ExecuteScalar();
}
Once this is done, you can proceed with the second query as follows:
String compilationQuery = "INSERT INTO compilation VALUES (#bookId, #rentId)";
using (f1.Connection = new SqlConnection(f1.connectionString))
using (SqlCommand command = new SqlCommand(compilationQuery, f1.Connection))
{
f1.Connection.Open();
command.Parameters.AddWithValue("#bookId", f1.listBook.SelectedValue);
command.Parameters.AddWithValue("#rentId", lastId);
// ...
You have disposed the command so SCOPE_IDENTITY() is gone. There is no reason to dispose of the commmand twice.
using(SqlCommand command = new SqlCommand(query, f1.Connection))
{
f1.Connection.Open();
command.Parameters.AddWithValue("#renterName", rentNameBox.Text);
command.Parameters.AddWithValue("#rentStartDate", DateTime.Now);
command.Parameters.AddWithValue("#rentEndDate", rentEndDatePicker.Value);
command.ExecuteScalar();
int id = (Int32)command.ExecuteScalar();
command.Parameters.Clear();
Compilationquery = "INSERT INTO compilation VALUES (#bookId, #id)";
command.CommandText = Compilationquery;
command.Parameters.AddWithValue("#bookId", f1.listBook.SelectedValue);
command.Parameters.AddWithValue("#id", id);
command.ExecuteScalar();
}
Question says it all really, I just want the all column names from a table, I'm looking for as basic way to do this as possible.
If you run the following SQL you'll get an empty rowset. From which you can interpret the column names by using a SqlCommand and DataReader.
using (var conn = new SqlConnection("your_conn_string"))
{
var command = new SqlCommand("select * from [dbo].[tableName] where 1 = 2");
conn.Open();
using(var dr = command.ExecuteReader())
{
var columns = new List<string>();
for(int i=0;i<reader.FieldCount;i++)
{
columns.Add(reader.GetName(i));
}
}
}
That depends entirely on the database. Almost all databases have some sort of metadata about the database. Most implement some version of the information_schema method.
For instance, a common way to get information about columns is:
select column_name
from information_schema.columns
where table_name = ? and table_schema = ?;
? are place-holders for the table name and schema.
This should do what you want.
public string[] getColumnsName()
{
List<string> listacolumnas=new List<string>();
using (SqlConnection connection = new SqlConnection(Connection))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "select c.name from sys.columns c inner join sys.tables t on t.object_id = c.object_id and t.name = 'Usuarios' and t.type = 'U'";
connection.Open();
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
listacolumnas.Add(reader.GetString(0));
}
}
}
return listacolumnas.ToArray();
}
Get column name from SQL Server
Here is my code
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (!string.IsNullOrWhiteSpace(Request.QueryString["id"]))
{
string clientId = Context.User.Identity.GetUserId();
if (clientId != null)
{
int id = Convert.ToInt32(Request.QueryString["id"]);
customize1 customize = new customize1
{
client_id = clientId,
product_id = id,
paper_type = Labelpt.Text,
corner = Labelpc.Text,
shipping_type = Labelsp.Text,
text = TextBox3.Text,
amount = Convert.ToInt32(lbResult.Text)
};
customizeModel model = new customizeModel();
Label9.Text = model.Insertcustomize(customize);
con.Open();
SqlCommand cmd2 = con.CreateCommand();
cmd2.CommandType = CommandType.Text;
cmd2.CommandText = "select top 1 * from customize1 where client_id='"+clientId+"' order by Id desc ";
cmd2.ExecuteNonQuery();
DataTable dt2 = new DataTable();
SqlDataAdapter da2 = new SqlDataAdapter(cmd2);
da2.Fill(dt2);
foreach (DataRow dr2 in dt2.Rows)
{
customizeid = dr2["Id"].ToString();
}
con.Close();
}
}
}
I need the last row id but my query does not generate any value.I also check my query in SSMS and query is working fine but in asp it is not generating any data and for inserting record i used the concept of class and entity relationship.
Any Solution.
Brother there are two ways:
One is when you insert your row place after the Insert query this:
SELECT SCOPE_IDENTITY()
For example:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
SELECT SCOPE_IDENTITY()
It gives the inserted ID back.
The second way is this query;
SELECT id FROM table ORDER BY id DESC LIMIT 1
If you keep struggling with problems be open to ask more.
I want to add ingredient into recipe. I have tried many things in order to do that but it didn't work sadly.
Idea: http://prntscr.com/dw8lom
My database tables: http://prntscr.com/dw8ms7
My code I've used to add recipe:
private void VoegReceptenToe()
{
string query = "INSERT INTO Recipe VALUES (#RecipeName, 30, 'goed mixen')";
using (connection = new SqlConnection(connectionstring))
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("#RecipeName", txtRecipeName.Text);
command.ExecuteScalar();
PopulateRecipes();
}
}
Populate recipe:
{
string query = "SELECT a.Name FROM Ingredient a " +
"INNER JOIN Recipe_Ingredient b ON a.Id = b.IngredientId " +
"WHERE b.RecipeId = #RecipeId";
// de connectionstring hoef je niet te openen en te sluiten als,
// je een using statement gebruikt, dat doet hij vanzelf.
using (connection = new SqlConnection(connectionstring))
using (SqlCommand command = new SqlCommand(query,connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
command.Parameters.AddWithValue("#RecipeId", lstRecipe.SelectedValue);
DataTable ingredientTable = new DataTable();
adapter.Fill(ingredientTable);
//Dit displayt de listbox.
lstIngredient.DisplayMember = "Name";
lstIngredient.ValueMember = "id";
lstIngredient.DataSource = ingredientTable;
}
}
You are opening a new connection to the database before closing the existing one.
What happens in your code is that when execution enters method VoegReceptenToe it opens a new connection to the database to insert some data. However, before closing that connection you're calling PopulateRecipes method which opens a new connection to the database.
What you have to do is to split insert and query operations and you can do this by moving the method VoegReceptenToe after the using statement:
private void VoegReceptenToe()
{
string query = "INSERT INTO Recipe VALUES (#RecipeName, 30, 'goed mixen')";
using (connection = new SqlConnection(connectionstring))
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("#RecipeName", txtRecipeName.Text);
command.ExecuteScalar();
}
PopulateRecipes();
}
As long as you ensure that Recipe & Ingredient names are unique in their tables (maybe using a unique index) & you have made sure the RecipeName & IngredientName exist in the tables (e.g. by only selecting from your listboxes) then the following query may do what you want :
INSERT INTO Recipe_Ingredient (RecipeID, IngredientID)
VALUES (
SELECT ID FROM Recipe Where Name = #RecipeName,
SELECT ID FROM Ingredient Where Name = #IngredientName)
This inserts an entry into the Recipe_Ingredient table, consisting of the ID of the RecipeName & the IngredientName as long as there exists a single entry for each.
You will need to add parameters for both the RecipeName & IngredientName to your command and run the ExecuteNonQuery method as the INSERT does not return a value.
Similarly to add a new RecipeName the ExecuteNonQuery method should be used to run this query :
INSERT INTO Recipe (Name, PrepTime, Instructions) VALUES (#RecipeName, 30, 'goed mixen')
and for a new Ingredient
INSERT INTO Ingredient (Name) VALUES (#Ingredient)
Also take note of RePierre's reordering of your code to ensure connections are not prematurely closed.