I created a query to insert into two ms access tables at a time in c#. I got the exception
{System.Data.OleDb.OleDbException: Characters found after end of SQL
statement. at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult
hr) at
System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS
dbParams, Object& executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object&
executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior
behavior, Object& executeResult) at
System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior
behavior, String method) at
System.Data.OleDb.OleDbCommand.ExecuteNonQuery() at
CompanyDetails.Model.CompanyDetailsModel.setCompanyDetailsToDB(CompanyDetailsDataList
_cmpDetailsList) in E:\Project\PBAttendence\ModifyPrivileage\CompanyDetails\Model\CompanyDetailsModel.cs:line
62}
my sample code is given below please solve my problem. sorry for my bad English.
int companyID = _cmpDetailsList[0].CompanyID;
string companyName = _cmpDetailsList[0].CompanyName;
string contactID = _cmpDetailsList[0].ContactID;
string companyAddress = _cmpDetailsList[0].CompanyAddress;
if (companyID == -1)
{
OleDbCommand cmd = new OleDbCommand("Insert into CompanyDetails([CompanyName],[CompanyAddress],[ContactID]) values ('" + companyName + "','" + companyAddress + "','" + contactID + "');Insert into UserCompanyDetails([UserID],[CompanyID]) values (" + "Select [UserID] from UserDetails;" + "," + "Select ##identity;" + "); ", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
else
{
OleDbCommand upcmd = new OleDbCommand("update CompanyDetails set [CompanyName] = '" + companyName + "',[CompanyAddress] = '" + companyAddress + "',[ContactID] = '" + contactID + "' where [CompanyID] = #cmpID;", conn);
conn.Open();
upcmd.Parameters.AddWithValue("#cmpID", companyID);
upcmd.ExecuteNonQuery();
conn.Close();
}
now i split into two insert command but i got the error {System.Data.OleDb.OleDbException: Syntax error. in query expression 'Select [UserID] from UserDetails;
OleDbCommand cmd = new OleDbCommand("Insert into CompanyDetails([CompanyName],[CompanyAddress],[ContactID]) values ('" + companyName + "','" + companyAddress + "','" + contactID + "');", conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
OleDbCommand cmd1 = new OleDbCommand("Insert into UserCompanyDetails([UserID],[CompanyID]) values (" + "Select [UserID] from UserDetails;" + "," + "Select ##identity" + ");", conn);
conn.Open();
cmd1.ExecuteNonQuery();
conn.Close();
The problem is this line of code:
OleDbCommand cmd = new OleDbCommand("Insert into CompanyDetails([CompanyName],[CompanyAddress],[ContactID]) values ('" + companyName + "','" + companyAddress + "','" + contactID + "');Insert into UserCompanyDetails([UserID],[CompanyID]) values (" + "Select [UserID] from UserDetails;" + "," + "Select ##identity;" + "); ", conn);
You have two insert statements in the same OleDbCommand. Try to move this into two different steps:
Insert into CompanyDetails table
Insert into UserCompanyDetails table
Hope this helps you
First of all , it would have been easier with the raw sql command then your code generating the sql.
You might consider making a stored procedure since your command is getting kinda complex
If i'm correct , what you are currently trying to do is :
Insert into table1(x,y,z) values a,b,c;
Insert into table2(x,y) values select * from table3; , ##identity
The second sql command is invalid in both syntax and logic, your ##identity won't be static since you're inserting new records during your command.
My recommendation would be to do something like this :
Insert into table1(x,y,z) values a,b,c;
declare #table1Id int = ##identity
Insert into table2(x,y) select colA, #table1Id from table3;
You cannot have ; in queries in Access. See http://office.microsoft.com/en-us/access-help/HV080760224.aspx You will have to do the two inserts separately as suggested by #juanreyesv
You will have to do 3 queries,
Do the insert using your sql: "Insert into CompanyDetails([CompanyName],[CompanyAddress],[ContactID]) values ('" + companyName + "','" + companyAddress + "','" + contactID + "')
Get the ##identity using
Select ##identity and store it in a variable say idnt
Use the identity value obtained in 2. to do the third insert:
"Insert into UserCompanyDetails([UserID],[CompanyID])
Select UserID, " + idnt.ToString() + " from UserDetails"
Refer to http://msdn.microsoft.com/en-us/library/ks9f57t0%28VS.71%29.aspx
Related
I am new to SQL, I have table with RecordId that is incremented automatically and is primary key. I would like to get RecordId of the row that was inserted into table.
Thanks in advance for help.
myCommand.CommandText = "INSERT INTO " + tableName + " (DateRaised,RaisedBy,WeekNo,Platform,Department,Site,Process, Area,NavErrorNo,RootCauseDescription,Status) " +
"VALUES ('" + currentDate.ToString(format) + "','" +
sender + "'," +
weekNumber + ",'" +
comboBoxPlatform.SelectedItem + "','" +
comboBoxDepartment.SelectedItem + "','" +
comboBoxSite.SelectedItem + "','" +
comboBoxProcess.SelectedItem + "','" +
comboBoxArea.SelectedItem + "','" +
textBoxNavError.Text + "','" +
textBoxIssue.Text + "','Open')";
//int lastInsertedId =
myCommand.ExecuteNonQuery();
lastInsertedId should be int from RecordId in my table.
To do this properly (if this is for SQL Server - you weren't very clear on this), I see two options:
Approach #1 - using SCOPE_IDENTITY
This works well if you're only ever inserting a single row at a time - use something like this:
// set up your query using *PARAMETERS** as you **ALWAYS** should!
// Using SELECT SCOPE_IDENTITY() to get back the newly inserted "Id"
myCommand.CommandText = "INSERT INTO dbo.SomeTable (list-of-columns) " +
"VALUES (#param1, #param2, #param3, ...., #paramN); " +
"SELECT SCOPE_IDENTITY();";
// set up the parameters and theirs values
object result = myCommand.ExecuteScalar();
if (result != null)
{
int lastInsertedId = Convert.ToInt32(result);
}
Approach #2 - using the OUTPUT clause
This works well even if you insert multiple rows at once (typically using a SELECT after the INSERT):
// set up your query using *PARAMETERS** as you **ALWAYS** should!
// Using SELECT SCOPE_IDENTITY() to get back the newly inserted "Id"
myCommand.CommandText = "INSERT INTO dbo.SomeTable (list-of-columns) " +
"OUTPUT Inserted.RecordId " +
"VALUES (#param1, #param2, #param3, ...., #paramN); ";
// set up the parameters and theirs values
object result = myCommand.ExecuteScalar();
if (result != null)
{
int lastInsertedId = Convert.ToInt32(result);
}
First thing this is not a good idea to call direct SQL statement from code it can cause an issue for SQL injection as #Zohar suggested.
You can either user parametrized query or sp.
Inside sp, you can use
SELECT ##IDENTITY AS 'Identity';
after Insert statement, it will return the last auto-incremented value for PK,
then return this value as an output parameter and catch it after .ExecuteNonQuery(); in C# code.
This should do the trick for You
private void SelectLast()
{
string sqlLast = "SELECT TOP(1) RecordId FROM [YourtableName] ORDER BY 1 DESC";
Connection.Open();
using (SqlCommand cmd = new SqlCommand(sqlLast, Connection))
{
cmd.CommandType = CommandType.Text;
{
int insertedID = Convert.ToInt32(cmdAdd.ExecuteScalar());
textBoxID.Text = Convert.ToString(insertedID);
}
Connection.Close();
}
}
I have received the following error:
Syntax error in INSERT INTO statement.
I don't seem to be able to find the mistake. here is the code:
if (Request["su"] == "save")
{
string sqlCommand = "";
string fileName = "UsersDB.accdb";
string tableName = "Table 2";
string website_name, website_psw;
website_name = Request["psw_name"];
website_psw = Request["psw"];
sqlCommand = "INSERT INTO " + tableName + " (fname, lname, umail, upassword, gender, age, uid) ";
sqlCommand += "VALUES ('"+0+ "','" + Session["umail"].ToString() + "','" + website_psw + "','" + website_name + "')";
MyAdoHelper.DoQuery(fileName, sqlCommand);
}
As for the database, it has 4 rows:
uid, uidd, psw_name, psw
What is the issue in the code which leads to such error?
It looks like your INSERT statement is specifying 7 columns (fname, lname, umail, upassword, gender, age, uid) to insert into and only 4 columns of data.
The table name with a space in it is also likely to cause an issue. Enclosing it in square brackets should fix that issue.
You SQL should start like this (if this text: " it has 4 rows: uid, uidd, psw_name, psw" means your table has 4 columns):
INSERT INTO [Table 2] (uid, uidd, psw_name, psw) VALUES (...
Try this two lines :
sqlCommand = "INSERT INTO " + tableName + " (fname, lname, umail, upassword, gender,
age, uid) ";
sqlCommand += "VALUES (\'"+0+ "\',\'" + Session["umail"].ToString() + "\',\'" +
website_psw + "\',\'" + website_name + "\')";
I am trying to perform an insert query in C# but it keeps telling me syntax error in insert into statement.
Here is my query:
Checks.SQL.Insert(mydb, "SELECT * FROM Employee", "INSERT INTO Employee(First_Name,Last_Name,Email,CellPhone_Number,TypeOfUser,Username,Password) VALUES('" + txtFirstName.Text + "','" + txtLastName.Text + "','" + txtEmail.Text + " ', '" + txtCellphone.Text + "'," + typeId + ",'"+Encrypcion.encrypt(txtUsername.Text)+"','"+Encrypcion.encrypt(txtPassword.Text)+"' )");
Here is my checks insert function
public static void Insert(OleDbConnection mydb, string SelectQuery, string InsertQuery)
{
mydb.Open();
OleDbDataAdapter query2 = new OleDbDataAdapter(SelectQuery, mydb);
OleDbCommand cmd = new OleDbCommand(InsertQuery, mydb);
query2.InsertCommand = cmd;
query2.InsertCommand.ExecuteNonQuery();
mydb.Close();
}
Here is a picture of my InsertQuery with input data as example:
enter image description here
See a picture of my table info:
Password is a reserved word in Access, so:
"INSERT INTO Employee(First_Name,Last_Name,Email,CellPhone_Number,TypeOfUser,Username,[Password]) .."
I am actually trying to get the primary key after the insertion by using ExecuteScalar(). Since it returns the first column of the first row after the insertion. But I am getting 0. I do not know why it is happening. Please help me out.
query = "Insert into Admissions(Admission_date, Student_name, Father_name, Mother_name, DOB, Gender, Address, State, City, Pincode, Admission_for, Previous_school, Fees) values ('" + txtAdmDate.Text + "','" + txtStudentName.Text + "','" + txtFatherName.Text + "','" + txtMotherName.Text + "','" + dob + "','" + gender + "','" + txtAddress.Text + "','" + txtState.Text + "','" + txtCity.Text + "','" + txtPincode.Text + "','" + cmbClass.Text + "','" + txtPreviousSchool.Text + "','" + txtFees.Text + "')";
cmd = new SqlCommand(query, con);
con.Open();
int admid = Convert.ToInt32(cmd.ExecuteScalar());
There are some issues with your code/question.
Your code is vulnerable to SQL Injection attacks. You need to parameterize your queries.
The INSERT statement by design is not meant to return anything, if you want to return the primary key of what you just inserted you need an output parameter in your query (better yet, a stored procedure).
A quick google for "return primary key on sql insert c#" would have given you a ton of results. Your question is asked almost verbatim here. In fact my answer is basically the top answers code (modified for your use).
Here is my answer
//Create an Admission class that represents your data
public static int Save(Admission admission)
{
var conn = DbConnect.Connection();
const string sqlString = "Admissions(Admission_date, Student_name, Father_name, Mother_name, DOB, Gender, " +
"Address, State, City, Pincode, Admission_for, Previous_school, Fees) values (#AdmissionDate, #StudentName, " +
"#FatherName, #MotherName, #DOB, #Gender, #Address, #State, #City, #Pincode, #AdmissionFor, #PreviousSchool, " +
"#Fees) SELECT SCOPE_IDENTITY()";
using (conn)
{
using (var cmd = new SqlCommand(sqlString, conn))
{
cmd.Parameters.AddWithValue("#AdmissionDate", admission.AdmissionDate);
cmd.Parameters.AddWithValue("#StudentName", admission.StudentName);
cmd.Parameters.AddWithValue("#FatherName", admission.FatherName);
cmd.Parameters.AddWithValue("#MotherName", admission.MotherName);
cmd.Parameters.AddWithValue("#DOB", admission.DOB);
cmd.Parameters.AddWithValue("#Gender", admission.Gender);
cmd.Parameters.AddWithValue("#Address", admission.Address);
cmd.Parameters.AddWithValue("#State", admission.State);
cmd.Parameters.AddWithValue("#City", admission.City);
cmd.Parameters.AddWithValue("#Pincode", admission.Pincode);
cmd.Parameters.AddWithValue("#AdmissionFor", admission.AdmissionFor);
cmd.Parameters.AddWithValue("#PreviousSchool", admission.PreviousSchool);
cmd.Parameters.AddWithValue("#Fees", admission.Fees);
cmd.CommandType = CommandType.Text;
conn.Open();
return (int)(decimal)cmd.ExecuteScalar();
}
}
}
Try using an OUTPUT clause in your SQL command to return information about your command.
public int NewProperty(PropertyData propertyData)
{
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("InsertUpdateProperty", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#id", propertyData.ID);
cmd.Parameters.AddWithValue("#ListPropertyFor", propertyData.ListPropertyFor);
cmd.Parameters.AddWithValue("#PropertyTypeId", propertyData.PropertyTypeId);
cmd.Parameters.AddWithValue("#PropertyLoction", propertyData.PropertyLocation);
cmd.Parameters.AddWithValue("#Locality", propertyData.Locality);
cmd.Parameters.AddWithValue("#ProjectName", propertyData.ProjectName);
cmd.Parameters.AddWithValue("#PropertyDescription", propertyData.PropertyDescription);
cmd.Parameters.AddWithValue("#SuperBulidupArea", propertyData.SuperBulidupArea);
cmd.Parameters.AddWithValue("#SuperBulidupId", propertyData.SuperBulidupAreaId);
cmd.Parameters.AddWithValue("#BulidupArea", propertyData.BulidupArea);
cmd.Parameters.AddWithValue("#BulidupAreaId", propertyData.BulidupAreaId);
cmd.Parameters.AddWithValue("#CarpetArea", propertyData.CarpetArea);
cmd.Parameters.AddWithValue("#CarpetAreaId", propertyData.CarpetAreaId);
cmd.Parameters.AddWithValue("#Bathrooms", propertyData.Bathrooms);
cmd.Parameters.AddWithValue("#Bedrooms", propertyData.Bedrooms);
cmd.Parameters.AddWithValue("#Balconies", propertyData.Balconies);
cmd.Parameters.AddWithValue("#FurnishedId", propertyData.FurnishedId);
cmd.Parameters.AddWithValue("#TotalFloors", propertyData.TotalFloors);
cmd.Parameters.AddWithValue("#PropertyOnFloors", propertyData.PropertyOnFloor);
cmd.Parameters.AddWithValue("#Parking", propertyData.Parking);
cmd.Parameters.AddWithValue("#AvalibiltyId", propertyData.AvalibiltyId);
cmd.Parameters.AddWithValue("#AgeOfProperty", propertyData.AgeOfProperty);
cmd.Parameters.AddWithValue("#OwnerShip", propertyData.OwenerShip);
cmd.Parameters.AddWithValue("#Price", propertyData.Price);
cmd.Parameters.AddWithValue("#IsActive", propertyData.IsActive);
con.Open();
int i = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
return i;
}
}
I'm using autonumber but it doesn't work for me. I want auto numbering in my StudentID number.
OleDbCommand system = new OleDbCommand();
system.CommandType = CommandType.Text;
system.CommandText =
"insert into Student(ID, Lastname, Middlename, Firstname, Address, DateofBirth, Birthplace, Contact_number, emailaddress, guardian_name, Guardian_contact) values ('" + txtStudentIDnumber.Text + "','" + txtlastname.Text + "','" + txtfirstname.Text + "','" +
txtmiddlename.Text + "','" + txtaddress.Text + "','" + txtdateofbirth.Text + "','" + txtbirthplace.Text + "','" + txtcontactnumber.Text + "','" + txtemailaddress.Text + "','" + txtGuardianname.Text + "','" + txtguardiancontact.Text + "')";
system.Connection = mydatabase;
if (MessageBox.Show("Save data?", "Confirm Save", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
It is difficult to determine the issue without the database schema or the error message. However, the issue is probably because you are trying to insert a value into the ID column when it may have auto numbering (also known as a counter) enabled. Change:
system.CommandText = "insert into Student(ID, Lastname, ..."; // And so on
to
system.CommandText = "insert into Student(Lastname, ..."; // And so on
Also consider changing the query to be a parameterized query (such as that mentioned in incorrect syntax near 's'. unclosed quotation mark after the character string ')') rather than using concatenation to avoid SQL injection and escaping issues.
first you should specify identity Column like this :
then your code :
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\db.accdb");
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = string.Format("insert into Student(LastName,...) values('{0}',...)",txtLastName.Text.Trim(),...);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Your ID column should be setup to be an identity (in the database), then you should omit it from the insert.
http://forums.asp.net/t/1492834.aspx/1
UPDATE
I suspect your StudentIdNumber is an actual stateissued ID number, and what you're looking for is an identity field.
You'll need to add an identity column to your table, either using the table designer you used to create the table, or using a script
CREATE TABLE Student(
ID int identity,
StudentIdNo varchar(10),
Lastname varchar(10),
Firstname varchar(10),
Middlename varchar(10),
CONSTRAINT AutoIncrementTest_PrimaryKey PRIMARY KEY (ID)
)
This will be the format of your insert statement, notice there is no ID field
"INSERT INTO Student (StudentIdNo, Lastname, Firstname, Middlename) VALUES (?)"
...in your case, after adding a identity field
OleDbCommand comm = new OleDbCommand();
comm.CommandType = CommandType.Text;
comm.CommandText =
#"insert into Student(StudentIdNo, Lastname, Firstname, Middlename)
values (#StudentIdNo, #Lastname, #Firstname, #Middlename)";
comm.Parameters.AddWithValue("#StudentIdNo", txtStudentIdNo.Text);
comm.Parameters.AddWithValue("#Lastname", txtlastname.Text);
comm.Parameters.AddWithValue("#Firstname", txtfirstname.Text);
comm.Parameters.AddWithValue("#Middlename", txtmiddlename.Text);
comm.Connection = mydatabase;