I have looked at all the similar questions on this topic but none seem to work for me.
When I try to run my application, I get the following error:
System.Data.SqlClient.SqlException: 'Cannot insert the value NULL into column 'Id', table 'C:\FINALLY\DATABASE.MDF.dbo.loginTB'; column does not allow nulls. INSERT fails.
Here is my code:
private void btnContinued_reg_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\finally\DataBase.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd= new SqlCommand("insert into loginTB(username,password)values('" + txtUserName_reg.Text + "','" + txtPaswword_reg.Text + "')",cn);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("good");
}
What am I doing wrong?
A snapshot of my code:
The problem does not indicate a connection problem at all. It seems that you are trying to insert a record into a table, and you are trying to pass null as the id, which gives you the error.
My guess would be the error is in the definition of that table loginTB, you make sure the column id has the property IDENTITY, since you are using SQL Server.
An example would be like this:
CREATE TABLE new_employees
(
id_num int PRIMARY KEY IDENTITY(1,1),
fname varchar (20),
minit char(1),
lname varchar(30)
);
Identity columns can be used for generating key values. The identity property on a column guarantees the following:
Each new value is generated based on the current seed & increment.
Each new value for a particular transaction is different from other concurrent transactions on the table.
The identity property on a column does not guarantee the following:
Uniqueness of the value
Uniqueness must be enforced by using a PRIMARY KEY or UNIQUE constraint or UNIQUE index.
Follow up answer of previous answers.
If you already created a table and want to modify it to work correctly:
Go to the table properties from SSMS tool and select the identity column and save the properties. Identity column must be marked as not nullable.
Related
I am creating a table that at first keyID column is NOT in AUTO INCREMENT since i am going to insert a data that came from an old database where the keyID is already been set to each rows and it's not possible to be changed. So is it possible that i can set the column to AUTO INCREMENT after all the data has been moved? I've seen this:
ALTER TABLE tbl_name MODIFY COLUMN keyID_id INT auto_increment
So if ever i set the keyID to auto increment after i moved all the data, so for example 10 rows has been transferred and some numbers may be missing for example, keyIDs: 1,2,3,5,6,7...15
can I assume that after i set the keyID to auto increment, the next row will be keyID 16?
The first thing to say here is that SQLite has no syntax to change the settings of a column. You are forced to rename your original table, create a new table with the schema you want and then copy from the renamed table into the new one.
So your code to add the AUTOINCREMENT flag to your table is something like this
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = yourConnection;
cmd.CommandText = "ALTER TABLE tblName RENAME TO tmp_tblName";
cmd.ExecuteNonQuery();
cmd = new SQLiteCommand(#"
CREATE TABLE tblName
(ID INTEGER PRIMARY KEY AUTOINCREMENT,
AnotherField NVARCHAR(100) NOT NULL)", cnn);
cmd.ExecuteNonQuery();
cmd.CommandText = "INSERT INTO tblName (ID, AnotherField) SELECT ID, AnotherField FROM tmp_tblName";
cmd.ExecuteNonQuery();
Now, when you create a table with the AUTOINCREMENT SQLite add a new row to an internal table called sqlite_sequence. This table could be read by the usual ADO.NET classes
cmd.CommandText = "SELECT seq FROM sqlite_sequence WHERE name = 'tblName'";
int lastInsertedValue = Convert.ToInt32(cmd.ExecuteScalar());
Console.WriteLine(lastInsertedValue);
If your run this test code you will see that the value for the field seq is equal to the maximum value inserted in the PRIMARY KEY field.
After this if you try to insert a new record in your table you will see that the AUTOINCREMENT flag has started to work as expected and your new record will receive the next value from the sequence....
Even though the SQLite documentation and some posts state that the alter table command in SQLite is very limited and should not allow making such modifications, it seems that it's still possible to alter PK properties. What worked for me was:
Create a table with CREATE TABLE "test" (Field1INTEGER,Field2TEXT,)
Insert arbitrary data
Change column definition for column Field1 with DB Browser for SQLite
Subsequent inserts should then auto increment the IDs in the column Field1.
I must admit that it might not be suitable if there's the requirement to do this programatically, but if some manual steps are acceptable, it may be a solution.
I am using a temporary table to display data in a datagridview. When the data in the datagridview is edited, I am trying to update the temporary table. This is the code inside the dataGridView1_RowValidated method that I'm using to do so:
MySqlDataAdapter adapter = new MySqlDataAdapter("select * from all_plants_temp", con);
MySqlCommandBuilder builder = new MySqlCommandBuilder(adapter);
adapter.UpdateCommand = builder.GetUpdateCommand();
adapter.Update(changes);
((DataTable)dataGridView1.DataSource).AcceptChanges();
However, I am running into the following error whenever I leave the edited row:
Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.
From what the error suggests (along with every website I visited), I need to include a primary key in the table. However, I already have an int auto-incrementing primary key. This is the code that I used to create the temporary table, along with the relevant code of the original non-temporary table.
ALTER TABLE all_plants ADD COLUMN plantID INT PRIMARY KEY AUTO_INCREMENT;
CREATE TEMPORARY TABLE all_plants_temp SELECT * FROM all_plants;
Can someone tell me the fault in my code? Any help is appreciated.
As said before I belive your temporary table does not have a primary key.
Try using this query. It will create the temporary table with a Primary Key. Change YourPk with what you want.
CREATE TEMPORARY TABLE all_plants_temp
(YourPk int(10) NOT NULL, PRIMARY KEY (YourPk)) SELECT * from all_plants;
I have a problem with ADO.NET query. I Create Database successfuly. There is only one table (RegUsers) in this database (I am just testing the work with ADO.NET). EDIT: Databese is based on Microsoft Azure
Create of a my table:
CREATE TABLE [dbo].[RegUsers] (
[Id] INT NOT NULL,
[Login] VARCHAR (50) NOT NULL,
[Password] VARCHAR (50) NOT NULL,
[Name] VARCHAR (50) NOT NULL,
[Surname] VARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC));
I create SqlConnecion and successfully connect to the database (I hope that successfully if I can Open the connection) and then I'd like to INSERT data into this table with this:
SqlConnectionStringBuilder csBuilder;
csBuilder = new SqlConnectionStringBuilder();
csBuilder.DataSource = "********.database.windows.net";
csBuilder.Encrypt = true;
csBuilder.TrustServerCertificate = false;
csBuilder.UserID = "************".ToString();
csBuilder.Password = "********".ToString();
csBuilder.ConnectTimeout = 30
SqlConnection con = new SqlConnection(csBuilder.ToString());
con.Open();
string PlneniDaty =
#"INSERT INTO [dbo].[RegUsers] (Login,Password,Name,Surname)"+
#" VALUES ('MyLogin','MyPassword','Pavel','Novak')";
SqlCommand NaplDaty = new SqlCommand(PlneniDaty, con);
NaplDaty.ExecuteNonQuery();
con.Close();
Whenever I execute this command It display Error:
Invalid object name 'dbo.RegUsers'
(and yes the table was successfully created I can see it in SQL Server object Explorer)
Where is the problem?
Your entire code looks good.you can post your connectionString.
Following things you need to check.
Connection String ( Data Source Name , Database Name )
Schema of your table.
If I understand correctly, you're executing a insert query in a database dbo.RegUsers and it's giving the error Invalid object name 'dbo.RegUsers'? That simply means that table cannot find an object called "RegUsers ". There are several possible reasons for this:
The object doesn't exist, possibly because the schema and/or database don't exist
The object exists, but the database is case-sensitive and some part of the name doesn't match the name in your code
You'll need to investigate more to find out what the cause is in your case, but as a complete guess, your production server has both the RegUsers and databases?
Finally, when posting questions please always include your SQL Server version (2000/2005/2008) and edition (Express, Standard, Enterprise); they can be very important when talking about schemas and permissions, because features and behaviour can be different.
As far as I can see from your create script, your table's name is RegUzivatele, while you're trying to insert to a table name RegUsers, which of course doesn't exist.
hi i have many problem with update sql database from c# form
fisrt: i use this code for a button called "Update" that get values directly from text boxes and fill main sql server database.
SqlConnection cnt = new SqlConnection("Data Source=.;Initial Catalog=db3;Integrated Security=True");
SqlCommand cmd = new SqlCommand("update phone set name=#name,lastname=#lastname,Phone=#Phone,Mobile=#Mobile,Area=#Area,date=#date", cnt);
cnt.Open();
cmd.Parameters.AddWithValue("#name", namebox.Text);
cmd.Parameters.AddWithValue("#lastname", lastbox.Text);
cmd.Parameters.AddWithValue("#Phone", phonebox.Text);
cmd.Parameters.AddWithValue("#Mobile", mobilebox.Text);
cmd.Parameters.AddWithValue("#Area", areabox.Text);
cmd.Parameters.AddWithValue("#date", datestring);
cmd.ExecuteNonQuery();
cnt.Close();
but it get error in mobile column :
Violation of UNIQUE KEY constraint 'UQ__phone__5C7E359EA73D3013'. Cannot insert duplicate key in object 'dbo.phone'. The duplicate key value is (4802615).
Note 2: I am using this code for select and view selected row ready for edit
1-Problem Solved the SQL column was Unique index so i removed that.
2- there wasn't a "where condition" so i fixed that too
Where clause is not used so all the rows in the table are getting updated and hence the error is getting generated.
Add a "WHERE Phone=#phone" and it's associated parameter command. As the other person pointed out, you're updating but you haven't told the database to specifically focus on an individual record, so your command updates them all.
This is fine for the first record, as soon as it tries updating the second, it blows up because phone has a unique constraint on it, preventing any other record having the same data. That's your error message.
You need to change your update statement to target the exact record you want to update.
I think you should set the PK or you update all the rows in the phone table.
for example: UPDATE tablename SET columName WHERE ....
I hope this will be useful
I am simply attempting to insert a new record into our SQL Server database. The insert is happening from within a WCF web service using LINQ.
The table d_coord_report_conflict is structured as follows:
conflict_report_id int NOT NULL IDENTITY PRIMARY KEY,
booking_id int,
conflict_date date,
coord_user_id int
guide_one_user_id int,
guide_two_user_id int,
product_id int,
price_id int
Everything is a foreign key except conflict_report_id and conflict_date.
Here's the insert from the WCF service in C#:
d_coord_report_conflict conflict = new d_coord_report_conflict
{
booking_id = bookingID,
conflict_date = date,
coord_user_id = Convert.ToInt32(item.coordID),
guide_one_user_id = pax.user_id_guide,
guide_two_user_id = Convert.ToInt32(item.guideID),
product_id = Convert.ToInt32(item.productID),
price_id = Convert.ToInt32(item.priceID)
};
db.d_coord_report_conflicts.InsertOnSubmit(conflict);
db.SubmitChanges();
It should be a straight forward insert but it keeps throwing back the following error:
Cannot insert explicit value for identity column in table 'd_coord_report_conflict' when IDENTITY_INSERT is set to OFF.
As far as I can see this shouldn't be happening. Also, turning on IDENTITY_INSERT is not an acceptable solution as I'm sure you understand.
UPDATE: I recovered the values of each field is it is passed into the LINQ query and attempted a manual insert from within SQL Server Management Studio and it worked fine. no errors at all. Any ideas?
Thanks in advance.
What query have u written in method db.d_coord_report_conflicts.InsertOnSubmit(conflict)?
Whether it is stored proc, or an inline sql query in c#, check for correct column names and order.
remember: you must not pass value/mention name of identity column in INSERT query.
if your table is like this
Create table Test
{
testId int not null identity primary key,
testName varchar(50), createdDate datetime
}
Your INSERT query should be something like
INSERT INTO TEST(testName,createdDate) values ('New Test', getdate())
observe that i have not mentioned the identity column anywhere in the insert query, since its value is automatically filled
Hope this makes sense!