Hi guys i'm trying to modify a piece of data in my database here is the section of code i'm using.
private void btnModifyMember_Click(object sender, EventArgs e)
{
string memberid = txtMemberID.Text;
string lastname = txtLastName.Text;
string firstname = txtFirstName.Text;
string phone = txtPhoneNumber.Text;
string email = txtEmail.Text;
string update = "UPDATE [Club_Member] SET [MemberID]=#memberid,[LastName]=#lastname,[FirstName]=#firstname,[Phone]=#phone,[E_mail]=#email";
OleDbCommand dbCmd = new OleDbCommand(update, dbConn);
dbCmd.Parameters.AddWithValue("#MemberID", memberid);
dbCmd.Parameters.AddWithValue("#LastName", lastname);
dbCmd.Parameters.AddWithValue("#FirstName", firstname);
dbCmd.Parameters.AddWithValue("#Phone", phone);
dbCmd.Parameters.AddWithValue("#E_mail", email);
try
{
dbCmd.ExecuteNonQuery();
MessageBox.Show("Update Complete");
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
}
So i run debug, i change one of the entries, i hit the modify member button, then i get a messagebox saying "The record cannot be deleted or changed because table 'Property' includes related records" Debug still goes and I don't get any errors.
Thank you.
You tried to perform an operation that would have violated referential integrity rules for related tables. For example, this error occurs if you try to delete or change a record in the "one" table in a one-to-many relationship when there are related records in the "many" table.
If you want to delete or change the record, first delete the related records from the "many" table. and in your case, you must be trying to update the foreign key column, which is referring to some other table's record.
From your code, one can easily assume that your column MemberID in table club_members, must be a foriegn key, referring to Member table's row. This is where you're making mess. you cannot violate the referential integrity by simply deleting/updating the record you want.
Related
In this code, I have an insert button that will take in the user's input from the textbox and store it in the database. I know the code works as intended with the other tables that have no Foreign Keys in them, but this one does and I'm not sure how to handle it. Everytime it tries to insert CustomerID, the Foreign Key, I keep getting the following error, System.Data.SqlClient.SqlException: 'The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Orders_Customers". The conflict occurred in database "northwind", table "dbo.Customers", column 'CustomerID'.
Below is the insert button code and an image of the program running.
private void button9_Click(object sender, EventArgs e)
{
Order od = new Order
{
OrderID = int.Parse(ordertxt.Text),
CustomerID = customertxt.Text
};
db.Orders.InsertOnSubmit(od);
try
{
db.SubmitChanges();
}
catch (Exception)
{
MessageBox.Show("Invalid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
db.SubmitChanges();
}
display_order();
Program Running
The value that you are inserting into the CustomerID column does not exist in your Customer table, so it cannot be inserted as a foreign key. You could either add logic to validate the value against the Customer table before inserting, and create a new customer if needed, or alter the column so that it is no longer a foreign key if you do not need it to act as such.
I am trying to add records to a SQL Server database. The connection works fine for any other table except one.
This is my code:
private void saveCurrent()
{
try
// Save entry into the database.
{
string query = "INSERT INTO entries VALUES (#Date, #Tags, #Entry, #User)";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("#Date", System.DateTime.Now.ToLongDateString());
command.Parameters.AddWithValue("#Tags", txtTags.Text);
command.Parameters.AddWithValue("#Entry", richEntryBox.Text);
command.Parameters.AddWithValue("#User", Form1.userName);
command.ExecuteNonQuery();
isDirty = false;
}
}
catch (Exception exception)
{
MessageBox.Show("There was an error saving this entry: " + exception.ToString());
}
The error is:
System.Data.SqlClient.SqlException (0x8-131904): Column name or number of supplied values does not match table definition.
All of the columns are of type nvarchar(50) and nvarchar(MAX). I am trying to enter just text information, no binaries. The dataset shows that the table has a "photos" column, but it can be null and I'm not using it (for some reason, I cannot get VS2017 to delete that column). I have altered the dataset to not include the "photos" field, but still receiving the error. Any push to the solution would be appreciated. A snap of the dataset is included here.
My dataset, in which I've removed the photos column:
--S
If your database still has the photos field, you'll need to specify the columns for insertion explicitly.
So change your insert to:
string query = "INSERT INTO entries (date, tags, entry, user) VALUES (#Date, #Tags, #Entry, #User)";
In general, you want to be explicit with your insertions. What would happen if someone added a column after tags and before entry in the database? This would break your code.
I have the following situation:
In my database, I have a table called Person. A person has an ID. In my conceptual model, student is inherited from person, so I have another table called Student.
I wrote C# code to insert into the Student table:
string query = "INSERT INTO Person (ID, ...) VALUES("id",...);";
MySqlCommand command = new MySqlCommand(query, connection);
command.ExecuteNonQuery();
query = "INSERT INTO Student (..., ID) VALUES(...,"id");";
command.ExecuteNonQuery();
Obviously, I need to add values into the Person class first, because every student is a person. So, after I did that, I try to add the rest of the Student data into the table.
The problem is that I am getting this error:
Duplicate entry (id) for key "PRIMARY"
which I don't understand, since this key needs to be the same.
The exception message is pretty clear:
Duplicate entry (id) for key "PRIMARY"
You ARE duplicating the ID on a table.
You didn't tell in which line this is happening, so, let's assume both possibilities (and that the error is not elsewhere).
The exception is happening when you are trying to insert into table PERSON.
In this case,if the PRIMARY KEY of this table was AUTO INCREMENT, this wouldn't be possible. If it isn't, and you are inserting the ID of the record by yourself, your code is not creating the ID's correctly and is inserting a value that already exists in the table.
To check if this is the case during runtime, just make a select for the ID you are trying to insert BEFORE actually inserting it:
string query = "SELECT count(*) FROM Person WHERE ID = " + id;
MySqlCommand command = new MySqlCommand(query, connection);
int count = (int)command.ExecuteScalar();
if (count > 0)
{
//You already inserted this ID. Warn the user
}
You are getting the exception on when inserting into table STUDENT
First, lets assume that the ID you are inserting into STUDENT that you're showing here is not the PRIMARY KEY of the table student, but only a FK (foreign key) to table PERSON.
In this case, the same fro the item 1 applies here. You ARE entering a duplicate id in the table. Use the same approach from item 1 to verify this.
But if the ID from PERSON is really the same ID from STUDENT (a ONE to ONE relationship), what's the problem?
Exactly the same. You are entering a duplicated ID.
So, no matter where the error is happening, you are allowing your code to try to insert a DUPLICATE ID (primary key) in the table.
Again, you must be creating the ID's manually, as an auto-increment primary key would not cause this problem (UNLESS you are manually setting the ID, in which case MySQL would use this value instead of the automatic value).
If you are creating the ID's manually, you MUST ensure that they are not duplicates.
I don't even know if this should be called an answer or a hack, but it worked:
string query = "INSERT INTO Person (ID, ...) VALUES(id, ...);
INSERT INTO Student (..., ID) VALUES(..., (select ID from Person WHERE Person.ID = id));";
MySqlCommand command = new MySqlCommand(query, connection);
I have a Windows Presentation Foundation, I have a Database called "Worker" and a table that belongs to this Database, the table is called TestTable,with 6 columns: Id,Name, Lastname, Gender, Email and Password, I already added some elements,in the Mainwindow the user can see all the information contained in the database columns except Id, I kept Id out of user`s sight, so I have different Listboxs with the information: ListboxNames, ListboxLastnames, ListboxGenders, etc...I made a method that allows me to delete rows from the Database according to the ListboxNames.SelectedItem, but it deletes using the name, which is not convenient because there could be several equal names, could you explain me how to get the correct id according to the ListboxNames.SelectedItem, how could I delete using the Id selecting a name from the ListBox?? Remember I never show the Id to the usser, thanks beforehand!!!
This is the method I use to delete, I guess I need to get the ids with the same name from the database maybe first and then I must choose between the ids the correct one, you just let me know!
private void buttonDelete_Click(object sender, RoutedEventArgs e)
{
cmd.CommandText = "delete from TestTable where name='" + listBoxListNames.SelectedItem + "'";
con.Open();
cmd.ExecuteNonQuery();
con.Close();
listBoxListNames.Items.Clear();
listBoxListLastnames.Items.Clear();
listBoxListGenders.Items.Clear();
listBoxListEmails.Items.Clear();
listBoxListPasswords.Items.Clear();
ShowDatabase();
}
You can use SelectedValue property of listbox in this case; for that you need to bind the list box in following way:
Listbox definition:
<ListBox Name="myList" SelectedValuePath="myID" DisplayMemberPath="myTextField"... />
Binding:
DataTable myDataTable= getDataTable();//populate datatable from database
myList.SelectedValuePath = "myID";
myList.DisplayMemberPath = "myTextField";
myList.ItemsSource = myDataTable;
Then you can re-write your code to delete items using SelectedValue :
private void buttonDelete_Click(object sender, RoutedEventArgs e)
{
cmd.CommandText = "delete from TestTable where itemID=#myID";
cmd.Parameters.AddWithValue("myID", myList.SelectedValue);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
//Do rest of operations here
}
Note : You have to use parameterized query to avoid injection; so take a look into the query too
i already created the windows forms that the function is to add the information to the database. But, i have a problem. When i type the number like this one "SM0001" in the "Product Code" column, and hit enter, it store the data to the database and when i type the same number like i typed before, it does not prevent the user like the entered "Product Code" already exists in the database. So, this is my currently database (displayed in the datagridview in the system):
As you can see the row "1" and row "2" has the same "Product Code".. My question is: How do i prevent the user to entering the same number twice?
i already change the Primary Key in the database to the "Product Code", but here is the error that i am getting:
The error is:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again.
The error is on:
cmd.ExecuteNonQuery();
on this function:
private void AddDatabase(object sender, EventArgs e)
{
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "INSERT INTO [Table] ([ProductCode], [Description], [Price]) VALUES (#ProductCode, #Description, #Price)";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.Add("#ProductCode", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#ProductCode"].Value = this.numericTextBox1.Text;
cmd.Parameters.Add("#Description", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Description"].Value = this.textBox3.Text;
cmd.Parameters.Add("#Price", System.Data.OleDb.OleDbType.Integer);
cmd.Parameters["#Price"].Value = this.textBox4.Text;
cmd.ExecuteNonQuery(); // The error is here
if (_choice.comboBox1.Text == "English")
{
System.Media.SoundPlayer _sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Exclamation.wav");
_sound.Play();
DialogResult _dialogResult = MessageBox.Show("Added Successfully!", "Success", MessageBoxButtons.OK);
if (_dialogResult == DialogResult.OK)
{
ViewDatabase(sender, e);
ClearTextBoxes(sender, e);
}
}
}
conn.Close();
}
}
I wanted to when user type the same "Product Code", the messagebox will appear that the typed "Product Code" is not allowed because it is exists on the database and not give an error (terminate the program from running).
How do i fix it?
Thank you
Your answer will be great appreciated!
The error you're getting is quite normal. You can't insert duplicates into the primary key (nor can they contain 'NULL') column. More info about primary keys:
W3schools - primary key
database.about.com
Before executing AddDatabase you should be checking whether the key is already present in the database. you can do this in many different ways.
Execute a select on the database
SELECT TOP 1 ProductCode FROM Table WHERE ProductCode = 'this.numericTextBox1.Text'"
If this query produces a result, then the productcode is already present in the database and the query should Not be executed
Check the datasource of your datagridview
As datasource for your datagridview, you're probably supplying a List/Dataset. You can check your list for the existance of your newly entered ProductCode. You could use link here or just iterate the source. (whatever floats your boat)
If you can give me the type of datasource then i might supply a code example
Check your Datagridview
If your datagridview contains all the records of the database then you can iterate the the rows and check if the first column contains an productcode equal to the newly entered product code.
something among the lines of
foreach (DataGridViewRow row in dgvDataGridView.Rows)
{
if(row.Cells[0].Value.toString().equals(this.numericTextBox1.Text))
{
// Productcode is already present
// Throw message/exception Or whatever
break;
}
}
I would opt for option 1, as you datagridview/datasource may not show/keep all records from Table
Before executing INSERT you can check if database is already contains ProductCode (which seems to be a key in your table).
Something like (copy/paste code from one of my projects, but should be clear)
var command = new OleDbCommand("SELECT COUNT(*) FROM results WHERE id = ?", _connection);
command.Parameters.Add("id", OleDbType.Date).Value = id;
if ((int)command.ExecuteScalar() == 0)
{
// not exists
}
Suggestion: do not make AddDatabase an event handler, but create a separate class to handle database operations, make method AddDatabase there and call it from event handler.
You could have 2 methods then Exists(id) and Add(...), so in the event you can do simple duplicate check:
if(Database.Exists(id))
{
// show errror
return;
}
DataBase.Add(...);
If your error is
an unhandled exception of type 'system.data.oledb.oledbexception' occurred in system.data.dll additional information: Overflow
The cloumn in DB is little for note or digits
Please change cloumn format to bigger
Number ----> integer upper to double
Tanks