string sql = "Update stdrecord set firstname='" + fname + "',lastname='" + lname + "',mobile='" + mob + "',phone='" + phn + "',city='" + city + "',province'" + prov + "'where id='" + id + "'";
error :
System.Data.SqlClient.SqlException: Incorrect syntax
can anybody cor rectify the query ?
Your missing an equal:
"',province = '" + prov + "' where id='" + id + "'";
And do not build SQL-Queries like this. Please use ADO.Net Parameter.
Equal sign is missing:
,province='" + prov + "' where id='" + id + "'";
string sql = "Update stdrecord set firstname='" + fname + "',lastname='" + lname + "',mobile='" + mob + "',phone='" + phn + "',city='" + city + "',province='" + prov + "'where id='" + id + "'";
You miss = after province and there is no space between prov and where !
Also in this case you are open to SqlInjection, please use SqlCommand.Parameters.
The Query should look like this.
string sql = #"Update stdrecord set firstname=#FName ,lastname=#LastName, mobile=#Mobile,
phone=#Phone,city=#City, province=#Province where id=#ID";
This will protect you from SqlInjection and also sql server will cache your query.
To using command Parameters you need to add this code to your SqlCommand
SqlCommand cmd = new SqlCommand(sql, connectionString);
cmd.Parameters.AddWithValue("#FName", fName);
cmd.Parameters.AddWithValue("#LastName", lname );
cmd.Parameters.AddWithValue("#Mobile", mob);
cmd.Parameters.AddWithValue("#Phone", phn);
cmd.Parameters.AddWithValue("#City", city);
cmd.Parameters.AddWithValue("#Province", prov);
cmd.Parameters.AddWithValue("#ID", id);
With this structure you will not have problems like this in future because you will not add + and ' non stop. Also use # when you build string this give you the possibility to write string on more than one line without using +.
Put a space before Where Clause and equal sign in province column, will get work perfectly
Related
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();
I am trying to pass both Column name and the Value to be checked in the code at runtime. However I am getting an:
"Invalid Column Name "
Exception. The code is as follows :
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO rezervasyon (Ad,Soyad,TelefonNo,OdaSayisi,KişiSayisi," +
"Ucret,Acıklama,GirisTarihi,CikisTarihi,KayitTarihi) VALUES " +
"(" + isim + ",'" + soyisim + "','" + telefon + "'," +
"'" + oda_sayisi + "','" + kisi_sayisi + "','" + ucret + "'," +
"'" + aciklama + "','" + giris_tar + "','" + cikis_tar + "'," +
"'" + current_tarih + "')";
cmd.ExecuteNonQuery();
con.Close();
You've missed a single quote here " + isim + " and it should be '" + isim + "'. However you should always use parameterized queries to avoid SQL Injection and also to get rid of this kind of errors.
cmd.CommandText = "INSERT INTO rezervasyon (Ad,Soyad,TelefonNo,OdaSayisi,KişiSayisi,Ucret" +
",Acıklama,GirisTarihi,CikisTarihi,KayitTarihi) " +
"VALUES (#isim, #soyisim , ...)";
cmd.Parameters.AddWithValue("#isim", isim);
cmd.Parameters.AddWithValue("#soyisim", soyisim);
//Other parameters
Although specify the type directly and use the Value property is more better than AddWithValue:
cmd.Parameters.Add("#isim", SqlDbType.VarChar).Value = isim;
Can we stop using AddWithValue() already?
I actually new in asp.net c# I want to know why this code below doesn't work.
All I want to do is store data form into a SQL Server database.
I have 2 tables and I want the data form entered stored in the database. Look at the select statement for retrieving the primary key to store it as a foreign key in the other table
String q = "Insert into dbo.requests(request_date,request_type,visit_date,reason,user_id,status_id)values('" + DateTime.Now.ToString() + "','" + DropDownList1.SelectedValue.ToString() + "','" + TextBox8.Text.ToString() + "','" + TextBox9.Text.ToString() + "','"+ 1+"','"+ 2+"')";
SqlCommand cmd = new SqlCommand(q, con);
cmd.ExecuteNonQuery();
con.Close();
con2.Open();
if (con2.State == System.Data.ConnectionState.Open)
{
String a = "select top 1 request_id from dbo.requests where request_date= CAST(GETDATE() AS DATE and user_id=999 order by request_id DESC ";
SqlCommand cmd2 = new SqlCommand(a, con2);
int r = cmd2.ExecuteNonQuery();
}
con2.Close();
con3.Open();
if (con3.State == System.Data.ConnectionState.Open)
{
String b = "INSERT into dbo.visitor(visitor_Fname,visitor_Mname,visitor_family_name,visitor_id,visitor_mobile,request_id,place_of_work,country_name) values ('" + TextBox1.Text.ToString() + "','" + TextBox2.Text.ToString() + "','" + TextBox3.Text.ToString() + "','" + TextBox4.Text.ToString() + "' , '" + TextBox5.Text.ToString() + "','r', '" + TextBox6.Text.ToString() + "', '" + TextBox7.Text.ToString() + "' )";
SqlCommand cmd3 = new SqlCommand(b, con3);
cmd3.ExecuteNonQuery();
}
You should change it
int r = cmd2.ExecuteNonQuery();
to
int r = (int)cmd2.ExecuteScalar();
To retrieve selecting only one field use ExecuteScalar instead of ExecuteNonQuery. ExecuteNonQuery doesn't return selecting fields.
Just store request_id in variable using data table.
Actually you are storing 'r' in table which is wrong. Try to store request_id from select statement in variable it will be work .
I got OleDbException: Syntax error in INSERT INTO statement. I think that my INSERT INTO statement is good. Parameters have good data type so it's not problem. Does someone maybe know what's the problem?
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
command.CommandType = CommandType.Text;
command.CommandText = String.Format("INSERT INTO Employees" +
" (ID, Company, Last Name, First Name, E-mail Address, Job Title, Business Phone, Home Phone" +
", Mobile Phone, Fax NUmber, Address, City, State/Province, ZIP/Postal Code, Country/Region, Web Page, Notes)" +
" Values ('{0}', '{1}','{2}','{3}','{4}','{5}'," +
"'{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}')", iD,kompanija,prezime,ime,email,
zvanje,busTelefon,telefon,mobTelefon,fax,adresa,grad,okrug,postanskiBroj,zemlja,web,beleska); zvanje,busTelefon,telefon,mobTelefon,fax,adresa,grad,okrug,postanskiBroj,zemlja,web,beleska);
conn.Open();
command.ExecuteNonQuery();
conn.Close();
Error message:
UDATE SQL:
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
command.CommandType = CommandType.Text;
string cmdText = String.Format(#"UPDATE TABLE Employees " +
"SET" +
" Company='" + kompanija + "'," +
" [Last Name]='" + prezime + "'," +
" [First Name]='" + ime + "'," +
" [E-mail Address]='" + email + "' ," +
" [Job Title]='" + zvanje +"'," +
" [Business Phone]='" + busTelefon + "'," +
" [Home Phone]='" + telefon + "'," +
" [Mobile Phone]='" + mobTelefon + "'," +
" [Fax Number]='" + fax + "'," +
" Address='" + adresa + "'," +
" City='" + grad + "'," +
" [State/Province]='" + okrug + "'," +
" [ZIP/Postal Code]='" + postanskiBroj + "'," +
" [Country/Region]='" + zemlja + "'," +
" [Web Page]='" + web + "'," +
" Notes='" + beleska + "' WHERE ID="+iD);
command.CommandText = cmdText;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
And this SQL don't work. The same error like previous.
When your fields names contain a space or other misleadings characters like the / (division operator) you need them to be enclosed in square brackets
string cmdText = #"INSERT INTO Employees
(ID, Company, [Last Name], [First Name], [E-mail Address],
.., [State/Province], ....) VALUES (....)";
Also you are not using parameters in your query. String.Format is just another type of string concatenation that cannot protect you by invalid inputs (for example, try to use a single quote in your lastname value) and cannot save your code from Sql Injection vulnerability.
You should always use parameterized queries
string cmdText = #"INSERT INTO Employees ( your_field_list_comma_sep)
VALUES (#id, #company, #lastname, #firstname,
......)";
OleDbCommand cmd = new OleDbCommand(cmdText, conn);
cmd.Parameters.Add("#id", OleDbType.Integer).Value = iD;
cmd.Parameters.Add("#company", OleDbType.VarWChar).Value = kompanija;
cmd.Parameters.Add("#lastname", OleDbType.VarWChar).Value = prezime;
cmd.Parameters.Add("#firstname", OleDbType.VarWChar).Value = ime;
....
// add all the other parameters with their name and type
....
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();