How to use LAST_INSERT_ID() in c# windows form? - c#

In database I have three tables-
patient(patientID,fName,lName)
illness(diseaseID,diseaseName)
patientDisease(patientID, diseaseID, dateChecked)
patientID and diseaseID are index.
So on in c# I have three textboxes fNameTxt and lNameTXT, diseaseTxt.I want to store the name in patient table and disease name in illness table. Besides, I have to record patientID and diseaseID in patientDisease table as well. For patient table, I used following code. I knew, I can use
SET #variable = LAST_INSERT_ID()
to get the id, but realised c#(visual studio) doesnt recognize it. Basically, I couldnt make the overall statement. Could anybody help me to get through this condition please.
string connStr = #"server=localhost; DATABASE=mario;User ID=root;Password=;";
MySqlConnection conn1 = new MySqlConnection();
conn1.ConnectionString = connStr;
MySqlCommand cmd = conn1.CreateCommand();
cmd.CommandText = "INSERT INTO patient(patientID,fName, lName)"
+ "Values("NULL",'" + fNameTxt.Text + "','" + lNameTxt.Text + "');";
conn1.Open();
cmd.ExecuteNonQuery();
I searched some other questions here, but they are almost about suggesting the use of LAST_INSERT_ID() but not how to use it.

It will be much better if you use stored procedures
INSERT INTO patient (patientID,patientID,lName)
VALUES("NULL",'" + fNameTxt.Text + "','" + lNameTxt.Text + "');
SET #last_id_in_patient = LAST_INSERT_ID();
INSERT INTO patientDisease (patientID,diseaseID,dateChecked)
VALUES( #last_id_in_patient ,NULL,'text'); # use ID in second table";
Now You can update your PatientDisease table for particular PatientId.

You can use this to get the last inserted id:
"SELECT * FROMtable(column) WHERE id = last_insert_id();
And use this if you want to insert a last id:
"INSERT INTO table(column) VALUES (LAST_INSERT_ID())";
Hope this might be useful.

Related

Update and delete rows from an access database don't work in a windows forms app

i create a database with access and used this database in an Windows forms app.
I can select and insert rows from the database but i can't delete and update the database.
I used the following code. The first part works, the second doesen't.
if (!string.IsNullOrEmpty(this.txb_Box.Text) && !string.IsNullOrEmpty(this.txb_Teil.Text))
{
this.select = "SELECT * FROM Lagerhaltung WHERE BoxNr='"+ this.txb_Box.Text+"' AND Reklamation='"+this.txb_Teil+"'";
DbCommand command2 = connection2.CreateCommand();
command2.CommandText = this.select;
DbDataReader reader2 = command2.ExecuteReader();
if(!reader2.HasRows)
{
this.select = "INSERT INTO Lagerhaltung ( BoxNr, Reklamation, EingelagertAm, Artikelnr) VALUES ('" + this.txb_Box + "','"+this.txb_Teil.Text+"','" + this.lbl_Datum.Text + "', 'Test')";
}
}
"UPDATE Lagerhaltung SET AusgelagertAm='"+this.lbl_Datum.Text+"', Erledigt= True WHERE id like '"+data.id+"'";
"DELETE FROM Lagerhaltung WHERE id like '1'";
Can someone help me?
Best regards
JuRi-2020
I find the mistake. I don't activate the command with
command.ExecuteNonQuery();
that's why nothing happened.

How do I make a foreign key in one of my databases copy the primary key that it is referencing to while I create a record? [duplicate]

I have a query to insert a row into a table, which has a field called ID, which is populated using an AUTO_INCREMENT on the column. I need to get this value for the next bit of functionality, but when I run the following, it always returns 0 even though the actual value is not 0:
MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertInvoice;
comm.CommandText += "\'" + invoiceDate.ToString("yyyy:MM:dd hh:mm:ss") + "\', " + bookFee + ", " + adminFee + ", " + totalFee + ", " + customerID + ")";
int id = Convert.ToInt32(comm.ExecuteScalar());
According to my understanding, this should return the ID column, but it just returns 0 every time. Any ideas?
EDIT:
When I run:
"INSERT INTO INVOICE (INVOICE_DATE, BOOK_FEE, ADMIN_FEE, TOTAL_FEE, CUSTOMER_ID) VALUES ('2009:01:01 10:21:12', 50, 7, 57, 2134);last_insert_id();"
I get:
{"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 'last_insert_id()' at line 1"}
MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertStatement; // Set the insert statement
comm.ExecuteNonQuery(); // Execute the command
long id = comm.LastInsertedId; // Get the ID of the inserted item
[Edit: added "select" before references to last_insert_id()]
What about running "select last_insert_id();" after your insert?
MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertInvoice;
comm.CommandText += "\'" + invoiceDate.ToString("yyyy:MM:dd hh:mm:ss") + "\', "
+ bookFee + ", " + adminFee + ", " + totalFee + ", " + customerID + ");";
+ "select last_insert_id();"
int id = Convert.ToInt32(comm.ExecuteScalar());
Edit: As duffymo mentioned, you really would be well served using parameterized queries like this.
Edit: Until you switch over to a parameterized version, you might find peace with string.Format:
comm.CommandText = string.Format("{0} '{1}', {2}, {3}, {4}, {5}); select last_insert_id();",
insertInvoice, invoiceDate.ToString(...), bookFee, adminFee, totalFee, customerID);
Use LastInsertedId.
View my suggestion with example here: http://livshitz.wordpress.com/2011/10/28/returning-last-inserted-id-in-c-using-mysql-db-provider/
It bothers me to see anybody taking a Date and storing it in a database as a String. Why not have the column type reflect reality?
I'm also surprised to see a SQL query being built up using string concatenation. I'm a Java developer, and I don't know C# at all, but I'd wonder if there wasn't a binding mechanism along the lines of java.sql.PreparedStatement somewhere in the library? It's recommended for guarding against SQL injection attacks. Another benefit is possible performance benefits, because the SQL can be parsed, verified, cached once, and reused.
Actually, the ExecuteScalar method returns the first column of the first row of the DataSet being returned. In your case, you're only doing an Insert, you're not actually querying any data. You need to query the scope_identity() after you're insert (that's the syntax for SQL Server) and then you'll have your answer. See here:
Linkage
EDIT: As Michael Haren pointed out, you mentioned in your tag you're using MySql, use last_insert_id(); instead of scope_identity();

String or binary data would be truncated. SQL Statements in C#

SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Server=; Database=; User id=; password=";
conn.Open();
string Query = "Insert into [Capstone0480].[dbo].[NAME] (NameID, FirstName, MI, LastName, UserID) Values('" + this.txtNameID.Text + "','" + txtFirst.Text + "','" + txtMI.Text + "','" + txtLast.Text + "', '" + txtUserID.Text + "')";
SqlCommand createCommand = new SqlCommand(Query, conn);
createCommand.ExecuteNonQuery();
MessageBox.Show("Updated");
conn.Close();
I have been getting this error on the ExecuteNonQuery() statement. I am not sure what is wrong here. I feel as if my sql statements are correct. I am just trying to add what is typed into textboxes into my database.
If there is a better way of doing this or if there is something wrong, please let me know!
One of the columns in your NAME table is shorter than the values you are trying to insert into it.
Try trimming the length of your name textboxes before you insert them into the database, or alternatively increase the length of your database columns.
For example:
If your FirstName Column is varchar(20)
then:
var firstName = txtFirst.Text.Length > 20 ? txtFirst.Text.Substring(0,20) : txtFirst.Text;
then insert the value of firstName into your SQL statement.
In addition, you should set the max length of your Textbox to be no more than the size of your columns.
The error suggest, that your input data length is more than the column length you define in database table.
suppose the column is like
TableName1
ColumnName1 varchar(50)
and now when you want to insert 51 or more character length input string, at that time the Sqlserver gives error. check this sample example.
declare #t table (name varchar(5))
insert into #t values('abc')
select * from #t
insert into #t values('abcdefg') --this gives error as you insert more than define length.
Please check at run-time what is the input string.
Good if you restrict your textbox to insert only the database column length like
<input type="textbox" maxlength="50" />

Inserting values into table from textboxes & from another table's foreign key C#

Im trying to insert into a table values from textboxes AND to retrieve a foreign key id from another table and insert that also.
So I have a users table which contains UserId and I want this inserted into a nutrition diary which includes all the data that comes from textboxes(ie Weight, Height, Date etc)
I am retrieving the MemberId by using a session to track the username(lblRegistered)
Here is my code:
SqlConnection con = new SqlConnection("path for my connection");
con.Open();
SqlCommand cmd = new SqlCommand("select COUNT(*)FROM Members where Username='" + lblRegistered.Text + "'", con);
con.Close();
con.Open();
cmd.CommandText = "INSERT INTO Nutrition(Weight, Height, Bmi, Date, WaterIntake, CalorieIntake, MemberId) values ('" + txtWeight.Text + "','" + txtHeight.Text + "','" + txtBmi.Text + "','" + txtDate.Text + "','" + txtWater.Text + "','" + txtCalorie.Text + "', Select Users.UserId From Users where (Users.Username= '" + lblRegistered.Text + "'))";
cmd.ExecuteNonQuery();
cmd.Clone();
con.Close();
Response.Redirect("Success.aspx");
The error is close to Select Users part.
Any help would be greatly appreciated!
First thing would be to read up on parameterized SQL queries. The code you have there is completely open to SQL injection attacks.
This is a good resource for that: http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html
Then for the problem you would be better off using a Stored Procedure to do the work. Something along the lines of :
CREATE PROCEDURE Nutrition_Insert
#weight varchar(10),
#height varchar(10),
#bmi varchar(10),
#date varchar(10),
#username varchar(10),
//etc for your fields
AS BEGIN
DECLARE #memberId varchar(10)
SELECT #memberId = UserId From Users where Username = #username
INSERT INTO Nutrition(Weight, Height, Bmi, Date, WaterIntake, CalorieIntake, MemberId)
values (#weight, #height, #bmi, ....., #memberId)
END
Note - I've made some assumptions there as I don't know your data types, they all look like strings, but not knowing the size of the varchar used, I picked an arbitary value. Replace the (10) with the actual field size.
If you must use embedded SQL - then this is how you parameterize it. I've also fixed the insert statement to pull the MemberId from the Members table as part of the insert.
using (var conn = new SqlConnection("YOUR CONNECTION STRING"))
{
conn.Open();
using (
var cmd = new SqlCommand(
"INSERT INTO Nutrition(...fields...) SELECT #Weight, #Height, #Bmi,...., Members.MemberId FROM Members WHERE Members.Username = #Username", conn)
)
{
cmd.Parameters.AddWithValue("#Weight", txtWeight.Text);
cmd.Parameters.AddWithValue("#Height", txtHeight.Text);
...
cmd.Parameters.AddWithValue("#Username", lblRegistered.Text);
cmd.ExecuteNonQuery();
}
conn.Close();
}
You'll notice the using statements too. This will make sure your connection are disposed of cleanly.
Hope that helps.
Thanks Richard..that worked very well on the problem.
I am just trying to do the same technique on a different page but this time it will have 2 where clauses
var cmd = new SqlCommand("INSERT INTO AssignPlan(Reps, Sets, WeightOrTime, Date, MemberId, ExerciseId) Select #Reps, #Sets,#WeightOrTime,#Date, Members.MemberId From Members Where Members.Username=#name,ExerciseDisplay.ExerciseId From ExerciseDisplay Where ExerciseDisplay.ExerciseName=#Exercise", conn)
It's showing up an error from the syntax. Can this be achieved?

asp.net SQL Server insert statement tidyup + error

I have a form which inserts data into a database.
There are certain fields that are not always going to be needed.
When I leave these blank in my code I get a error saying.
Column name or number of supplied values does not match table
definition.
This is how I have the database setup. SQL Server 2008
[youthclubid]
[youthclubname]
[description]
[address1]
[address2]
[county]
[postcode]
[email]
[phone]
Here is the code that I have connecting to the database and doing the insert.
connection.Open();
cmd = new SqlCommand("insert into youthclublist values ('" + youthclubname.Text + "', '" + description.Text + "','" + address1.Text + "','" + address2.Text + "', '" + county.Text + "', '" + postcode.Text + "', '" + email.Text + "', '" + phone.Text + "')", connection);
cmd.ExecuteNonQuery();
You have two major problems:
1) concatenating together your SQL statement is prone to SQL injection attacks - don't do it, use parametrized queries instead
2) You're not defining which columns you want to insert in your table - by default, that'll be all columns, and if you don't provide values for all of them, you'll get that error you're seeing.
My recommendation: always use a parametrized query and explicitly define your columns in the INSERT statement. That way, you can define which parameters to have values and which don't, and you're safe from injection attacks - and your performance will be better, too!
string insertStmt =
"INSERT INTO dbo.YouthClubList(Youthclubname, [Description], " +
"address1, address2, county, postcode, email, phone) " +
"VALUES(#Youthclubname, #Description, " +
"#address1, #address2, #county, #postcode, #email, #phone)";
using(SqlConnection connection = new SqlConnection(.....))
using(SqlCommand cmdInsert = new SqlCommand(insertStmt, connection))
{
// set up parameters
cmdInsert.Parameters.Add("#YouthClubName", SqlDbType.VarChar, 100);
cmdInsert.Parameters.Add("#Description", SqlDbType.VarChar, 100);
.... and so on
// set values - set those parameters that you want to insert, leave others empty
cmdInsert.Parameters["#YouthClubName"].Value = .......;
connection.Open();
cmdInsert.ExecuteNonQuery();
connection.Close();
}
The first major issue is that you are concatenating inputs in the query. This makes your application highly vulnerable to SQL Injection. Do not do this. Use a parametrized query.
The regular syntax for insert statement is like this:
Insert into <TableName> (Col1, Col2...Coln) values (val1, val2...valn)
If you need to insert only a selected set of columns, you need to provide the list of columns you are inserting data into in the column list.
If you do not specify the column list, the indication is that you are inserting data to each one of them.
So you may check for the input and if it is not there, you may omit the respective column.
The other better way is use a stored proc. That will ease out the issue.
This not way to do the code you make use of SqlParameter for this kind of statement.
So your code something like
SqlConnection thisConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Northwind_ConnectionString"].ConnectionString);
//Create Command object
SqlCommand nonqueryCommand = thisConnection.CreateCommand();
try
{
// Create INSERT statement with named parameters
nonqueryCommand.CommandText = "INSERT INTO Employees (FirstName, LastName) VALUES (#FirstName, #LastName)";
// Add Parameters to Command Parameters collection
nonqueryCommand.Parameters.Add("#FirstName", SqlDbType.VarChar, 10);
nonqueryCommand.Parameters.Add("#LastName", SqlDbType.VarChar, 20);
nonqueryCommand.Parameters["#FirstName"].Value = txtFirstName.Text;
nonqueryCommand.Parameters["#LastName"].Value = txtLastName.Text;
// Open Connection
thisConnection.Open();
nonqueryCommand.ExecuteNonQuery();
}
catch (SqlException ex)
{
// Display error
lblErrMsg.Text = ex.ToString();
lblErrMsg.Visible = true;
}
finally
{
// Close Connection
thisConnection.Close();
}
You need to tell SQL server that which field you want to insert like
insert into youthclublist(youthclubid, youthclubname, ....) values ('" + youthclubname.Text + "', '" + description.Text + "'.....
and you are fine.
Though new into programming, the easiest way i know to insert into a database is to create a "save" stored procedure, which is then called up through your connection string. Believe me, this is the best way.
Another way around is to use LINQ to SQL. i found this much more easier. Follow this steps.
Add a new LINQ to SQL Classes to your project. Make sure the file extension is '.dbml'. Name it your name of choice say "YouthClub.dbml"
Connect your Database to Visual Studio using the Server Explorer
Drag your table to the OR Designer.(I'm not allowed to post images).
You can now save to the Database with this code
//Create a new DataContext
YouthClubDataContext db = new YouthClubDataContext();
//Create a new Object to be submitted
YouthClubTable newYouthClubRecord = new YouthClubTable();
newYouthClubRecord.youthlubname = txtyouthclubname.Text;
newYouthClubRecord.description = txtdescription.Text;
newYouthClubRecord.address1 = txtaddress1.Text;
newYouthClubRecord.address2 = txtaddress2.Text;
newYouthClubRecord.county = txtcounty.Text;
newYouthClubRecord.email = txtemail.Text;
newYouthClubRecord.phone = txtphone.Text;
newYouthClubRecord.postcode = txtpostcode.Text;
//Submit to the Database
db.YouthClubTables.InsertOnSubmit(newYouthClubRecord);
db.SubmitChanges();
Hope this time I have given a real answer

Categories