SqlCeCommand command = new SqlCeCommand(#"INSERT INTO fpl_table
(FLIGHT_ID, BPN_TIME, BPX_TIME, DAY_NB)
VALUES (#FLIGHT_ID, #BPN_TIME, #BPX_TIME, #DAY_NB)
ON DUBLICATE UPDATE FLIGHT_ID = #FLIGHT_ID, BPN_TIME=#BPN_TIME,BPX_TIME=#BPX_TIME,DAY_NB=#DAY_NB"
,connection);
command.Parameters.AddWithValue("FLIGHT_ID", format);
command.Parameters.AddWithValue("BPN_TIME", format1);
command.Parameters.AddWithValue("BPX_TIME", format2);
command.Parameters.AddWithValue("DAY_NB", format3);
Hi everyone!
Ive got the problem with inserting 4 values into columns. I wanna prevent inserting 4 existing columns into database, i cant set them unique, cause the same column can be inserted with other 1,2 or 3 columns, i just wanna prevent only 4 existing columns insert.
you can add a unique constraint on 4 columns
CONSTRAINT UC_unique UNIQUE (col1, col2, col3, col4)
https://www.w3schools.com/sql/sql_unique.asp
Why not you use a seperate function to find out duplicate records at first.
bool CheckDuplicateFlight(int FLIGHT_ID)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"YOURCONNECTION STRING";
con.Open();
if (con.State == System.Data.ConnectionState.Open)
{
SqlCeCommand cmd = new SqlCeCommand("select count(*) from YOURTABLE where FLIGHT_ID= #FLIGHT_ID", con);
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("#FLIGHT_ID",FLIGHT_ID);
int ExistingId= Convert.ToInt32(cmd.ExecuteScalar());
}
con.Close();
if(ExistingId> 0)
return true;
return false;
}
if(CheckDuplicateFlight(FLIGHT_ID))
{
///// Your insertion/Update Code here
}
But Your Question is confusing a bit, Are you sure you want to insert record instead of update??? Insert query always inserts new record.
You need to add Unique Constraints to 3 columns, and than using exception handling at your code, insert new record.
Related
Sorry for my vague-ish title. Basically, I have a Call Logging app that uses a database with 2 tables (Customer and Records) to add, remove and search for records. I have a column in Records called 'CallID' that I use to help keep the calls unique and so I can use the CallID to Remove specific records. However, the problem lies on my adding call function. I currently have it so that the CallID is the number of items in the list incremented by 1:
private void addcall_btn_Click(object sender, EventArgs e)
{
try
{
//This is my addcall click event that inserts a row in 'Records' table using what the user has entered into the fields
string sql = "INSERT Records (CustomerID, CallID, CustomerName, Telephone, DateAndTime, Status, Description) VALUES (#CustomerID, #CallID, #CustomerName, #Telephone, #DateAndTime, #Status, #Description)";
SqlConnection conn = ConnectionString();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Connection = conn;
cmd.Parameters.AddWithValue("CustomerID", customerID_cb.Text);
cmd.Parameters.AddWithValue("CallID", (CallListBox.Items.Count + 1));
cmd.Parameters.AddWithValue("DateAndTime", DateTime.Now);
cmd.Parameters.AddWithValue("Status", status_cb.Text);
cmd.Parameters.AddWithValue("Description", description_txt.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Record Created");
this.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
You probably know by now that simply incrementing one to the number of items in the list is a clumsy way of doing things and it leads to problems after records have been removed and you want to add more. I want to know if there is a way to do what I am trying to do but in a much better way :)
Thanks!
Set CallID to auto increment
ALTER TABLE Records AUTO_INCREMENT=1
Then change your insert statement so that it excludes the field
INSERT Records (CustomerID, CustomerName, Telephone, DateAndTime, Status, Description) VALUES (#CustomerID, #CustomerName, #Telephone, #DateAndTime, #Status, #Description)
The value for the CallID field will then be handled by the database for any subsequent rows added.
Proceed in this way(Incase if you're not using auto increment in database), it may help you.
Bind your last value into label or textbox,
SqlConnection con = new SqlConnection("Your Connection String");
con.Open();
SqlCommand cmd = new SqlCommand("Select Max(CallID) from Yourtablename",con);
SQlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
Label1.Text = dr.GetInt32(0).ToString();
}
con.Close();
Change like this in your above code,
cmd.Parameters.AddWithValue("CallID", Convert.ToInt32(Label1.Text));
Make a datatype to int of your CallID column.
Please let me know the further issues.
So I am trying to fetch a value from the database, selecting the row using WHERE INT.
conn = new MySqlConnection(DBdetails.connStr);
conn.Open();
query = "SELECT * FROM tables WHERE table=#tafel";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("#tafel", tafel);
cmd.ExecuteNonQuery();
However it wont pass 'cmd.ExecuteNonQuery()', it throws a error saying the syntax isnt right like: "near table=1", "near table=2"
I tried fetching a other one in the same table that is a var char and it worked perfectly.
Don't really see what I am doing wrong. The 'table' column is a int and 'tafel' is a int to.
Thanks!
Put your field name table in backticks (table is a reserved word in MySQL) :
query = "SELECT * FROM `tables` WHERE `table` = #tafel";
As others said, table is a reserved word in MySQL. You need to use quote with it like
query = "SELECT * FROM tables WHERE `table` = #tafel";
However, the best solution is to change the name to a nonreserved word.
Also use using statement to dispose your MySqlConnection and MySqlCommand like;
using(MySqlConnection conn = new MySqlConnection(DBdetails.connStr))
using(MySqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM tables WHERE `table` = #tafel";
cmd.Parameters.AddWithValue("#tafel", tafel);
conn.Open();
cmd.ExecuteNonQuery();
}
By the way, I don't understand why you use ExecuteNonQuery with SELECT statement. It just executes your query. It doesn't even return any value.
If you want to get the result of your query, you can use ExecuteReader method which returns SqlDataReader as your result rows.
I'm trying to make a program that copies data from one table to the other in other server.
The thing is table is not exactly same. So Let's say these are my tables:
Server A:
TableA (Col1, Col2, Col3)
Server B:
TableB (Col1, Col2)
I want to copy from ServerA.TableA to ServerB.TableB.
My code:
Truncate_table(ConnectionB, "TableB");
MySqlCommand CmdB = new MySqlCommand("", ConnectionB);
CmdB.CommandText = "INSERT INTO ServerB.TableB (col1, col2) VALUES (#val1, #val2)";
using (MySqlCommand cmd = new MySqlCommand("", ConnectionA))
{
cmd.CommandText = "SELECT col2, col3 FROM ServerA.TableA";
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
CmdB.Parameters.AddWithValue("#val1", reader.GetInt32(0));
CmdB.Parameters.AddWithValue("#val2", reader.GetInt32(1));
CmdB.ExecuteNonQuery();
}
}
}
However, it gives error saying 'Parameter '#val1' has already been defined.'.
Can you guys give me a piece of advice?
And is there more efficient way to do this? but I want to do this in C#.
Try adding the parameters once, then setting the value of those parameters within the while-loop:
MySqlCommand CmdB = new MySqlCommand("", ConnectionB);
CmdB.CommandText = "INSERT INTO ServerB.TableB (col1, col2) VALUES (#val1, #val2)";
CmdB.Parameters.AddWithValue("#val1", 0); // Default values
CmdB.Parameters.AddWithValue("#val2", 0);
using (MySqlCommand cmd = new MySqlCommand("", ConnectionA))
{
cmd.CommandText = "SELECT col2, col3 FROM ServerA.TableA";
using (MySqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
CmdB.Parameters["#val1"].Value = reader.GetInt32(0));
CmdB.Parameters["#val2"].Value = reader.GetInt32(1));
CmdB.ExecuteNonQuery();
}
}
}
Also, I could be wrong, but I believe you need to use ? to delimit parameters for MySql. If you have any other issues you might try replacing #val1 and #val2 with ?val1 and ?val2.
You are coping row by row the data. This is a very inefficient way to copy from a table to another. You can achieve the same result with a similar code executing just one INSERT on the database, you just need to read previously all the rows you want to insert.
Oh I just added
CmdB.Parameters.Clear();
After
CmdB.ExecuteNonQuery();
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get last inserted id?
I am trying to get the last id (Last value of an identity column) to show it on control incremented by 1 each time when data is inserted to table.
How to get this last id in a stored procedure in SQL Server 2005 using C#?
Identity columns are incremented in the database, not on the C# side. You can query for the last value like this:
SELECT MAX(id) FROM mytable
Either just grab the latest ID when the insert happens (using SCOPE_IDENTITY()), or if you need to check the current value of an IDENTITY column later on, use SELECT IDENT_CURRENT('table_name') to get that value.
So the easiest way is to just get the ID as you insert your values - something like this:
string sql = "INSERT INTO dbo.YourTable(Col1, ..., ColN) VALUES(#Val1, ..., #ValN); SELECT SCOPE_IDENTITY()";
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
_ID = (Int32)cmd.ExecuteScalar();
conn.Close();
}
Or if you cannot grab the ID as it's being inserted, you can always check later on what the current last used value of the IDENTITY column on a given table was, using something like this:
string sql = string.Format("SELECT IDENT_CURRENT('{0}');", yourTableName);
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
_ID = (Int32)cmd.ExecuteScalar();
conn.Close();
}
You can use this
SELECT ##IDENTITY AS 'Identity';
or this
SELECT MAX(SomeID) FROM SomeTable;
EDIT
Best way to use
SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]
and in C# you could call
Int32 _ID = 0;
//you could use second variant sql= "SELECT MAX(SomeID) FROM SomeTable";
string sql =
"SELECT ##IDENTITY AS 'Identity'";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
_ID = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
EDIT
Nice link to feel difference
Using ##IDENTITY and SCOPE_IDENTITY with triggers
SELECT TOP 1 Id FROM table_name ORDER BY 1 DESC
or in LINQ:
context.table.Select(x->x.Id).OrderByDescending(x->x.Id).FirstOrDefault();
This question already has answers here:
If Exists Update Else Insert with VB.net (sql parameterised query)
(3 answers)
Closed 9 years ago.
I have the following query:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
SqlCommand cmd = new SqlCommand("INSERT INTO Raspunsuri Values(#raspuns,#cnp,#data,'1',#ip,#idsesiune)", con);
cmd.Parameters.AddWithValue("#cnp", Session["sesiune_cnp"]);
cmd.Parameters.AddWithValue("#raspuns", textbox1.Text);
cmd.Parameters.AddWithValue("#data", DateTime.Now.ToLocalTime());
cmd.Parameters.AddWithValue("#ip",ip);
cmd.Parameters.AddWithValue("#idsesiune", id_sesiune);
try
{
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("User2.aspx");
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex);
}
finally
{
con.Close();
}
What i need is to see if there is any record in the table and if there is than update else insert it.How can I achieve that?
This is probably best done in a Stored Procedure due to the amount of scripting involved (it would be messy inline!).
Pass your parameters to a Stored Procedure and do something like:
IF EXISTS(SELECT cnp FROM Raspunsuri WHERE cnp=#cnp)
BEGIN
UPDATE ...
WHERE cnp=#cnp
END
ELSE
BEGIN
INSERT INTO....
END
Assuming #cnp is your Primary Key
Your SqlCommand would then be changed to:
SqlCommand cmd = new SqlCommand("sp_StoredProcedureName", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#cnp", Session["sesiune_cnp"]);
cmd.Parameters.AddWithValue("#raspuns", textbox1.Text);
cmd.Parameters.AddWithValue("#data", DateTime.Now.ToLocalTime());
cmd.Parameters.AddWithValue("#ip",ip);
cmd.Parameters.AddWithValue("#idsesiune", id_sesiune);
You can use the Exists function in SQL. For Example
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
SqlCommand cmd = new SqlCommand("if Exists(Select 1 from Raspunsuri where <your unique criteria>)\r\n" +
"Update Raspunsuri set <values you want to set> where <your unique criteria\r\n" +
"else\r\n" +
"INSERT INTO Raspunsuri Values(#raspuns,#cnp,#data,'1',#ip,#idsesiune)", con);
cmd.Parameters.AddWithValue("#cnp", Session["sesiune_cnp"]);
cmd.Parameters.AddWithValue("#raspuns", textbox1.Text);
cmd.Parameters.AddWithValue("#data", DateTime.Now.ToLocalTime());
cmd.Parameters.AddWithValue("#ip",ip);
cmd.Parameters.AddWithValue("#idsesiune", id_sesiune);
That should do the trick
You can use the ##ROWCOUNT feature from SQL Server.
UPDATE Raspunsuri SET (...) WHERE PrimaryKeyColumn='YourValue'
IF ##ROWCOUNT=0
INSERT INTO Raspunsuri VALUES (...)
Similar question: Insert / Update to Sql
What i need is to see if there is any record in the table and if there is than update else insert
it.How can I achieve that?
Write proper SQL?
Basiacll waht you need to forumlate is known as an "Upsert".
http://www.databasejournal.com/features/mssql/article.php/3739131/UPSERT-Functionality-in-SQL-Server-2008.htm
hasa good explanation.
First you check whether the record is present in the table by writing a query as "Select count(*) from tablename where columnvalue="something".If count is more than 0 then table has record.So in that case you write an Update statement else write Insert statement. This you can write in your code or by writing a stored procedure.
What i need is to see if there is any record in the table and if there
is than update else insert it.How can I achieve that?
I like #Alex's approach
-- For each row in source
BEGIN TRAN
UPDATE target
SET <target_columns> = <source_values>
WHERE <target_expression>
IF (##ROWCOUNT = 0)
INSERT target (<target_columns>)
VALUES (<source_values>)
COMMIT