How to use FK SQL in a relation M:1 - c#

i need to understand how to work with FK SQL,i'm really desperate. I've a FK between two tables. From a third table i select what item i want to Execute(those item's are local urls). I select them, i run them, i need to save in the third table(tabStoricoDetail) a code referred to the items started. STOP if i manage how to do that i can then try to pickup the first date of the first event and the last date of the last item. I thought that the FK that i've made was ok but it's not. PLEASE HELP PLEASE
//btnStart it allows to lunch the selected items
private void btnSTART_Click(object sender, RoutedEventArgs e)
{
ApplyExecuteResults(ExecuteResults());//non toccare
sqliteCon.Open();
if (sqliteCon.State == System.Data.ConnectionState.Open)
{
SqlCommand cmd1 = new SqlCommand("INSERT INTO tabStoricoDetail(NomeItem,ResItemDet)values('Prova','RProva')", sqliteCon);
/*cmd1.Parameters.AddWithValue("#DATESD", this.DPStart.Text);
cmd1.Parameters.AddWithValue("#DATEED", this.DPEnd.Text);*/
cmd1.ExecuteNonQuery();
cmd1.Parameters.Clear();
SqlCommand cmd2 = new SqlCommand("UPDATE tabStoreExec SET FK_TSD_id =(tabStoricoDetail.id)", sqliteCon);
cmd2.ExecuteNonQuery();
cmd2.Parameters.Clear();
MessageBox.Show("Dato Aggiunto");
}
sqliteCon.Close();
}

When inserting a row into tabStoricoDetail you will need to save the generated ID into a variable. Note the OUTPUT clause of the INSERT statement:
SqlCommand cmd1 = new SqlCommand("INSERT INTO tabStoricoDetail(NomeItem,ResItemDet) OUTPUT inserted.Id VALUES ('Prova','RProva')", sqliteCon);
/*cmd1.Parameters.AddWithValue("#DATESD", this.DPStart.Text);
cmd1.Parameters.AddWithValue("#DATEED", this.DPEnd.Text);*/
int generatedId = Convert.ToInt32(cmd1.ExecuteScalar());
cmd1.Parameters.Clear();
Then you just use this generatedId when updating tabStoreExec, although you probably want some kind of WHERE on that UPDATE, because right now you'll just update all the existing rows.
SqlCommand cmd2 = new SqlCommand("UPDATE tabStoreExec SET FK_TSD_id = #tsdId", sqliteCon);
cmd2.Parameters.AddWithValue("#tsdId", generatedId);
cmd2.ExecuteNonQuery();

Related

connection property not initialized. i am trying to insert data in two table

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["abc"].ConnectionString);
SqlCommand cmd;
cmd = new SqlCommand("insert into student (name,email,mobile,userid,pass) values('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"')", con);
cmd = new SqlCommand("insert into course (stid) select top (1) stid from student order by stid desc", con);
cmd = new SqlCommand("update course set coursename ='"+comboBox1.Text+"'where stid = top (1) stid from course order by stid desc",con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
i am trying to insert data in two table using a single form with primary and foreign key relation stid is primary key in table student and foreign key in course
Your queries should be like this
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["abc"].ConnectionString);
SqlCommand cmd;
con.Open();
cmd = new SqlCommand("insert into student (name,email,mobile,userid,pass) values('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"')", con);
cmd.ExecuteNonQuery();//Foreach query you need to execute this line
cmd = new SqlCommand("insert into course (stid) select top (1) stid from student order by stid desc", con);
cmd.ExecuteNonQuery();//Foreach query you need to execute this line
cmd = new SqlCommand("update course set coursename ='"+comboBox1.Text+"'where stid = top (1) stid from course order by stid desc",con);
cmd.ExecuteNonQuery();//Foreach query you need to execute this line
con.Close();
There are a couple of issues in your code:
Issue 1: The first two commands
cmd = new SqlCommand("insert into student (name,email,mobile,userid,pass) values('"+textBox1.Text+"','"+textBox2.Text+"','"+textBox3.Text+"','"+textBox4.Text+"','"+textBox5.Text+"')", con);
cmd = new SqlCommand("insert into course (stid) select top (1) stid from student order by stid desc", con);
are not being used. You need to use the ExecuteNonQuery to get them executed. At present only the third command will be executed.
The error which you are getting
connection property not initialized
is because you need to assign the connection to the SqlCommand.
Issue 2: Your code is open to SQL Injection. You need to use parameterized query to get rid of that.(It is highly recommended.)
Issue 3: Try to use using statement to deal with SqlConnection as that would automatically close your connection once you are done with your execution.

How can I delete a single entry from a table

I have a listbox with usernames, and a remove button I want the selected a user (with all entered data associated with that user) to be deleted when the remove button is clicked.
My code
SqlConnection con = new SqlConnection("Data Source=JAMES-PC\\SQLEXPRESS;Initial Catalog=staff;Integrated Security=True");
con.Open();
string sql = #"DELETE FROM staff1;";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
this code deletes the whole table.
How can I just delete the selected user?
You need a WHERE clause to select the required record. You have to get the username of the selected user to be deleted and pass it to #UserName parameter.
var userName = (listBox.SelectedItem as DataRowView)["UserName"].ToString();
string sql = #"DELETE FROM staff1 WHERE Username = #UserName;";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#UserName",useName);
cmd.ExecuteNonQuery();
con.Close();
See this thread on how to use parameters in the SQL.
When you execute a delete query, in order to delete only 1 row from the table you need to add a WHERE clause.
Based on the comments the workflow should be something like: you click on a delete button, you send the name of the staff you want to delete to the command, which looks like:
string sql = #"DELETE FROM staff1 where Name=#Name;";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#Name","NameReceivedFromList");
cmd.ExecuteNonQuery();
con.Close();
When you are deleting you should remember to add a Where clause, it is actually very powerfull here is some examples that will get you started
The following query will delete only one element
DELETE FROM Table WHERE Table.PrimaryField = Value
The following query will delete all items that matches
DELETE FROM Table WHERE Table.Field = Value
You can also have a join in your delete statement for more complex delete queries
DELETE A FROM Table A
INNER JOIN TableB B ON A.Key = B.Key
WHERE B.PrimaryField = Value

Updated MS Access DB not working without any error

i create a program which load the data to listbox from ms-access, and create some action like add, update and delete the item..i got the item inserted and deleted properly. but i do not know what should i do to make this update working because the update query just won't fire up when the button is clicked(the item not getting updated on database), just to let ya know i got the messagebox.show below this code working like it should be.
OleDbCommand cmd = new OleDbCommand("UPDATE Item SET ITEM = #ITEM, ITEM_DESC = #ITEM_DESC, PRICE = #PRICE, QUANTITY = #QUANTITY WHERE ID = #ID", GetConnection());
cmd.Parameters.AddWithValue("#ID", Convert.ToInt32(txtItemID.Text));
cmd.Parameters.AddWithValue("#ITEM", txtItemName.Text);
cmd.Parameters.AddWithValue("#ITEM_DESC", txtItemDesc.Text);
cmd.Parameters.AddWithValue("#PRICE", Convert.ToDouble(txtItemPrice2.Text));
cmd.Parameters.AddWithValue("#QUANTITY", Convert.ToInt32(txtItemQuantity.Value));
cmd.ExecuteNonQuery();
Your parameters are in the wrong order, as far as I can see, they must be in the same order as the query. The names are completely irrelevant except as prompts for the progammer, they are not used in any real sense. This means that the wrong value for ID is being used.
OleDbCommand cmd = new OleDbCommand("UPDATE Item SET ITEM = #ITEM,
ITEM_DESC = #ITEM_DESC, PRICE = #PRICE, QUANTITY = #QUANTITY
WHERE ID = #ID", GetConnection());
cmd.Parameters.AddWithValue("#ITEM", txtItemName.Text);
cmd.Parameters.AddWithValue("#ITEM_DESC", txtItemDesc.Text);
cmd.Parameters.AddWithValue("#PRICE", Convert.ToDouble(txtItemPrice2.Text));
cmd.Parameters.AddWithValue("#QUANTITY", Convert.ToInt32(txtItemQuantity.Value));
cmd.Parameters.AddWithValue("#ID", Convert.ToInt32(txtItemID.Text));
cmd.ExecuteNonQuery();

INSERT data from Textbox to Postgres SQL

I just learn how to connect C# and PostgresSQL.
I want to INSERT data from tb1(Textbox) and tb2 to database. But I don't know how to code
My previous code is SELECT from database.
this is my code
private void button1_Click(object sender, EventArgs e)
{
bool blnfound = false;
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=postgres;Password=admin123;Database=Login");
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand("SELECT * FROM login WHERE name='" + tb1.Text + "' and password = '" + tb2.Text + "'",conn);
NpgsqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
blnfound = true;
Form2 f5 = new Form2();
f5.Show();
this.Hide();
}
if (blnfound == false)
{
MessageBox.Show("Name or password is incorrect", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
dr.Close();
conn.Close();
}
}
So please help me the code.
First off, you need to use the ExecuteNonQuery method rather than ExecuteReader since you're executing an INSERT rather than a SELECT statement. So, something like:
NpgsqlCommand cmd = new NpgsqlCommand("insert into table1 values(1, 1)", conn);
cmd.ExecuteNonQuery();
The ExecuteNonQuery method will also return the number of rows affected if that's important for you.
Second, you need to use SQL parameters rather than building an unsafe SQL string.
Use:
cmd.Parameters.Add(new NpgsqlParameter("name", tb1.Text));
cmd.Parameters.Add(new NpgsqlParameter("pw", tb2.Text));
To add a parameter to your query. You can now refer to it in your INSERT statement with :name or :pw, for example:
NpgsqlCommand cmd = new NpgsqlCommand("insert into login (Name, Password) values(:name, :pw)", conn);
cmd.ExecuteNonQuery();
Lastly, you might be interested in using an ORM rather than executing raw SQL statements. I'd check into the .NET Entity Framework or Castle Active Record, which is built on NHibernate. These libraries will allow you to query, update, create and delete data within your database without writing the actual SQL statements involved. It's a great way to get started, and will simply your code quite a bit!

User name can not contain null value

I am trying to insert two values to mysql database through two textboxes using WPF and C#. I am connecting to the database successfuly but when I try to insert the data I get error: Column "user_name" can not be null. What is really confusing be is that I am entering data in the first and the second textboxes. It seems that the data to inserted in the textboxes is not passed. My question is do you know where is the problem and how to fix it?
PS: my database is very simple contain id as int16 auto incremented, name as varchar100 and user_password as varchar100
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection("host=tara.rdb.superhosting.bg;user=sozopouk;password=27051996;database=sozopouk_test2;");
MySqlDataAdapter da = new MySqlDataAdapter();
da.InsertCommand = new MySqlCommand("Insert into niki2 values (#id,#name, #user_password)", con);
da.InsertCommand.Parameters.Add("#name", MySqlDbType.VarChar).Value = textBox1.Text;
da.InsertCommand.Parameters.Add("#user_password", MySqlDbType.VarChar).Value=textBox2.Text;
con.Open();
da.InsertCommand.ExecuteNonQuery();
con.Close();
}
Guys after I did couple of changes I am getting this error message:
Unknown column 'name' in 'field list'
Here is edited code:
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection con = new MySqlConnection("host=tara.rdb.superhosting.bg;user=sozopouk;password=27051996;database=sozopouk_test2;");
MySqlDataAdapter da = new MySqlDataAdapter();
da.InsertCommand = new MySqlCommand("INSERT INTO niki (name, user_password) VALUES (#name, #user_password)", con);
da.InsertCommand.Parameters.Add("#name", MySqlDbType.VarChar).Value = textBox1.Text;
da.InsertCommand.Parameters.Add("#user_password", MySqlDbType.VarChar).Value=textBox2.Text;
con.Open();
da.InsertCommand.ExecuteNonQuery();
con.Close();
}
When I replace name with user_name and try to insert data I get an error ** Column "user_name" cannot be null**
The affected line is :
da.InsertCommand.ExecuteNonQuery();
Do you have any idea how to solve it?
Look at your code:
da.InsertCommand.Parameters.Add("#user_id", MySqlDbType.Int16).Value = "";
da.InsertCommand.Parameters.Add("#user_name", MySqlDbType.VarChar).Value = "";
da.InsertCommand.Parameters.Add("#user_password", MySqlDbType.VarChar).Value =
textBox2.Text;
Now look at what you've said:
It seems that the data to inserted in the textboxes is not passed.
Look at the code again. Look at the value being used for user_name (and indeed user_id). How is that using a textbox value? How are you expecting the data from textBox1 to get to the database when your code never mentions it?
Additionally, as sblom mentions in comments, I'd encourage you to use explicit column names - at which point you won't need to specify anything for user_id, which I assume is an auto-generated identity column anyway. (It therefore doesn't make sense to try to insert an empty value into it.) It's not clear why you're trying to use an empty string as a value for an Int16 column, either...
EDIT: For your edited code:
da.InsertCommand = new MySqlCommand(
"INSERT INTO niki (name, user_password) VALUES (#name, #user_password)", con);
Given your first error, the column is user_name, not name...
Can you just check what table you want to use exactly?
in your actual question it was
da.InsertCommand = new MySqlCommand("Insert into **niki2** values (#id,#name, #user_password)", con);
and in updated question the table name is changed to
da.InsertCommand = new MySqlCommand("INSERT INTO **niki** (name, user_password) VALUES (#name, #user_password)", con);
I feel you have two tables you are playing with and are confused
seems like
name is in niki2 and
user_name is in niki probably your actual table.
I am sure no one can answer with this much ambiguity
Try
For Table niki
da.InsertCommand = new MySqlCommand("INSERT INTO niki (user_name, user_password) VALUES (#user_name, #user_password)", con);
For Table niki2
da.InsertCommand = new MySqlCommand("INSERT INTO niki2 (name, user_password) VALUES (#name, #user_password)", con);
OR Reversal
Luck
You haven't specified in the insert statement in which fields the values should be stored, so the values will end up in the first three fields in the order that you specified, regardless of their names. I guess that the user name field is the fourth, so it doesn't get a value, thus being null.
Specify which fields should be used:
da.InsertCommand = new MySqlCommand("INSERT INTO niki (user_id, user_name, user_password) VALUES (#user_id,#user_name, #user_password)", con);
finally I find the problem causing me this exception. As you can see my old code:
da.InsertCommand = new MySqlCommand("INSERT INTO niki (name, user_password) VALUES (#name, #user_password)", con);
da.InsertCommand.Parameters.Add("#name", MySqlDbType.VarChar).Value = textBox1.Text;
da.InsertCommand.Parameters.Add("#user_password", MySqlDbType.VarChar).Value=textBox2.Text;
enter code here
What I did was to replace the
# with ?
And basically my code looked like :
da.InsertCommand = new MySqlCommand("INSERT INTO niki (name, user_password) VALUES (?name, ?user_password)", con);
da.InsertCommand.Parameters.Add("?name", MySqlDbType.VarChar).Value = textBox1.Text;
da.InsertCommand.Parameters.Add("?user_password", MySqlDbType.VarChar).Value=textBox2.Text;
enter code here
Thanks to all who involved in the discussion!

Categories

Resources