Cannot insert the value NULL into column 'UserId', table - c#

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

Related

How to fix FK Constraint insert Exception

According to my question with weird problem specified here how to fix
System.Data.SqlClient.SqlException: String or binary data would be truncated in table
My problem is, that if I am saving new problem into the database, its ID is always set to 0 (I checked this out in debugging), which then throws
System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK__Alert__Problem_I__17F790F9". The conflict occurred in database "SmartOne", table "dbo.Problem", column 'id'
But in SQL Server Management Studio, the ID is set correctly (ID is defined as an Identity column).
Where both I am using is in my question mentioned below. Thanks for any ideas or advice.
Method that saves Problem:
public void Save(Problem element)
{
using (SqlConnection conn = new SqlConnection(DatabaseSingleton.connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO Problem VALUES " +
"(#nameOfAlert, #value, #result, #message_ID) ", conn))
{
command.Parameters.Add(new SqlParameter("#nameOfAlert", element.NameOfAlert));
command.Parameters.Add(new SqlParameter("#value", (int)element.Value));
command.Parameters.Add(new SqlParameter("#result", (int)element.Result));
command.Parameters.Add(new SqlParameter("#message_ID", element.Message_Id));
command.ExecuteNonQuery();
command.CommandText = "Select ##Identity";
}
conn.Close();
}
}
Method that saves an Alert:
public void Save(Alert element)
{
using (SqlConnection conn = new SqlConnection(DatabaseSingleton.connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand("INSERT INTO [Alert] VALUES (#message_ID, #date, #email, #AMUser_ID, #Problem_ID) ", conn))
{
command.Parameters.Add(new SqlParameter("#message_ID", element.Id_MimeMessage));
command.Parameters.Add(new SqlParameter("#date", element.Date));
command.Parameters.Add(new SqlParameter("#email", element.Email));
command.Parameters.Add(new SqlParameter("#AMUser_ID", element.User_ID));
command.Parameters.Add(new SqlParameter("#Problem_ID", element.Problem_ID));
command.ExecuteNonQuery();
command.CommandText = "Select ##Identity";
}
conn.Close();
}
}
SQL Scheme
CREATE TABLE [dbo].[Alert](
[id] [int] IDENTITY(1,1) NOT NULL,
[message_ID] [varchar](100) NOT NULL,
[date] [datetime] NOT NULL,
[email] [varchar](50) NOT NULL,
[AMUser_ID] [int] NOT NULL,
[Problem_ID] [int] NOT NULL);
//Where is ID, it means FK ID
CREATE TABLE [dbo].[Problem](
[id] [int] IDENTITY(1,1) NOT NULL,
[nameOfAlert] [varchar](50) NOT NULL,
[Value_ID] [int] NOT NULL,
[Result_ID] [int] NOT NULL,
[message_ID] [varchar](100) NOT NULL);
One problem might be that you're never actually getting back the inserted IDENTITY value from your first insert - thus you aren't using any valid ProblemId value for your second insert.
Try something like this:
public void Save(Problem element)
{
using (SqlConnection conn = new SqlConnection(DatabaseSingleton.connString))
{
conn.Open();
// define INSERT query - I'd *strongly* recommend specifying all
// columns you're inserting into!
// Also: run the "SELECT SCOPE_IDENTITY()" right after the INSERT
string insertQry = "INSERT INTO dbo.Problem(NameOfAlert, Value, Result, MessageId) " +
"VALUES (#nameOfAlert, #value, #result, #message_ID); " +
"SELECT SCOPE_IDENTITY();";
using (SqlCommand command = new SqlCommand(insertQry, conn))
{
// also here: define the *datatype* of the parameter, and use
// .Value = to set the value.
// Since you haven't shown what the table looks like, I'm just
// **guessing** the datatype and max length for the string parameters - adapt as needed!
command.Parameters.Add("#nameOfAlert", SqlDbType.VarChar, 100).Value = element.NameOfAlert;
command.Parameters.Add("#value", SqlDbType.Int).Value = (int)element.Value;
command.Parameters.Add("#result", SqlDbType.Int).Value = (int)element.Result;
command.Parameters.Add("#message_ID", SqlDbType.VarChar, 100).Value = element.Message_Id;
// since your statement now returns the ID value - use "ExecuteScalar"
var returnedValue = command.ExecuteScalar();
if (returnedValue != null)
{
// if a value was returned - convert to INT
int problemId = Convert.ToInt32(returnedValue);
}
}
conn.Close();
}
}
Now, in case the INSERT works, you get back the ProblemId value from the identity column, and you can now use this in your second insert as value for the #ProblemId parameter.
For saving the id into other table, you have to complete the insertion first. if the insertion is not completed then you can not get the problem id (if it is the primary key, which is supposed to be returned by saving the datas). Only after saving the data to the table, you are going to have the problem id then you can use it as FK in the same method.
if i say, there is two table and you are going to use the first table primary key in the second table as FK. Then you need to complete the first table row insertion. after excuting the query for the first table, you will get the primary key of that row and you can use easily in the second table as FK.

How to select Max Value from database in Textbox

i have simple table item and a text box textbox1 now i want to show max value in textbox i am using the command but code not work
item table: CREATE TABLE TableItem( ItemId NUMBER(10) NOT NULL,
ItemName VARCHAR2(40) NOT NULL, UnitId NUMBER(10) NOT NULL,
CategoryId NUMBER(10) NOT NULL, ItemStatus NUMBER(1) NOT NULL,
SupplierId NUMBER(10)NOT NULL );
and item table insert data:
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(01,'Product-1',21,10,1,51);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(02,'Product-2',22,11,1,52);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(03,'Product-3',23,12,1,53);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(04,'Product-4',24,14,1,53);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(05,'Product-5',21,12,1,53);
INSERT INTO TableItem(ITEMID,ITEMNAME,UNITID,CATEGORYID,ITEMSTATUS,SUPPLIERID)
VALUES(06,'Product-5',23,12,1,52);
now i need max value of itemid
con.Open();
try
{
OleDbCommand cmd4 = new OleDbCommand("SELECT MAX(ItemId) FROM TableItem", con);
textBoxInsert.Text = cmd4.ExecuteScalar().ToString();
}
finally
{
}
con.Close();
You need to create a data adapter, it will fetch your SQL in your database based on your connection. After that you will get a table as result, so you just need to add it to your DataTable and get the rows. There is more interesting implementations, but with this code you can see if it everything is working fine, I've implemented a MySQL version like this:
DataTable _datatable = new DataTable();
MySQLDataAdapter _adapter = new MySQLDataAdapter("SELECT * FROM TEST_TABLE", connection)
_adapter.Fill(_datatable);
myTextBox.Text = _datatable.Rows[0]["ID"].ToString();
On your case, you just need to replace MySQLDataAdapter with OracleDataAdapter, from OracleClient
Reference:
https://msdn.microsoft.com/pt-br/library/system.data.oracleclient.oracledataadapter(v=vs.110).aspx
It is simple. We took the double result for the number we will get in the database.
using (MySqlCommand cmd = new MySqlCommand("SELECT MAX(ItemId) FROM TableItem", con))
{
con.Open();
double result = (Convert.ToDouble(cmd.ExecuteScalar()));
textBoxInsert.Text = result.ToString();
}

insert value from TextBox into sql

I'm getting this error message: Cannot insert the value NULL into column 'id', table ''; column does not allow nulls. INSERT fails. thanks in advance
protected void AddItem(object sender, EventArgs e)
{
string insertCmd = "INSERT INTO Picture (Album, id) VALUES (#Album, #id)";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
// Create parameters for the SqlCommand object
// initialize with input-form field values
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
myCommand.Parameters.Add("#id", SqlDbType.Int).Direction = ParameterDirection.Output;
myCommand.ExecuteNonQuery();
int id = (int)myCommand.Parameters["#id"].Value;
}
}
I suppose that ID is an IDENTITY column. Its value is generated automatically by the database engine and you want to know what value has been assigned to your record.
Then you should change your query to
string insertCmd = #"INSERT INTO Picture (Album) VALUES (#Album);
SELECT SCOPE_IDENTITY()";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
int newID = Convert.ToInt32(myCommand.ExecuteScalar());
}
The query text now contains a second instruction SELECT SCOPE_IDENTITY() separated from the first command by a semicolon. SCOPE_IDENTITY returns the last IDENTITY value generated for you by the database engine in the current scope.
Now the command is run using the ExecuteScalar to get back the single value returned by the last statement present in the query text without using any output parameter
I would think that ID is identity. You don't have to add this value. I would try the following code and check the database if you get automatically an ID.
string insertCmd = "INSERT INTO Picture (Album) VALUES (#Album)";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
// Create parameters for the SqlCommand object
// initialize with input-form field values
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
myCommand.ExecuteNonQuery();
}
I case you want to set the id yourself(withoud automatic increment from the db), you should change the schema of the database removing identity from ID as shown below:
I hope this helps
If you need to stay this column empty you can try to replace to ' '(blank). This will work if you column is not "Key"
Or try to use:
substitute a value when a null value is encountered
NVL( string1, replace_with )
You can do this using stored procedure. Below is the script for Create stored procedure.
CREATE PROCEDURE [dbo].[InsertIntoPicture]
#Album varchar(500)=null,
#id int=0 output
AS
BEGIN
insert INTO Picture(Album)VALUES(#Album)
SET #id=##IDENTITY
END
Below is the code for call stored procedure with C# .
string insertCmd = "InsertIntoPicture";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["strConn"].ConnectionString))
{
conn.Open();
SqlCommand myCommand = new SqlCommand(insertCmd, conn);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("#Album", txtAlbum.Text);
myCommand.Parameters.Add("#id", SqlDbType.Int).Direction = ParameterDirection.Output;
myCommand.ExecuteNonQuery();
int id = (int)myCommand.Parameters["#id"].Value;
}
Using above code you can insert a date from TextBox and also get last inserted record ID as an output variable as per your requirement.
Thanks .

C# SQL Server database with relationships - insert statement

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.

how can i update SQL table logic

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)

Categories