C# insert into Access database - c#

I have a simple user interface for an inventory database. The operation will be insert into, edit existing, view data grid, etc....There are a total of 4 fields for the inventory. The insert statement I am using works but if one of the entries does not have a value then it shows an error when trying to insert.
" Data type mismatch in criteria expression "
command.CommandText = "insert into Inventory(SerialNumber,PartNumber,ROnumber,Location)
values ('" + txtPart.Text + "','" + txtSerial.Text + "','" +
txtRO.Text + "','" + txtLocation.Text + "')";
I assume it is because the code needs a value for each field so how do I get around this issue?.

Actually when you trying to use this query you have said the First Parameter is SerialNumber and then PartNumber and when you are passing its reverse.
command.CommandText = "insert into Inventory(SerialNumber,PartNumber,ROnumber,Location)
values ('" + txtPart.Text + "','" +
txtSerial.Text + "','" +
txtRO.Text + "','" +
txtLocation.Text + "')";
Due to this reason the fields you are entering have different size May be part number is bigger in size instead of SerialNumber or vice versa. So you should change it to
command.CommandText = "insert into Inventory(SerialNumber,PartNumber,ROnumber,Location)
values ('" + txtSerial.Text + "','" +
txtPart.Text + "','" +
txtRO.Text + "','" +
txtLocation.Text + "')";

Related

Inserting values into database multiple tables through C# windows application

private void btnsave_Click(object sender, EventArgs e)
{
string dbpath = #"Data Source=ABC;Initial Catalog=ApplicationForm;Integrated Security=True";
SqlConnection con = new SqlConnection(dbpath);
con.Open();
string savequerybscs="insert into bscs values('"+txtapplicantnumber.Text+"','"+txtname.Text+"','"+txtfathername.Text+"','"+txtmatrictotal.Text+"','"+txtmatricobtained.Text+"','"+txtmatricpercent.Text+"','"+txtintertotal.Text+"','"+txtinterobtained.Text+ "','"+txtinterpercent.Text+"')";
string savequerybsit ="insert into bsit values('" + txtapplicantnumber.Text + "','" + txtname.Text + "','" + txtfathername.Text + "','" + txtmatrictotal.Text + "','" + txtmatricobtained.Text + "','" + txtmatricpercent.Text + "','" + txtintertotal.Text + "','" + txtinterobtained.Text + "','" + txtinterpercent.Text + "')";
string savequerymcs ="insert into bscs values('" + txtapplicantnumber.Text + "','" + txtname.Text + "','" + txtfathername.Text + "','" + txtmatrictotal.Text + "','" + txtmatricobtained.Text + "','" + txtmatricpercent.Text + "','" + txtintertotal.Text + "','" + txtinterobtained.Text + "','" + txtinterpercent.Text + "','"+txtbachelortotal.Text+"','"+txtbachelorobtained.Text+"','"+txtbachelorpercent.Text+"')";
string savequerymit ="insert into bscs values('" + txtapplicantnumber.Text + "','" + txtname.Text + "','" + txtfathername.Text + "','" + txtmatrictotal.Text + "','" + txtmatricobtained.Text + "','" + txtmatricpercent.Text + "','" + txtintertotal.Text + "','" + txtinterobtained.Text + "','" + txtinterpercent.Text + "','" + txtbachelortotal.Text + "','" + txtbachelorobtained.Text + "','" + txtbachelorpercent.Text + "')";
SqlCommand cmd = new SqlCommand(savequerybscs,savequerymcs,bla blaa);
}
As you can see, this solution is pretty messed up. Is there any other way to handle such issues? All I want is to insert data in multiple tables simultaneously but SqlCommand only takes 1 argument.
I just learned about bulk query or bulk insertion. Can someone guide me through that? I am not clearly getting those concepts from youtube.
You can do one insert query using the comma separator between tuples for multiples rows:
insert into bsit values (field1, field2...), (field1, field2...), ...
But this insert is for one table.
Basically, you use as many SQL query as many table you want to update.
I'm not advanced but perhaps, depending on the database server, you could execute a "script" in one C# SqlCommand execute non query call, using the semilicon separator, like:
string sql = "insert into table1 values (field1, field2...), (field1, field2...), ... ; "
+ "insert into table2 values (field1, field2...), (field1, field2...), ... ;";
MySql should support that.
You should use SQL Parameters for security reason instead of adding values to the sql string itself:
string sql = "insert into table1 values (?, ?)";
var command = new OdbcCommand(sql, connection);
command.Parameters.Add("#ID", OdbcType.Text).Value = Guid.NewGuid().ToString();
command.Parameters.Add("#Name", OdbcType.Text).Value = "Test";
command.ExecuteNonQuery();
https://learn.microsoft.com/dotnet/api/system.data.sqlclient.sqlcommand.parameters

MS Access DB Insert Query Not Working

I am trying to insert Data into MS ACCESS DB. Everything is fine. Connection, DB Path etc.
There is a table CIT in it.
I am using this Insert into query
string query = "INSERT INTO CIT (GRNO:, Name, FName, CNIC, Address, ContactNO, Gender, Qualification, DOB, RegDate, Photo) VALUES ('" + txtGRNO.Text + "','" + txtName.Text + "','" + txtFName.Text + "','1234','" + txtAddress.Text + "','" + txtContact.Text + "','" + cBoxGender.Text + "','" + cBoxQual.Text + "','" + dteDOB.Text + "','" + dteReg.Text + "','" + path + "');";
I tried everything but cant seem to find what is wrong here. The datatype of fields is Text in DB, & when I execute the query , it gives the error
Your table includes 2 fields whose names are problematic: GRNO:; and Name.
Since GRNO: includes a colon, you can enclose it in square brackets so the db engine will accept it: [GRNO:]
And since Name is a reserved word, enclose that one in square brackets, too.
"INSERT INTO CIT ([GRNO:], [Name], ...
Beyond those field name issues, the standard advice is to use a parameter query for your INSERT. Note you will still need to bracket those problem names in a parameter query.
Also, Access will let you use back-ticks instead of square brackets if you prefer ...
"INSERT INTO CIT (`GRNO:`, `Name`, ...
Try:
string query = "INSERT INTO CIT (GRNO, Name, FName, CNIC, Address, ContactNO, Gender, Qualification, DOB, RegDate, Photo) VALUES ('" + txtGRNO.Text + "','" + txtName.Text + "','" + txtFName.Text + "','1234','" + txtAddress.Text + "','" + txtContact.Text + "','" + cBoxGender.Text + "','" + cBoxQual.Text + "','" + dteDOB.Text + "','" + dteReg.Text + "','" + path + "');";
Remove ; after GRNO field.

uploading xml file to sql, turn off primary key in command

I've searched google and youtube and here of course and i can't find the answer. I need to turn the identity insert On and OFF but don't know how to do that in the sql command of the ADO.Net project. I'm sure it must be extremely easy for you highly experienced people.
additional information I'm using c#, visual studio and sql server, i don't know if that helps narrow the problem down?
here is sql command i tried in the ado.net project.
sql = "SET IDENTITY_INSERT HomeCareVisit ON insert into HomeCareVisit values("
+ VisitRefNo + ",'" + PatientNo + "','" + ScheduledDateTime + "','"
+ TreatmentInstructions + "','" + MedicalStaffID + "','" + Priority + "','"
+ ActualVisitDateTime + "','" + TreatmentProvided + "','" + Prescription
+ "','" + AdvisoryNotes + "'," + (FurtherVisitRequired ? "1" : "0") + " );";
and it gave the error
Violation of PRIMARY KEY constraint 'PK_VisitRefNo'. Cannot insert duplicate key in object 'dbo.HomeCareVisit'.
The statement has been terminated.
here is the code shows what data type the column are
VisitRefNo = ds.Tables[0].Rows[i].ItemArray[0].ToString();
PatientNo = Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[1]);
ScheduledDateTime = Convert.ToDateTime(ds.Tables[0].Rows[i].ItemArray[2]);
TreatmentInstructions = ds.Tables[0].Rows[i].ItemArray[3].ToString();
MedicalStaffID = Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[4]);
Priority = ds.Tables[0].Rows[i].ItemArray[5].ToString();
ActualVisitDateTime = Convert.ToDateTime(ds.Tables[0].Rows[i].ItemArray[6]);
TreatmentProvided = ds.Tables[0].Rows[i].ItemArray[7].ToString();
Prescription = ds.Tables[0].Rows[i].ItemArray[8].ToString();
AdvisoryNotes = ds.Tables[0].Rows[i].ItemArray[9].ToString();
FurtherVisitRequired = Convert.ToBoolean(ds.Tables[0].Rows[i].ItemArray[10]);
This is the command to do it
SET IDENTITY_INSERT YourTable ON
Try this:
sql = "SET IDENTITY_INSERT HomeCareVisit ON insert into HomeCareVisit(column_names) values("
+ VisitRefNo + ",'" + PatientNo + "','" + ScheduledDateTime + "','"
+ TreatmentInstructions + "','" + MedicalStaffID + "','" + Priority + "','"
+ ActualVisitDateTime + "','" + TreatmentProvided + "','" + Prescription
+ "','" + AdvisoryNotes + "'," + FurtherVisitRequired + " );";
where column_names is list of table columns in order in which you insert.
I think you pass string in place where table doesn't expect this, like TreatmentProvided column (by name, i assume that you pass True/False, but not as string).

How to insert a record with a primary key in ms access database c#

I am using the following command for inserting a record in an MS Access database:
OleDbCommand cmd = new OleDbCommand("insert into Table1 values('" + Name + "','" +
Symbol + "','" + D + "','" + Red + "','" + RedBuy + "','" + RedSell + "','" +
SBIntraBuy + "','" + SBTR1Buy + "','" + SBTR2Buy + "','" + SBTR3Buy + "','" +
SBIntraSell + "','" + SBTR1Sell + "','" + SBTR2Sell + "','" + SBTR3Sell + "','" + RSTL
+ "','" + Green + "');", con);
I want to add a column before Name called CustomerId with a Primary key. I don't know how to insert it with primary key. What i should add in my command for primary key?
There would be a great appreciation if someone could help me.
Thanks In Advance.
Check this link for screen shot of the table layout.
If your key is auto increment, then you don't need to. The database will do it for you. If your key is not auto increment, consider changing it. It's really neat!
Also, please consider using binding instead of building a full insert query.
Suppose the following table:
Table1
PK (auto_increment)
Name
Symbol
What you will want to do is:
OleDbCommand cmd = new OleDbCommand("insert into Table1 (Name,Symbol) values (?,?)");
cmd.Parameters.Add(new OleDbParameter("#Name",Name));
cmd.Parameters.Add(new OleDbParameter("#Symbol",Symbol));
or (safer):
OleDbCommand cmd = new OleDbCommand("insert into Table1 (Name,Symbol) values (#Name,#Symbol)");
cmd.Parameters.Add(new OleDbParameter("#Name",Name));
cmd.Parameters.Add(new OleDbParameter("#Symbol",Symbol));
And finally:
cmd.ExecuteNonQuery();

exception with nvarchar - data was truncated while converting from one data type to another

I'm having a bit of trouble with entering data into several columns of a database, all nvarchar types. I'm getting:
The data was truncated while converting from one data type to another. Name of function(if known)
DBConn.Open();
cmd = new SqlCeCommand("INSERT INTO [Employee Table] VALUES ('"+ social + "','" +
first + "','" + last + "','" + mid + "','" + address + "','" + phone + "',"
+ "'Employee'" + ",'" + city + "','" + state + "','" + zip + "','" + email + "','" + userName + "')", DBConn);
cmd.ExecuteNonQuery();
Any suggestions on how to avoid the truncating/converting error?
Your NVARCHAR isn't big enough to hold your string.
try using Parameters
SqlParameter param = new SqlParameter("Field", SqlDbType.NVarChar)
Param.Value = Field;
The reason is that the column's length is very short. So the value is longer than the maximum width of the column of the table.

Categories