Here I am inserting an image in msaccess database (accdb). I am not able to figure out why this is generating expcetion. It says Error in insert into statement.
String q = #"Insert Into tblModal (ModalName, CategoryId, Gender, Type, Description, image, LastUpdated) values ('" +
txtModalName.Text + "','" + categoryId + "','" + gender + "','"+txtType.Text +"', '" + txtDescription.Text + "',#pic, '" + DateTime.Now.ToString() + "')";
OleDbCommand cmd = new OleDbCommand(q);
cmd.Parameters.AddWithValue("#pic", Check.imageToByteArray(pictureBoxPhoto.Image));
int res;
res = br.ExecuteNonQuery(cmd);
Related
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
I'm new in this field. Trying to insert the values from textbox to my database table, but I get an error at
adapter.InsertCommand.ExecuteNonQuery();
Can anyone help me solve this?
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "insert into NewName values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')";
command = new SqlCommand(sql,con);
adapter.InsertCommand = new SqlCommand(sql,con);
// this line here is showing the error
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
con.Close();
Since your table is called table and that is a SQL reserved word, you have two choices:
Change your table name. This is the only option you should be considering but for completeness;
Quote the name of the table:
insert into [table] values....
You do not list your column name on insert. This means you are also attempting to insert your identity column as well. Always list your column names
insert into NewName (firstname, lastname, username, email, password, contact)
values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')
Yes I've done it .I was using "user" in table column which is not allowed .After changing the column name everything works.
This is the code
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "insert into NewName values('" + first_Name.Text + "','" + last_Name.Text + "','" + user.Text + "','" + email.Text + "','" + password.Text + "','" + contact.Text + "')";
command = new SqlCommand(sql, con);
adapter.InsertCommand = new SqlCommand(sql, con);
// this line here is showing the error
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
con.Close();
Data comes from "Temp" table.
Stored in variables
Inserted into "Client" table with the addition of two more variables.
And there comes an error. The INSERT query is not executing properly.
Query,
int r;
string que = "INSERT INTO client (fname, lname, dob,
email, gender, uname, upass) VALUES
('" + fname + "',
'" + lname + "', '" + dob + "',
'" + email + "',
'" + gender + "',
'" + TextBox1.Text + "',
'" + TextBox2.Text + "') ";
r = c.savedeldata(que);
savedeldata Function
public int savedeldata(string qu)
{
con.Open();
cmd = new SqlCommand(qu, con);
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
That's the only solution I can find.
if (ds.Tables["0"].Rows.Count == 1)
{
int r;
string queryt = "DELETE FROM tbl_client";
r = c.savedeldata(queryt);
string que = "INSERT INTO tbl_client(fname, lname, dob, email, gender) SELECT * FROM temp WHERE dob = '" + TextBox3.Text + "'";
r = c.savedeldata(que);
string quer = "UPDATE tbl_client SET uname = '"+ TextBox1.Text +"', upass = '"+ TextBox2.Text +"' WHERE dob = '"+ TextBox3.Text +"'";
r = c.savedeldata(quer);
}
I have a sql table which has an image cloumn I'm trying to insert the image after converting it into byte.... the my insert query looks like this
INSERT INTO Member (F_NAME, L_NAME, D_O_B, UAE_ID_NO, MOBILE_NO, EMAIL_ID, REFERER, REF_CONTACT, ADDRESS, PICTURE) VALUES ('" + fname + "','" + lname + "','" + dob.ToShortDateString() + "','" + uaeid + "','" + mobile + "','" + emailid + "','" + reffere + "','" + refercontact + "','"+address+"',"+photo+")"
here pic is the image column... I'm converting the image into byte array using the following method
MemoryStream ms = new MemoryStream();
//save the image into memory stream
pBoxMember.Image.Save(ms, ImageFormat.Jpeg);
//assign the byte array with total size of memorystream
photo = new byte[ms.Length];
ms.Position = 0;
ms.Read(photo, 0, photo.Length);
return true;
But it is giving me this error
An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name. For other statements, look for empty alias names. Aliases defined as "" or [] are not allowed. Change the alias to a valid name.
invalid syntax near ".
If this should work at all this should look like this:
var sql = "INSERT INTO Member (F_NAME, L_NAME, D_O_B, UAE_ID_NO, MOBILE_NO, " +
"EMAIL_ID, REFERER, REF_CONTACT, ADDRESS, PICTURE) " +
"VALUES ('" + fname + "','" + lname + "','" + dob.ToShortDateString() + "','" + uaeid + "','" + mobile + "','" + emailid + "','" + reffere + "','" + refercontact + "','" + address + "'," + photo + ")"
But you should use SQL Params for this, something like:
string queryString = "INSERT INTO Member (F_NAME, L_NAME, D_O_B, UAE_ID_NO, ... VALUES(#fname ,#lname ....)";
SqlCommand cmd = new SqlCommand(queryString, dbConnection);
cmd.Parameters.AddWithValue("#fname",fname);
cmd.Parameters.AddWithValue("#lname",lname);
...
cmd.Parameters.AddWithValue("#blobParam",YourBytesArray);
...
cmd.ExecuteNonQuery();
Note: I'm building a practice project where my trainer has forbid me to parameterize. I am aware of the security risks, but the site will not be deployed. I'm using a select scope_identity method to grab an auto-incremented value from the SubmissionId column of my table Submissions.
I want to insert that value into two other tables; I've got newSubID declared as a var and I use it in the insert statements, but I get the error message
The name "newSubID" is not permitted in this context. Valid expressions are constants, constant expressions, and (in some contexts) variables. Column names are not permitted.
What am I missing here?
Here's my code:
protected void BtnSubmit_Click(object sender, EventArgs e)
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
String subQuery = "INSERT INTO Submission (Coverage, CurrentCoverage, PrimEx, Retention, EffectiveDate, Commission, Premium, Comments) VALUES ('" + TbCoverage.Text + "','" + TbCurrentCoverage.Text + "','" + TbPrimEx.Text + "','" + TbRetention.Text + "','" + TbEffectiveDate.Text + "','" + TbCommission.Text + "','" + TbPremium.Text + "','" + TbComments.Text + "')"
+ "SELECT CAST (SCOPE_IDENTITY() AS int)";
using (SqlConnection sqlConn = new SqlConnection(connectionString))
{
sqlConn.Open();
SqlCommand subCmd = new SqlCommand(subQuery, sqlConn);
using (subCmd)
{
subCmd.ExecuteNonQuery();
var newSubID = (Int32)subCmd.ExecuteScalar();
String custQuery = "INSERT INTO Customer (CustId, CustName, SicNaic, CustAdd, CustCity, CustState, CustZip, SubId) VALUES ('" + TbCustId.Text + "', '" + TbCustName.Text + "', '" + RblSicNaic.SelectedItem + "', '" + TbCustAddress.Text + "', '" + TbCustCity.Text + "', '" + DdlCustState.SelectedItem + "', '" + TbCustZip.Text + "', newSubID)";
String broQuery = "INSERT INTO Broker (BroId, BroName, BroAdd, BroCity, BroState, BroZip, EntityType, SubId) VALUES ('" + TbBroId.Text + "', '" + TbBroName.Text + "', '" + TbBroAddress.Text + "', '" + TbBroCity.Text + "', '" + DdlBroState.SelectedItem + "', '" + TbBroZip.Text + "', '" + DdlEntity.SelectedItem + "', newSubID)";
SqlCommand custCmd = new SqlCommand(custQuery, sqlConn);
SqlCommand broCmd = new SqlCommand(broQuery, sqlConn);
using (custCmd)
using (broCmd)
{
custCmd.ExecuteNonQuery();
broCmd.ExecuteNonQuery();
Response.Redirect("~/View.aspx?ProductId=" + newSubID);
}
This is called up on the next page like so (I have left the errors as they are in the interest of helping whomever may need to see the problem and solutions, which are listed in answers below):
string x = Request.QueryString["SubmissionId"];
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
string editCustQuery = "SELECT CustName, SicNaic, CustCity, CustAdd, CustState, CustZip FROM Customer WHERE SubId =" + x;
using (SqlConnection editConn = new SqlConnection(connectionString))
{
editConn.Open();
using (SqlCommand CustCommand = new SqlCommand(editCustQuery, editConn))
{
SqlDataReader dr = CustCommand.ExecuteReader();
dr.Read();
LblCustName.Text = dr.GetString(0);
LblSicNaic.Text = dr.GetString(1);
LblCustCity.Text = dr.GetString(2);
LblCustAddress.Text = dr.GetString(3);
LblCustState.Text = dr.GetString(4);
LblCustZip.Text = dr.GetInt32(5).ToString();
}
It's because you're not concatenating the newSubID into the custQuery / btoQuery SQL statements, but instead your using the literal text "newSubID" in the statement which is invalid here as it will assume "newSubID" is a column name.
i.e.
String custQuery = "INSERT INTO Customer (CustId, CustName, SicNaic, CustAdd, CustCity,
CustState, CustZip, SubId)
VALUES ('" + TbCustId.Text + "', '" + TbCustName.Text + "', '" + RblSicNaic.SelectedItem +
"', '" + TbCustAddress.Text + "', '" + TbCustCity.Text + "', '" +
DdlCustState.SelectedItem + "', '" + TbCustZip.Text + "'," +
newSubID.toString() + ")";
Of course, I'm only giving an answer that uses dynamic SQL like this because of your disclaimer and is not what I'd do in real life!
Answer of AdaTheDev is correct.
I think you have another issue. If you do ExecuteNonQuery and then ExecuteScalar with the same command, you'll insert twice. Use an out-parameter for your scope_id and call only exenonquery or call just exescalar.
//subCmd.ExecuteNonQuery();
var newSubID = (Int32)subCmd.ExecuteScalar();