I'm trying to build a little application in C# with a SQL Server database.
I created 2 tables:
Firm with an ID (primary key and Identity) and a column Name
Worker also with an ID, Forename and Surname
In next step I created a relationship between them.
I can add a Firm but in case of adding a worker I get an exception.
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Worker_Firm". The conflict occurred in database "TestDB", table "dbo.Firm", column 'ID'.
The statement has been terminated.
Adding Firm:
string sqlIns = "INSERT INTO Firm (Name) VALUES (#name)";
conn.Open();
SqlCommand cmdIns = new SqlCommand(sqlIns, conn);
cmdIns.Parameters.Add("#name", "MyFirm");
cmdIns.ExecuteNonQuery();
cmdIns.Dispose();
cmdIns = null;
conn.Close();
Adding Worker:
string sqlIns = "INSERT INTO Worker(Forename, Surname) VALUES (#forename, #surname)";
conn.Open();
SqlCommand cmdIns = new SqlCommand(sqlIns, conn);
cmdIns.Parameters.Add("#forename", "MyForename");
cmdIns.Parameters.Add("#surname", "MySurname");
cmdIns.ExecuteNonQuery();
cmdIns.Dispose();
cmdIns = null;
conn.Close();
How can I set the relationship between the worker and the firm into the statement? I doesent see any property like Firm_ID.
Thanks a lot.
Related
I'm trying to insert two data columns into my SQL Server database but I get an error at the code line -> cmd.ExecuteNonQuery();
Cannot insert the value NULL into column OrderID, table RestaurantApp.dbo.Junc_Order; column does not allow nulls. INSERT fails.
The OrderID column is actually the primary key in my data table. I set it identity(1, 1) and want to insert other data and meanwhile it can insert 1, 2, 3, 4....automatically.
Here is the part of my code:
string insertString = "INSERT INTO Junc_Order(ID, Quantity)values (#ID, #Quantity)";
SqlCommand cmd = new SqlCommand(insertString, conn);
cmd.Parameters.AddWithValue("#ID", r_ID);
cmd.Parameters.AddWithValue("#Quantity", r_Quantity);
cmd.ExecuteNonQuery();
I already get connection with database ahead of these codes, so the problem should not be that.
Updated Junc_Order table design:
OrderID (PK,FK,int,not null)
ID(FK,int,not null)
Quantity(int,not null)
By viewing your question, it seems that your insert query is not correct:
First of all, you don't need to insert "OrderID" as it is primary key identity so sql server automatically insert it.
second, somewhere you are getting "r_ID" as null that's why you are facing error.Verify it and modify your code with the following:
string insertString = "INSERT INTO Junc_Order(Quantity) values(#Quantity)";
SqlCommand cmd = new SqlCommand(insertString, conn);
cmd.Parameters.AddWithValue("#Quantity", r_Quantity);
cmd.ExecuteNonQuery();
I have a database with 3 tables. One of them holds a relation of the other two. E.g.:
Table1 = idTable1 (PK_Table1), attribute1, attribute2, attribute3
Table2 = idTable2 (PK_Table2), attribute1
Table3 = idTable3 (PK_Table3), attribute1 (FK relating to idTable1), attribute2 (FK relating to idTable2)
All primary keys are auto-incrementing fields assigned automatically by Access (2002 version, that's why my db is a .mdb).
In my code I insert data in Table1 and Table2 using some code like this:
public void insert()
{
string query = "INSERT INTO Table1 (attribute1,attribute2,attribute3) VALUES (?,?,?)";
OleDbConnection dbConnection = new OleDbConnection();
dbConnection.ConnectionString = connStr;
try
{
dbConnection.Open();
OleDbCommand commandStatement = new OleDbCommand();
OleDbCommand primarykey = new OleDbCommand("ALTER TABLE Table1 ADD CONSTRAINT pk_Table1 primary key(idTable1)", dbConnection);
primarykey.Connection = dbConnection;
commandStatement.Connection = dbConnection;
commandStatement.CommandText = query;
commandStatement.Parameters.Add("attribute1", OleDbType.Integer).Value = attribute1;
commandStatement.Parameters.Add("attribute2", OleDbType.Integer).Value = attribute2;
commandStatement.Parameters.Add("attribute3", OleDbType.Integer).Value = attribute3;
commandStatement.ExecuteNonQuery();
primarykey.ExecuteNonQuery();
dbConnection.Close();
dbConnection.Dispose();
commandStatement.Dispose();
primarykey.Dispose();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
(and then something like that for Table2 as well).
For each row in Table1, I insert about 40 rows in Table2 (they're tables holding info of a contest and their contestants).
Now I need to create a relation between those two, using Table3, which must reference the id of both tables as foreign keys.
And that's where I'm lost. I don't know how to say "take the id of the row you just inserted in Table1 and then the id of a row you just inserted in Table2 and insert them as a new record in Table3".
Is there a way to get the autoincrementing IDs that are being assigned by the database, as soon as I insert a record?
After inserting a row you can use SELECT ##Identity to retrieve the autoincremented value. Store it, insert the other row, do the same select and then insert these values to the link table.
More information (for VB.NET, but easily understandable) from Microsoft at HOW TO: Retrieve the Identity Value While Inserting Records into Access Database
In C# I am trying to insert records from one access table to another access table, but I get the above error message. What is causing this error (OleDbException: No value given for one or more required parameters) as it is a straight Select * statement?
OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=P:\\Source.mdb;");
connection.Open();
OleDbCommand command = new OleDbCommand("INSERT INTO [;DATABASE=V:\\Destination.mdb;].[table1] SELECT * FROM table1 WHERE company = 2", connection);
command.ExecuteNonQuery();
connection.Close();
EDIT --- Error in Insert Statement
OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=P:\\Source.mdb;");
connection.Open();
OleDbCommand command = new OleDbCommand("INSERT INTO [;DATABASE=V:\\Destination.mdb;].[table1] (Name, Address, Phone, RepeatCustomer) SELECT Name, Address, Phone, RepeatCustomer FROM table1 WHERE company = 2", connection);
command.ExecuteNonQuery();
connection.Close();
Are the two tables identical? You'd get this error if the column order and/or types don't match. It's much better form to explicitly define the columns you want to modify:
INSERT INTO [;DATABASE=V:\\Destination.mdb;].[table1] (col1,col2) SELECT col1,col2 FROM table1 WHERE company = 2
this way, order doesn't matter, and you aren't trying to add to columns that don't exist.
I had the same issue copying to the same table. This sample of just two fields worked for me:
INSERT INTO [Orders] (CUST, PART_NUMBE) SELECT CUST, PART_NUMBE FROM [orders]
WHERE [OrderNumber]= 23979
I have a table structured as,
Table 3
Fruit ID - Foreign Key (Primary Key of Table 1)
Crate ID - Foreign Key (Primary Key of Table 2)
Now I need to execute a query which will,
Update Crate ID of Fruit ID if Fruit ID is already in Table, and if not then insert record in table 3 as new record.
This is what I got in code right now,
private void RelateFuirtWithCrates(List<string> selectedFruitIDs, int selectedCrateID)
{
string insertStatement = "INSERT INTO Fruit_Crate(FruitID, CrateID) Values " +
"(#FruitID, #CrateID);"; ?? I don't think if it's right query
using (SqlConnection connection = new SqlConnection(ConnectionString()))
using (SqlCommand cmd = new SqlCommand(insertStatement, connection))
{
connection.Open();
cmd.Parameters.Add(new SqlParameter("#FruitID", ????? Not sure what goes in here));
cmd.Parameters.Add(new SqlParameter("#CrateID",selectedCrateID));
}
You can do an "upsert" with the MERGE syntax in SQL Server:
MERGE [SomeTable] AS target
USING (SELECT #FruitID, #CrateID) AS source (FruitID, CrateID)
ON (target.FruitID = source.FruitID)
WHEN MATCHED THEN
UPDATE SET CrateID = source.CrateID
WHEN NOT MATCHED THEN
INSERT (FruitID, CrateID)
VALUES (source.FruitID, source.CrateID);
Otherwise, you can use something like:
update [SomeTable] set CrateID = #CrateID where FruitID = #FruitID
if ##rowcount = 0
insert [SomeTable] (FruitID, CrateID) values (#FruitID, #CrateID)
I encounter this error when trying to insert the comments user edited under my UPDATE SQL statement. As my UserId is an uniqueIdentifier, I do not really know how to solve this error.
The error shows:
Cannot insert the value NULL into column 'UserId', table
My .cs code is:
int CommentID = int.Parse(ListView1.DataKeys[e.ItemIndex].Value.ToString());
ListViewItem item = ListView1.Items[e.ItemIndex];
TextBox Title = (TextBox)item.FindControl("Title");
TextBox commentContent = (TextBox)item.FindControl("commentContent");
string connectionString = ConfigurationManager.ConnectionStrings["ASPNETDBConnectionString1"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
{
string sql = "Update Comments set Title = #Title, commentContent=#commentContent where CommentID = #CommentID";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#Title", TextBox1.Text.Trim());
cmd.Parameters.AddWithValue("#commentContent", TextBox2.Text.Trim());
cmd.Parameters.AddWithValue("#CommentID", CommentID);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
I think the UserID column in the table is having NOT NULL constraint.Check your table schema.
It seems to me, the UserID has a not null constraint. Check in your database for that.
I think that UserId is your foreign key, you must define one foreign key
Comments contains UserId as Foreign Key, you must set UserId, because key can't be null