Update command for data table in C# not working - c#

I am relatively new to the world of databases and C# and I am having a problem getting my data tables to update according to changes I make via a C# program. I am using a TableAdapter to issue commands to the database.
In my program I have a form that allows a new row to be added to the data table. As far as I can tell this works, because the rest of my program can access the new information by querying the database.
this.patientInfoTableTableAdapter.InsertNewPatient(
this.FirstName, this.LastName, this.StreetAddress, this.City, this.State, this.Zip,
this.Email, this.Phone, this.DOB, this.Gender);
I can even stop the run of the program and restart it, and the added data is still accessible. However, when I view the data table directly, the added row is not there and the next time I run the program the table has reverted to the unmodified state in the program's eyes as well.
I do have an Update method that I use every time I go through this process, but it has no effect, either on retaining the added row or any changes to the existing rows:
this.Validate();
this.patientInfoTableBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.eMRSDatabaseDataSet);
MessageBox.Show("Update Successful");
I always see the MessageBox appear and I do not get any errors.
I have come to the conclusion that some setting or property for my database is amiss, and I could use some help figuring out my problem.
In case it helps, the database queries for the involved code follow:
INSERT INTO [PatientInfoTable] ([First_Name], [Last_Name], [Street_Address], [City], [State], [Zip], [Email], [Phone], [DOB], [Gender]) VALUES (#fName, #lName, #sAddress, #city, #state, #zip, #email, #phone, #dob, #gender)
and
UPDATE PatientInfoTable
SET Street_Address = #saddress, City = #city, State = #state, Zip = #zip, Email = #email, Phone = #phone, Gender = #gender
WHERE (Patient_ID = #p11)
These queries were generated using the Visual Studio query builder.
I would greatly appreciate any suggestions!

query = "Update mcm_class Set class_status='" +
dgv.Rows[i].Cells[1].ToString() + "' where class_id ='" +
dgv.Rows[i].Cells[0].ToString() + "'"+ "AND"+" med_id='" +
lst_med.SelectedValue.ToString() + "'";
cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();

Related

Getting a "System.Data.SQLite.SQLiteException: SQL logic error" while trying to add rows to my database with SQLite C#

So I'm trying to insert a new row into my database with SQLite3, and for some reason I'm getting a SQL logic error.
Database dbObject = new Database();
string query = "INSERT INTO info ('firstName, lastName, email') VALUES (#firstName, #lastName, #email";
SQLiteCommand myCommand = new SQLiteCommand(query, dbObject.Connection); //Opens chain of commands
dbObject.OpenConnection();
myCommand.Parameters.AddWithValue("#firsName", "blank name");
myCommand.Parameters.AddWithValue("#lastName", "blank last name");
myCommand.Parameters.AddWithValue("#email", "blank#gmail.com");
var result = myCommand.ExecuteNonQuery();
dbObject.CloseConnection();
Console.WriteLine("Rows added: {0}", result);
Console.ReadKey();
Can someone please tell me what am I doing wrong? Thank you!
Your query misses bracket at the end (after #email).
Moreover, I am not sure about the single quotes you added between firstName and email. I think they should be removed.
"INSERT INTO info (firstName, lastName, email) VALUES (#firstName, #lastName, #email)";
And as a side note that is not relevant to the error, you also need to dispose SQLiteCommand class as it is not disposed by itself. You can do it with using statement.

Get the recent ID and insert it to another table in ASP.NET

Please help - I'm creating a simple register from I'm trying to get the userID and insert the UserID from User table into the Employee table. I get an error at the line
newID = (int)cmd.ExecuteScalar();
My User table has a primary key UserID, the Employee table has a column UserID as foreign key.
Thank you in advance!
Here is my register.cs
// instantiate
using (SqlConnection con = new SqlConnection(Helper.GetCon()))
{
int newID;
string query = #"INSERT INTO Users VALUES (#TypeID, #EmployeeId, #Username, #Password, #SecurityQuestion1, #SecurityAnswer1, #SecurityQuestion2, #SecurityAnswer2, #DateModified);SELECT CAST(scope_identity() AS int";
con.Open();
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#TypeID", ddlUserTypes.SelectedValue);
cmd.Parameters.AddWithValue("#Username", txtUsername.Text);
cmd.Parameters.AddWithValue("#Password", Helper.CreateSHAHash(txtPW.Text));
cmd.Parameters.AddWithValue("#SecurityQuestion1", ddlSec1.SelectedValue);
cmd.Parameters.AddWithValue("#SecurityAnswer1", txtSecAns1.Text);
cmd.Parameters.AddWithValue("#SecurityQuestion2", ddlSec2.SelectedValue);
cmd.Parameters.AddWithValue("#SecurityAnswer2", txtSecAns2.Text);
cmd.Parameters.AddWithValue("#DateModified", DateTime.Now);
cmd.ExecuteNonQuery();
newID = (int)cmd.ExecuteScalar();
con.Close();
}
string query2 = #"INSERT INTO Employees VALUES (#FirstName, #MiddleName, #LastName, #EmployeeNumber, #Gender, #Birthdate, #Birthplace, #Nationality, #CivilStatus, #PermamentAddress, #PresentAddress, #ContactNumber, #Email, #Position, #Department, #Designation, #DateHired, #EmploymentStatus, #TIN, #SSS, #HDMF, #PHIC, #Supervisor, #Remarks, #Photo, #Attachments, #DateModified)";
using (SqlCommand cmd = new SqlCommand(query2, con))
{
cmd.Parameters.AddWithValue("#FirstName", txtFN.Text);
cmd.Parameters.AddWithValue("#MiddleName", txtMD.Text);
cmd.Parameters.AddWithValue("#LastName", txtLN.Text);
cmd.Parameters.AddWithValue("#EmployeeNumber", txtEmpNo.Text);
cmd.Parameters.AddWithValue("#Gender", ddlGender.SelectedValue);
cmd.Parameters.AddWithValue("#Birthdate", txtbdate.Text);
cmd.Parameters.AddWithValue("#Birthplace", txtBP.Text);
cmd.Parameters.AddWithValue("#Nationality", txtNat.Text);
cmd.Parameters.AddWithValue("#CivilStatus", ddlCIv.SelectedValue);
cmd.Parameters.AddWithValue("#PermamentAddress", txtPermAdd.Text);
cmd.Parameters.AddWithValue("#PresentAddress", txtPreAdd.Text);
cmd.Parameters.AddWithValue("#ContactNumber", txtContactNo.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#Position", txtPosi.Text);
cmd.Parameters.AddWithValue("#Department", txtDept.Text);
cmd.Parameters.AddWithValue("#Designation", txtDesig.Text);
cmd.Parameters.AddWithValue("#DateHired", txtdateh.Text);
cmd.Parameters.AddWithValue("#EmploymentStatus", txtEmpl.Text);
cmd.Parameters.AddWithValue("#TIN", txtTin.Text);
cmd.Parameters.AddWithValue("#SSS", txtSSS.Text);
cmd.Parameters.AddWithValue("#HDMF", txtPhilH.Text);
cmd.Parameters.AddWithValue("#PHIC", txtPag.Text);
cmd.Parameters.AddWithValue("#Supervisor", txtSuper.Text);
cmd.Parameters.AddWithValue("#Remarks", txtRemarks.Text);
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss-") + fuImage.FileName;
cmd.Parameters.AddWithValue("#Photo", fileName);
fuImage.SaveAs(Server.MapPath("~/EmployeeData/Images/" + fileName));
string attachments = DateTime.Now.ToString("yyyyMMddHHmmss-") + fuAttach.FileName;
cmd.Parameters.AddWithValue("#Attachments", attachments);
fuAttach.SaveAs(Server.MapPath("~/EmployeeData/Attachments/" + attachments));
cmd.Parameters.AddWithValue("#DateModified", DateTime.Now);
cmd.ExecuteNonQuery();
con.Close();
}
}
I'm not sure how this code gets an error at the line you're saying it happens, since I'd expect an error.at the line before the one mentioned. Here are a variety of tips, too long for a comment. I hope they sort out the problem, and if they dont, then the first point will help you get to the answer.
When asking for help about an error, please post the error that you got. This is the most important thing about diagnosing an error.
The line before the error is cmd.ExecuteNonQuery(), which will execute the command, inserting the record. Then you do cmd.ExecuteScalar(), which will execute the command again, inserting another record. Remove the cmd.ExecuteNonQuery(), since you need the identity value back from ExecuteScalar.
I'm not sure how the cmd.ExecuteNonQuery() works (it must do, unless you are mistaken in telling us that it crashes on the next line), since there is a typo in the query, missing the close bracket from the end SELECT CAST(scope_identity() AS int.
Please Can we stop using AddWithValue.
There's no need to Close the connection (ever), since it's in a using block. When it exits that block, the implicit Dispose will call Close.
Consider adding a Transaction. You are doing two separate inserts. If the second one fails, you will be left with the first record in the database. If you use a transaction around both commands, then either they both get in, or neither get in.
You're passing #DateModified the value DateTime.Now, which is a 'Local' time (look at the Kind property). When you read the value back from SQL, unless you call SpecifyKind, it won't be a local time, leading to discrepancies. Safer to always store and read the value as UTC (by using DateTime.UtcNow here, and SpecifyKind UTC when you read it) or switch to using DateTimeOffset.

Number of query values and destination fields are not the same OLEDB

I getting an error while i'm trying to insert data to my DB.
This is the error.
"System.Data.OleDb.OleDbException: 'Number of query values and destination fields are not the same.'".
cmd.CommandText = "INSERT INTO [clients]([Firstname],[Lastname],[Email],[Phonenumber],[Address],[CNP],[SeriesCI],[NumberCI],[Sex],[CUI],[J],[Personaldescription],[Temperament],[Provenance],[Registerdata],[Idteam],[NumeAgent])" +
"Select #f,#l,#e,#ph,#add,#cnp,#ser,#n,#sex,#cui,#j,#pd,#te,#prov,#reg,team.[id] from team where team.[Email]=#email,#agent";
cmd.Parameters.AddWithValue("#f", materialSingleLineTextField16.Text);
cmd.Parameters.AddWithValue("#l", materialSingleLineTextField15.Text);
cmd.Parameters.AddWithValue("#e", materialSingleLineTextField14.Text);
cmd.Parameters.AddWithValue("#ph", materialSingleLineTextField13.Text);
cmd.Parameters.AddWithValue("#add", materialSingleLineTextField6.Text);
cmd.Parameters.AddWithValue("#cnp", materialSingleLineTextField1.Text);
cmd.Parameters.AddWithValue("#ser", materialSingleLineTextField3.Text);
cmd.Parameters.AddWithValue("#n", materialSingleLineTextField2.Text);
cmd.Parameters.AddWithValue("#sex", gender);
cmd.Parameters.AddWithValue("#cui", materialSingleLineTextField4.Text);
cmd.Parameters.AddWithValue("#j", materialSingleLineTextField5.Text);
cmd.Parameters.AddWithValue("#pd", richTextBox2.Text);
cmd.Parameters.AddWithValue("#te", bunifuDropdown1.selectedValue);
cmd.Parameters.AddWithValue("#prov", bunifuDropdown2.selectedValue);
cmd.Parameters.AddWithValue("#reg", DateTime.Now.ToString("dd-MM-yyyy HH: mm:ss"));
cmd.Parameters.AddWithValue("#email", Form1.Email);
cmd.Parameters.AddWithValue("#agent", NumeAgent);
In DB (clients) i have 17 columns + id (but the id is auto increment).
What am I doing wrong?
clients
team
cmd.CommandText = "INSERT INTO [clients]([Firstname],[Lastname],[Email],[Phonenumber],[Address],[CNP],[SeriesCI],[NumberCI],[Sex],[CUI],[J],[Personaldescription],[Temperament],[Provenance],[Registerdata],[NumeAgent],[Idteam])" + "Select #f,#l,#e,#ph,#add,#cnp,#ser,#n,#sex,#cui,#j,#pd,#te,#prov,#reg,[Firstname]+' '+[Lastname] from team where [Email]=#email,team.[id] from team where team.[Email]=#email";
Try changing your INSERT statement like this:
cmd.CommandText = "INSERT INTO [clients]([Firstname],[Lastname],[Email],[Phonenumber],[Address],[CNP],[SeriesCI],[NumberCI],[Sex],[CUI],[J],[Personaldescription],[Temperament],[Provenance],[Registerdata],[Idteam],[NumeAgent])" +
"Select #f,#l,#e,#ph,#add,#cnp,#ser,#n,#sex,#cui,#j,#pd,#te,#prov,#reg,team.[id],#agent from team where team.[Email]=#email";
Note, I have moved the ,#agent part from the end of WHERE clause to the end of SELECT field list.
However, I'm not sure your overall idea is correct. If you are selecting values to be inserted from the team table, why to also specify them as Command parameters?

C# updating entries and passing columns in an SQL database

I need to make my code for where the data is inserted into 'Class_1' there are actually 3 score columns (Score_1, Score_2, Score_3) as the application I am building requires the database to keep a record of the last three entered scores. The problem with the code is that every time the data is added it will create a new entry and so what I need the program to do is check to see if the First_Name and Last_Name are present in another entry and if so, update that entry, then what I would like to do is check to see if score_1 has a value present and of course if this is true, skip score_1 and input the data into score_2 but I am completely new to C# so any help here would be much appreciated!, Thankyou!
if(inpClassNumber.Text == "Class 1")
{
con = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Program Files (x86)\Flux Infusion\Projects\Primary School Quiz System\Primary School Quiz System\Scores.mdf; Integrated Security = True");
con.Open();
cmd = new SqlCommand("INSERT INTO Class_1 (First_Name,Last_Name,Score_1) VALUES (#First_Name,#Last_Name,#Score)", con);
cmd.Parameters.AddWithValue("#First_Name", txtFirstName.Text);
cmd.Parameters.AddWithValue("#Last_Name", txtLastName.Text);
cmd.Parameters.AddWithValue("#Score", lblScore.Text);
cmd.ExecuteNonQuery();
}
If you are running SQL Server 2008 or newer you can use a MERGE TSQL:
MERGE Class_1 AS target
USING (SELECT #First_Name, #Last_Name, #Score) AS source (fName, lName, score)
ON (target.First_Name = source.fName and target.Last_Name = source.lName)
WHEN MATCHED THEN
UPDATE SET
Score_1 = #Score,
Score_2 = Score_1,
Score_3 = Score_2
WHEN NOT MATCHED THEN
INSERT (First_Name, Last_Name, Score_1)
VALUES (#First_Name, #Last_Name, #Score);
.
The above code keeps the most recent score in column Score_1, the second most recent in Score_2, and so on.
Here is the link to the TSQL documentation.

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