string query = "UPDATE Completed_orders SET service=N'" + comboBox1.SelectedValue + "',kolvo=N'" + kol.Text + "',note=N'" + not.Text + "' WHERE orders='" + form3.ordersgrid.CurrentRow.Cells[0].Value.ToString() + "' ";
SqlCommand cmd = new SqlCommand(query, dataBase.getConnection());
dataBase.openConnection();
cmd.ExecuteNonQuery();
dataBase.closeConnection();
form3.serviceklient();
MessageBox.Show("Изменена");
this.Hide();
You try to add an occurence in a table when a record with the same id (primary key) already exist.
If it's possible for your project, I suggest you tu use a numeric ID with the autoincrement option :
CREATE TABLE `table_name` ( id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, [...] );
Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table.
When you insert a new record in the table, you don't have to specify the id.
Related
I have MySql Tables with autoinc ID columns, such as "director_id" here:
CREATE TABLE directors (
director_id Integer NOT NULL AUTO_INCREMENT,
first_name VarChar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
middle_name VarChar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci,
last_name VarChar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL,
suffix VarChar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci,
PRIMARY KEY (
director_id
)
)
I want to store the autoincremented director_id value in the movies_main Table.
So I try to assign the autoincremented value to an int variable:
long director_id = 0;
...in the call to LastInsertedId here (last line):
if (!alreadyExists)
{
comm.Parameters.Clear();
comm.CommandText = "INSERT INTO Directors " +
"(first_name, middle_name, last_name, suffix) " +
"VALUES " +
"(#first_name, #middle_name, #last_name, #suffix)";
comm.Parameters.AddWithValue("#first_name", directorNamePartsList[0]);
comm.Parameters.AddWithValue("#middle_name", directorNamePartsList[1]);
comm.Parameters.AddWithValue("#last_name", directorNamePartsList[2]);
comm.Parameters.AddWithValue("#suffix", directorNamePartsList[3]);
comm.ExecuteNonQuery();
director_id = comm.LastInsertedId;
}
...and then assign it to the movies_main Table like so:
if (!alreadyExists)
{
comm.Parameters.Clear();
comm.CommandText = "INSERT INTO Movies_Main " +
"(movie_title, mpaa_rating, imdb_rating, movie_length, director_id,
screenwriter_id, year_released) " +
"VALUES " +
"(#movie_title, #mpaa_rating, #imdb_rating, #movie_length, #director_id,
#screenwriter_id, #year_released)";
comm.Parameters.AddWithValue("#movie_title", title);
comm.Parameters.AddWithValue("#mpaa_rating", mpaa_rating);
comm.Parameters.AddWithValue("#imdb_rating", Math.Round(imdb_rating, 1));
comm.Parameters.AddWithValue("#movie_length", movie_length);
comm.Parameters.AddWithValue("#director_id", director_id);
comm.Parameters.AddWithValue("#screenwriter_id", screenwriter_id);
comm.Parameters.AddWithValue("#year_released", year_released);
comm.ExecuteNonQuery();
movie_id = comm.LastInsertedId;
}
Yet the value assigned to the movies_main Table for director_id is always 0!
Why is LastInsertId (apparently) returning 0, and how can I get it to actually return the value its name claims it does? Will I have to resort to a "SELECT MAX(director_id)" query to actually get the value?
NOTE: The movie_id code does work! I get a non-zero value when assigning the result of the call to LastInsertedId to the movie_id variable, and it is added to other tables just fine. This code works as expected:
foreach (var gen_desc in genreList)
{
long genreID = Convert.ToInt32(GetGenreIDForDescription(gen_desc));
alreadyExists = PairAlreadyExistsInMoviesGenresM2Mtable(
movie_id, genreID);
if (!alreadyExists)
{
comm.Parameters.Clear();
comm.CommandText = "INSERT INTO Movies_Genres " +
"(movie_id, genre_id) " +
"VALUES " +
"(#movie_id, #genre_id)";
comm.Parameters.AddWithValue("#movie_id", movie_id);
comm.Parameters.AddWithValue("#genre_id", genreID);
comm.ExecuteNonQuery();
}
}
An alternative way to LastInsertedId property from the MySqlCommand is the native MySql function LAST_INSERT_ID. We can call this function and get its return value adding a simple SELECT statement to your current command text. MySql supports batch statements and so, with a single server call we could execute more than one single command text.
if (!alreadyExists)
{
comm.Parameters.Clear();
comm.CommandText = "INSERT INTO Directors " +
"(first_name, middle_name, last_name, suffix) " +
"VALUES " +
"(#first_name, #middle_name, #last_name, #suffix); " + // semicolon to close the first statement
"SELECT LAST_INSERT_ID()";
comm.Parameters.AddWithValue("#first_name", directorNamePartsList[0]);
comm.Parameters.AddWithValue("#middle_name", directorNamePartsList[1]);
comm.Parameters.AddWithValue("#last_name", directorNamePartsList[2]);
comm.Parameters.AddWithValue("#suffix", directorNamePartsList[3]);
director_id = Convert.ToInt64(comm.ExecuteScalar());
}
Note that we can now use ExecuteScalar because we get back just one record with a single column.
Let me say however that I have tried to reproduce your problem with LastInsertedId. I have recreated your table and written a simple script in LinqPad trying to insert some fixed data in that table.
I have no problem with LastInsertedId property and I get the correct value. I have read that if you have more threads that are concurrently inserting records you could get some problems with that property but I have no proof of any kind of misbehaving
I have created two tables ItemList and Salt in SQL Server 2012.
I want to create a winforms application in C#.
Salt (parent table)
Salt_ID int NOT NULL, (primary Key)
Salt_Name var
ItemList (child table)
Item_ID int NOT NULL, (primary Key)
Salt_ID int NOT NULL, (foreign Key)
Item Name var
Combobox binding detail
Datasource = SaltBindingSource
DisplayMember = Salt_Name (from `Salt` table)
Value Member = Salt_ID (primary key)
Selected Value = itemListBindingSource-Salt_ID (Foreign Key in Child table)`
Now I want to insert combobox primary key data into child table foreign key column and my statement is that
(SqlCommand query = new SqlCommand("Insert into Itemlist(Item_Name,Packing,Salt_ID) values ('" + this.textBox1.Text + "','" + this.textBox2.Text + "','" + this.comboBox1.SelectedValue+ "')", con);)`
after this statement I get an error
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Conversion failed when converting the varchar value 'Salt_ID' to data type int.
So please tell me how to insert data into SQL Server database table foreign key column
Set these values to combobox:
classTeacher_Combobox.DisplayMember = "teacher_username";
classTeacher_Combobox.ValueMember = "teacher_id";
Insert into Class(item1,item2,teacher_id) values ('" + this.textBox1.Text + "','" + this.textBox2.Text + "','" + classTeacher_Combobox.SelectedValue + "')", con)
I Sql server i use this command to insert value and if the id already exist update the vale
string commandLine = "IF NOT EXISTS(SELECT clientid FROM Rating WHERE clientid = " + clientId + " AND userid = " + userid + ") " +
"INSERT INTO Rating VALUES(#clientId,#userid,#rating) " +
"ELSE " +
"UPDATE Rating SET rating=#rating WHERE clientid = " + clientId + " AND userid = " + userid + ";";
And i now move to MySQL and this command won't work. there is any thing same in MySQL?
The INSERT ... ON DUPLICATE KEY UPDATE provides an easier syntax in MySQL and also gives you feedback as to what was happening via the affected-rows API call. Few people realise in my experience how handy it can come in your program logic to know that:
With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if
the row is inserted as a new row, 2 if an existing row is updated, and
0 if an existing row is set to its current values.
If you have unique constraint or primary key on clientid, userid you can use INSERT ... ON DUPLICATE KEY UPDATE Syntax
INSERT INTO Rating VALUES(#clientId,#userid,#rating)
ON DUPLICATE KEY
UPDATE Rating SET rating=#rating
how to create table query in c# for mysql database..
MySqlConnection con = new MySqlConnection("Server=localhost;Database=demo_test;UID=root;Password= ");
MySqlCommand acmd = new MySqlCommand("CREATE TABLE first (" + a.Columns[0] + " int(20) NOT NULL auto_increment,'" + a.Columns[1].ToString() + "' varchar(100) NOT NULL default,PRIMARY KEY (" + a.Columns[0]+") 1", con);
con.Open();
acmd.ExecuteNonQuery();
it gives me an error
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ''name' varchar(100) NOT NULL default,PRIMARY KEY (id) 1' at line
1
Instead of fighting with SQL directly, you could use Mig# like this:
var schema = new DbSchema(ConnectionString, DbPlatform.MySql5);
schema.Alter(db => db.CreateTable("first")
.WithPrimaryKeyColumn(a.Colunns[0], DbType.Int32).AsIdentity()
...);
It's because you are wrapping the column names with single quote which converts the value into string and not an identifier anymore. Remove the single quotes and it will work.
string query = #"CREATE TABLE first (" + a.Columns[0] + " int(20) NOT NULL auto_increment, "
+ a.Columns[1].ToString() + " varchar(100) NOT NULL default,
PRIMARY KEY (" + a.Columns[0]+")"
At the moment I'm writing a small conversion program, it will convert the primary key strategy to the using of GUIDs in stead of integers. This is a simple client induced requirement and I can't change that.
I've added a substitute pk candidate of the RAW(16) to every table in the database and filled each record with a SYS_GUID().
I did the same for the FKs, I added a substitute column for each FK.
Now I'm in the process of linking the FKs to their PKs, by querying the parent table I get the guid/new key for the specific row, after that I want to insert into the substitute candidate FK in the child table.
Somewhat like this:
sqlString = "SELECT PK FROM " + t+ " WHERE " + fkcol+ " = " + childValue;
OracleDataReader guidReader = GetDataReader(sqlString);
while (guidReader.Read())
{
sqlString = "UPDATE T SET FK = " + guidReader["PK"];
}
Debugging this sqlString gets me the following value:
UPDATE SIS_T_USER SET FK_C_EMPLOYEE_ID
= System.Byte[]
Now, how do I go forth and save this as a nice guid in my oracle database?
EDit how:
OracleCommand command = new OracleCommand(sqlString, this.oracleConnection);
command.CommandType = CommandType.Text;
OracleParameter op1 = new OracleParameter("guid", OracleDbType.Raw);
op1.Value = guidReader["PK"];
command.Parameters.Add(op1);
try
{
command.ExecuteNonQuery();
}
catch (OracleException oex)
{
Console.WriteLine("Unable to update: {0}", oex.Message);
}
Why don't you just do this all on Oracle side?
MERGE
INTO sis_t_user s
USING employee e
ON (s.integer_fk = e.integer_pk)
WHEN MATCHED THEN
UPDATE
SET s.guid_fk = e.guid_pk
Try this code:
sqlString = "UPDATE T SET FK = '" + (new Guid((byte[])guidReader["PK"])).ToString() + "'";
Basically, you just need to create guid from bytes and then convert it to string.
There is Guid constructor that allows it: http://msdn.microsoft.com/en-us/library/90ck37x3(v=VS.100).aspx.