So I have been given administration on a website that is basically a company conference room reservation system, it is connected to an access database for room details and vacancies. Problem is, AppScan source is showing a risk of XSS and SQL Injection. This is the complete function in where it is indicating the occurrence of these errors.
protected void btnReserve_Click(object sender, System.EventArgs e)
{
string start_slot, end_slot, event_desc, room_id, emp_nid;
string[] date;
start_slot = ddlStart.SelectedValue;
end_slot = ddlEnd.SelectedValue;
event_desc = txtEventDesc.Text;
room_id = Server.HtmlEncode(Request.QueryString["room_id"]);
emp_nid = Regex.Replace(Request.ServerVariables["LOGON_USER"], #"^.*\\(.*)$", "$1").ToUpper();
date = Request.QueryString["date"].Split('/');
DateTime dt = new DateTime(Convert.ToInt32(date[2]),Convert.ToInt32(date[0]),Convert.ToInt32(date[1]));
string sCmdCheckConflict = #"
SELECT count(*)
FROM t_msc_event
WHERE (event_date = #" +DateTime.Parse(Request.QueryString["date"]).ToString() + #"# )
AND (room_id = " + room_id + #") AND
(
(" + start_slot + #" BETWEEN start_slot AND end_slot) OR
(" + end_slot + #" BETWEEN start_slot AND end_slot) OR
(start_slot BETWEEN " + start_slot + #" AND " + end_slot + #") OR
(end_slot BETWEEN " + start_slot + #" AND " + end_slot + "))";
OleDbCommand cmdConflictCounter = new OleDbCommand(sCmdCheckConflict, cn);
int n;
int event_id;
try
{
cn.Open();
n = (int) cmdConflictCounter.ExecuteScalar();
string Msg;
if (n>0)
{
Msg = "<script language=javascript>alert('Chosen time is not possible due to a conflict.');</script>";
}
else
{
#region MS Access related region
OleDbCommand cmdgetMaxId = new OleDbCommand("select max(event_id) from t_msc_event", cn);
string sCmdInsert;
OleDbCommand cmdInsertEvent = null;
event_id = 0; bool success = false; int trials = 0;
do
{
try
{
event_id = (int) cmdgetMaxId.ExecuteScalar() + 1;
}
catch
{
event_id = 0;
}
sCmdInsert = #"
insert into t_msc_event (event_id,
emp_nid, event_desc, event_date,
start_slot, end_slot, room_id
) values (" + event_id + #",
'" + Server.HtmlEncode(emp_nid) + "', '" + Server.HtmlEncode(event_desc.Replace("'", "''")) + "', #" + dt.ToShortDateString() + "#, " +
start_slot + ", " + end_slot + ", " + room_id + ")";
cmdInsertEvent = new OleDbCommand(sCmdInsert, cn);
cmdInsertEvent.ExecuteNonQuery();
success = true;
} while ((!success) && (trials <=5));
OleDbDataAdapter daGetSlots = new OleDbDataAdapter("select slot_id, left(slot_desc,5) as slot_start, right(slot_desc,5) as slot_end from t_msc_slot order by slot_id", cn);
DataTable dtSlotInfo = new DataTable();
daGetSlots.Fill(dtSlotInfo);
OleDbCommand cmdGetRoolTitle = new OleDbCommand("select room_title from t_msc_room where room_id=" + Server.HtmlEncode(room_id), cn);
string room_title = (string) cmdGetRoolTitle.ExecuteScalar();
string msg = "Dear " + emp_nid +
",<br><br>This is to confirm your reservation of " +
room_title +
" on " + dt.ToShortDateString() + " from " +
dtSlotInfo.Rows[Convert.ToInt32(start_slot)]["slot_start"].ToString() + " to " +
dtSlotInfo.Rows[Convert.ToInt32(end_slot)]["slot_end"].ToString() + "." +
"<br><br>In case you want to cancel, go to " +
"<a href='" + Regex.Replace(Request.Url.ToString(), #"^(.*)/.*\.aspx\?*.*$", "$1/MyReservations.aspx") + "'>" +
"MS Conference Rooms Reservation -> MyReservatios</a>";
#endregion
string subject = "MS Conference Room Reservation Confirmation [id=" + event_id + "]";
try
{
SendEmail(emp_nid, subject, msg);
Msg = "<script language=javascript>alert('Room successfully reserved. You should receive a confirmation email shortly.'); if (opener) {opener.__doPostBack('" + Request.QueryString["btnGetScheduleID"].Replace("_","$") + "', '');} window.close();</script>";
}
catch
{
Msg = "<script language=javascript>alert('Room successfully reserved.'); if (opener) {opener.__doPostBack('" + Request.QueryString["btnGetScheduleID"].Replace("_","$") + "', '');} window.close();</script>";
}
}
Response.Write(Msg);
}
catch (Exception x)
{
Response.Write(x.ToString());
string Msg;
Msg = "<script language=javascript>alert('Error: " + x.ToString() + "');</script>";
Response.Write(Msg);
}
finally
{
cn.Close();
}
}
Sorry for having to show you the whole function as I have really no idea what I need to do here, this isn't my app.
what I did do is 1) Enable Request Validation in ASP.NET 2) encode user input by using Server.HtmlEncode(); but it is still reporting the same thing. Note that both start_slot and end_slot are DDLs so I thought I wouldn't need to encode/check them before sending. Would you please help me in modifying this code to neglect harmful user input? Thank you loads.
The correct way to use parameterized SQL query is
string commandText = "UPDATE ProductDetails
SET ProductQuantity = #quantity WHERE ProductId = #productId";
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.AddWithValue("#productId", "P123");
command.Parameters.AddWithValue("#quantity", 10);
You can safely replace the "P123" with user provided input now.
Related
I am trying to run a SQL query on my UWP code. I don't use Linq or EF. The connection to the base work and the simple requests work. This causes me problems: in a first time i populate a listview with the result of a simple request, i choose an element and i click on a searchin button. This request is call with an error:
static public ObservableCollection GetGaz(string connectionString,
string selectedOrder)
{
string GetGazQuery =
"SELECT " +
"tbl_607_gaz_type.gaz_type," +
"tbl_607_theorical_content.theorical_content," +
"tbl_607_made_tolerance.made_tolerance," +
"tbl_607_order_details.gaz_lifetime," +
"tbl_607_gaz.gaz_comments," +
"tbl_607_order_details.FK_ID_order," +
"tbl_607_order_details.poste_number, " +
"tbl_607_order.order_number" +
"FROM " +
"tbl_607_provider join tbl_607_order on tbl_607_provider.ID = tbl_607_order.FK_ID_provider " +
"join tbl_607_order_details on tbl_607_order.ID = tbl_607_order_details.FK_ID_order" +
"join tbl_607_gaz on tbl_607_order_details.FK_ID_gaz = tbl_607_gaz.ID " +
"join tbl_607_gaz_type on tbl_607_gaz.FK_ID_gaz_type = tbl_607_gaz_type.ID " +
"join tbl_607_made_tolerance on tbl_607_gaz.FK_ID_made_tolerence = tbl_607_made_tolerance.ID " +
"join tbl_607_theorical_content on tbl_607_gaz.FK_ID_theorical_content = tbl_607_theorical_content.ID " +
"WHERE " +
"tbl_607_order.order_number" + " LIKE " + "'%" + selectedOrder + "%'";
ObservableCollection GazList = new ObservableCollection();
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
if (conn.State == System.Data.ConnectionState.Open)
{
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = GetGazQuery;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Gaz gaz = new Gaz
{
Gaz_type = reader.GetString(0),
Theorical_content = reader.GetString(1),
Made_tolerance = reader.GetDouble(2),
Gaz_lifetime = reader.GetInt32(3),
Gaz_comments = reader.GetString(4),
Poste_number = reader.GetInt32(6)
};
GazList.Add(gaz);
}
}
}
}
}
return GazList;
}
catch (Exception eSql)
{
Debug.WriteLine("Exception: " + eSql.Message);
}
return null;
}
}
private string selectedOrder;
public Gestion_Stock()
{
this.InitializeComponent();
SelectOrders.ItemsSource = OrdersDataHelper.GetOrders(connectionString: (Windows.UI.Xaml.Application.Current as App).ConnectionString);
}
private void Search_Click(object sender, RoutedEventArgs e)
{
Affichage_Stock_Gaz.ItemsSource = GazDataHelper.GetGaz((Windows.UI.Xaml.Application.Current as App).ConnectionString, selectedOrder);
}
private void SelectOrders_SelectionChanged (object sender, SelectionChangedEventArgs e)
{
ListView selectOrders = sender as ListView;
Orders orders = SelectOrders.SelectedItem as Orders;
selectedOrder = orders.Order_Number;
}
The output:
Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.SqlClient.dll
Exception: Incorrect syntax near the keyword 'join'
This simple request is working, i don't use a variable and "where" command.
This work:
static public ObservableCollection GetOrders(string connectionString)
{
const string GetOrdersQuery = "" +
"select " +
"tbl_607_order.start_date," +
"tbl_607_order.end_date," +
"tbl_607_provider.provider_name," +
"tbl_607_order.order_number," +
"tbl_607_order.shipping_request_active," +
"tbl_607_order.item_reception_active " +
"from " +
"tbl_607_provider join tbl_607_order on tbl_607_provider.ID = tbl_607_order.FK_ID_provider "
;
Someone would have any idea?
Thanks a lot!
Add the missing space by changing
"SELECT " +
"tbl_607_gaz_type.gaz_type," +
"tbl_607_theorical_content.theorical_content," +
"tbl_607_made_tolerance.made_tolerance," +
"tbl_607_order_details.gaz_lifetime," +
"tbl_607_gaz.gaz_comments," +
"tbl_607_order_details.FK_ID_order," +
"tbl_607_order_details.poste_number, " +
"tbl_607_order.order_number" +
"FROM " +
"tbl_607_provider join tbl_607_order on tbl_607_provider.ID = tbl_607_order.FK_ID_provider " +
"join tbl_607_order_details on tbl_607_order.ID = tbl_607_order_details.FK_ID_order" +
"join tbl_607_gaz on tbl_607_order_details.FK_ID_gaz = tbl_607_gaz.ID " +
"join tbl_607_gaz_type on tbl_607_gaz.FK_ID_gaz_type = tbl_607_gaz_type.ID " +
"join tbl_607_made_tolerance on tbl_607_gaz.FK_ID_made_tolerence = tbl_607_made_tolerance.ID " +
"join tbl_607_theorical_content on tbl_607_gaz.FK_ID_theorical_content = tbl_607_theorical_content.ID " +
"WHERE " +
"tbl_607_order.order_number" + " LIKE " + "'%" + selectedOrder + "%'";
to
"SELECT " +
"tbl_607_gaz_type.gaz_type," +
"tbl_607_theorical_content.theorical_content," +
"tbl_607_made_tolerance.made_tolerance," +
"tbl_607_order_details.gaz_lifetime," +
"tbl_607_gaz.gaz_comments," +
"tbl_607_order_details.FK_ID_order," +
"tbl_607_order_details.poste_number, " +
"tbl_607_order.order_number" +
"FROM " +
"tbl_607_provider join tbl_607_order on tbl_607_provider.ID = tbl_607_order.FK_ID_provider " +
"join tbl_607_order_details on tbl_607_order.ID = tbl_607_order_details.FK_ID_order " + // note the missing space added here
"join tbl_607_gaz on tbl_607_order_details.FK_ID_gaz = tbl_607_gaz.ID " +
"join tbl_607_gaz_type on tbl_607_gaz.FK_ID_gaz_type = tbl_607_gaz_type.ID " +
"join tbl_607_made_tolerance on tbl_607_gaz.FK_ID_made_tolerence = tbl_607_made_tolerance.ID " +
"join tbl_607_theorical_content on tbl_607_gaz.FK_ID_theorical_content = tbl_607_theorical_content.ID " +
"WHERE " +
"tbl_607_order.order_number" + " LIKE " + "'%" + selectedOrder + "%'";
string TJOBCODE1 = ddlJobCode.SelectedItem.Value;
string abc = ddlJobCode.SelectedItem.ToString();
string TJob_Name = abc.Substring(0, abc.IndexOf('['));
string TRo_Name = abc.Substring(abc.LastIndexOf('[') + 1);
TRo_Name = TRo_Name.Replace("]", "");
string TJOBCODE = TJOBCODE1;
SqlCommand fsql = new SqlCommand("SELECT COUNT(*) AS REC FROM [MTS_TV_RO_TC_FINAL] where JOB_CODE='" + TJOBCODE + "' AND AGENCY_CODE in( select agency_code FROM " + tmptvrlbktbl + ")", Global.con1);
SqlDataAdapter Fda1 = new SqlDataAdapter(fsql);
DataTable Fdt1 = new DataTable();
Fda1.Fill(Fdt1);
int DD = Convert.ToInt32(Fdt1.Rows[0].ItemArray.GetValue(0).ToString());
if (DD == 0)
{
string INSQURY = " insert into [MTS_TV_RO_TC_FINAL] ([DATE],[CAPTION_NAME],[IST],[DURATION],[AMOUNT],[CRID],[JOB_CODE],[AGENCY_CODE],[STATUS],[TBAND_IN],[TBAND_OUT],[DATE_FROM],[DATE_TO],[CREATE_DATE],[USER_NAME],[REMARKS],[Ro_Name],[Job_Name]) SELECT [DATE],[CAPTION],[IST],[DURATION],[AMOUNT],[CRID],'" + TJOBCODE + "',[Agency_code],[STAT],[TBAND_IN],[TBAND_OUT],'" + COMP_FROM + "','" + COMP_TO + "',GETDATE() AS DT,'" + Global.uname + "' ,[REMARKS],'" + TRo_Name + "','" + TJob_Name + "' FROM " + tmptvrlbktbl + " ORDER BY DATE";
SqlCommand cmd1 = new SqlCommand(INSQURY, Global.con1);
cmd1.ExecuteNonQuery();
Alert.show1("Data Saved Successfully", this);
}
else
{
Alert.show1("Data Already Saved", this);
return;
}
The code was perfectly fine, there was an issue with the excel sheet. i changed the query to parametrized and changed the excel sheet as well and it worked.
Change insQury to
string INSQURY = " insert into [MTS_TV_RO_TC_FINAL] ([DATE],[CAPTION_NAME],[IST],[DURATION],[AMOUNT],[CRID],[JOB_CODE],[AGENCY_CODE],[STATUS],[TBAND_IN],[TBAND_OUT],[DATE_FROM],[DATE_TO],[CREATE_DATE],[USER_NAME],[REMARKS],[Ro_Name],[Job_Name]) SELECT [DATE],[CAPTION],[IST],[DURATION],[AMOUNT],[CRID],'" + TJOBCODE + "',[Agency_code],[STAT],[TBAND_IN],[TBAND_OUT],COMP_FROM, COMP_TO,GETDATE() AS DT,'" + Global.uname + "' ,[REMARKS],'" + TRo_Name + "','" + TJob_Name + "' FROM " + tmptvrlbktbl + " ORDER BY DATE";
If COMP_FROM and COMP_TO are dates already you don't need to surround them with single quotation marks.
I have been working on a software which uses database which is shared with multiple PCs. The project is all about to store missing baggage information. We have given a facility to copy the newly inserted record into the master DB.
Now what here happens is when multiple users are trying to update the db at the same time single item get stored for multiple time in the global DB.
So I have tried to use TableLock using serializable but I got nothing here.
Edit
query = "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;BEGIN TRANSACTION;";
insertdata(query); //using cmd.ExecuteNonQuery();
query = "select * from Goods WITH (TABLOCKX)" ;
DataSet dsGoods = getdata(query, "config");//Function to get the data
updateitem();
query = "COMMIT TRANSACTION";
insertdata(query);//using cmd.ExecuteNonQuery();
And the updateitem() is as follow
public static void updateitem()
{
string query = "select * from config where param='lastsync'";
DataSet ds = dataaccess.getdata(query, "config");
query = "select isonlive,associateid,itemid,founddate,regdate,status,foundbyname,categoryid,subcatid,item,model,color,foundwhere,returnedtoname,showonline,officeid,isdeleted,(select username from [user] where userid=registeredby) as reguser,(select username from [user] where userid=returnby) as returnedby,notes,returneddate from item ";
String updatedDate =ds.Tables[0].Rows[0]["value"].ToString();
if (updatedDate != "")
{
query = "select isonlive,associateid,itemid,founddate,regdate,foundbyname,status,categoryid,subcatid,item,model,color,foundwhere,returnedtoname,officeid,showonline,isdeleted,(select username from [user] where userid=registeredby) as reguser,(select username from [user] where userid=returnby) as returnedby,notes,returneddate from item where updateat >= #updateat";
}
System.Data.SqlClient.SqlCommand cmd = new SqlCommand(query);
if (updatedDate != "")
{
cmd.Parameters.AddWithValue("#updateat",DateTime.ParseExact(updatedDate,"dd-MM-yyyy HH:mm:ss",null,System.Globalization.DateTimeStyles.None));
}
DataRow dr;
ds = dataaccess.getdata(cmd, "item");
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
try
{
int status = 0;
dr = ds.Tables[0].Rows[i];
if (dr["status"].ToString() == "Transferred")
{
status = 2;
}
else if (dr["status"].ToString() != "Received")
{
status = 1;
}
DateTime regdate = Convert.ToDateTime(dr["regdate"]);
DateTime founddate = Convert.ToDateTime(dr["founddate"]);
//returndatetime = String.Format("MMM dd yyyy H:mm:ss", returndate);
if (dr["showonline"].ToString() == "False")
{
status = 1;
}
if (dr["isdeleted"].ToString() == "true")
{
insertdata("delete from goods where AssociateID='" + dr["associateid"] + "' and ID='" + dr["itemid"] + "'");
continue;
}
if (dr["isonlive"].ToString() == "true")
{
query = "update goods set Status='" + status + "',officeid='" + dr["officeID"] + "', notes='" + dr["notes"].ToString().Replace("'", "''") + "',ReturnedTo='" + dr["returnedtoname"].ToString().Replace("'", "''") + "',founddate=#founddate,ReturnedDate=#returndate,ReturnedBy='" + dr["returnedby"].ToString().Replace("'", "''") +
"',Model='" + dr["model"].ToString().Replace("'", "''") + "',ColorID='" + dr["color"].ToString().Replace("'", "''") + "',FoundWhere='" + dr["foundwhere"].ToString().Replace("'", "''") + "',MainCat='" + dr["categoryid"] + "',SubCat='" + dr["subcatid"] + "',ItemID='" + dr["item"] + "' where AssociateID='" + dr["associateid"] + "' and ID='" + dr["itemid"] + "'";
}
else
{
query = "select * from goods where AssociateID='" + dr["associateid"] + "' and ID='" + dr["itemid"] + "' and MainCat='" + dr["categoryid"] + "' and SubCat='" + dr["subcatid"] + "' and ItemID='" + dr["item"] + "'";
DataSet dsItems = getdata(query, "config");
if(dsItems.Tables[0].Rows.Count==0)
{
query = "insert into goods (AssociateID,ID,DateReg,Status,MainCat,SubCat,ItemID,Model,ColorID,FoundWhere,RegBy,FoundBy,ReturnedTo,ReturnedDate,ReturnedBy,Notes,IP,founddate,officeid) values('" + dr["associateid"] + "','" + dr["itemid"] + "',#regdate,'" + status + "'," +
"'" + dr["categoryid"] + "','" + dr["subcatid"] + "','" + dr["item"] + "','" + dr["model"].ToString().Replace("'", "''") + "','" + dr["color"].ToString().Replace("'", "''") + "'," +
"'" + dr["foundwhere"].ToString().Replace("'", "''") + "','" + dr["reguser"].ToString().Replace("'", "''") + "','" + dr["reguser"].ToString().Replace("'", "''") + "','" + dr["returnedtoname"].ToString().Replace("'", "''") + "',#returndate," +
"'" + dr["returnedby"].ToString().Replace("'", "''") + "','" + dr["notes"].ToString().Replace("'", "''") + "','',#founddate,'" + dr["officeID"].ToString() + "')";
}
}
SqlCommand sce = new SqlCommand(query);
if (dr["returneddate"].ToString() != "")
{
sce.Parameters.AddWithValue("#returndate", Convert.ToDateTime(dr["returneddate"]));
}
else
{
sce.Parameters.Add("#returndate", SqlDbType.DateTime).Value = DBNull.Value;
}
sce.Parameters.AddWithValue("#regdate", regdate);
sce.Parameters.AddWithValue("#founddate", founddate);
insertdata(sce);
query = "update item set isonlive = 'true',updateat=#updateDate where itemid = '" + dr["itemid"] + "'";
sce = new SqlCommand(query);
sce.Parameters.AddWithValue("#updateDate", DateTime.Now);
dataaccess.insertdata(sce);
}
catch (Exception ex)
{
App.writelog(ex.Message + "\n" + ex.StackTrace);
}
}
}
P.S.: I want it to be done though ASP.Net.
I wanted to update the values of a few columns of a database table, using queries or stored procedure, but wanted to use my C# library to alter the value.
For eg, I want the columns A,B,C of table T to be replaced with Encrypt(A), Encrypt(B) and Encrypt(C) where Encrypt is a part of a C# library. I could have done it in a simple console application, but I have to do this process for a lot of columns in lot of tables.
Could I use a SQLCLR stored procedure / query to do this process in SQL Server Management Studio? It will be really great if someone could assist in this.
public class SP
{
[Microsoft.SqlServer.Server.SqlFunction()]
public static void Enc()
{
using (SqlConnection connection = new SqlConnection("context connection=true"))
{
connection.Open();
SqlCommand command;
SqlCommand command1;
for (int i = 0; i < 1; i++)
{
command = new SqlCommand("SELECT " + tableFieldArray[i, 1].ToString() + " FROM " + tableFieldArray[i, 0].ToString(), connection);
SqlDataReader reader = command.ExecuteReader();
using (reader)
{
while (reader.Read())
{
if (!reader.IsDBNull(0) && !String.IsNullOrEmpty(reader.GetString(0)))
{
//SqlContext.Pipe.Send("Data = " + reader.GetString(0) + "; Encrypted = " + Encrypt(reader.GetString(0)));
SqlContext.Pipe.Send("UPDATE " + tableFieldArray[i, 0].ToString() + " SET "
+ tableFieldArray[i, 1].ToString() + " = '" + Encrypt(reader.GetString(0)) + "' "
+ "WHERE " + tableFieldArray[i, 1].ToString() + " = '" + reader.GetString(0) + "'");
//query = "UPDATE " + tableFieldArray[i, 0].ToString() + " SET "
// + tableFieldArray[i, 1].ToString() + " = '" + Encrypt(reader.GetString(0)) + "' "
// + "WHERE " + tableFieldArray[i, 1].ToString() + " = '" + reader.GetString(0) + "'";
command1 = new SqlCommand("UPDATE " + tableFieldArray[i, 0].ToString() + " SET "
+ tableFieldArray[i, 1].ToString() + " = '" + Encrypt(reader.GetString(0)) + "' "
+ "WHERE " + tableFieldArray[i, 1].ToString() + " = '" + reader.GetString(0) + "'",connection);
}
}
}
SqlCommand command1 = new SqlCommand(query , connection);
command1.ExecuteNonQuery();
}
connection.Close();
}
}
public static string Encrypt(string TextFromForm)
{
//implementation
}
}
}
You can use SQLCLR to call encryption from C#, though this is the wrong approach. If you need to do a custom algorithm, you should encapsulate that into a SQLCLR function so that it can be used in an UPDATE statement or even an INSERT or SELECT or anywhere. Something like:
public class SP
{
[Microsoft.SqlServer.Server.SqlFunction(IsDeterministic = true)]
public static SqlString EncryptByAES(SqlString TextToEncrypt)
{
return DoSomething(TextToEncrypt.Value);
}
}
Then you can use that function as follows:
UPDATE tb
SET tb.FieldA = EncryptByAES(tb.FieldA)
FROM dbo.TableName tb
WHERE tb.FieldA some_test_to_determine_that_FieldA_is_not_alreay_encrypted;
BUT, before you write a custom encryption algorithm, you might want to check out the several built-in paired ENCRYPTBY / DECRYPTBY functions that might do exactly what you need:
ENCRYPTBYASYMKEY / DECRYPTBYASYMKEY
ENCRYPTBYCERT / DECRYPTBYCERT
ENCRYPTBYKEY / DECRYPTBYKEY
ENCRYPTBYPASSPHRASE / DECRYPTBYPASSPHRASE
What's wrong with this SQL UPDATE statement?
try
{
int ageValue = Int32.Parse(age.Text);
string updateQuery = "Update \nMyTable \nSet \nFName = '" + fname.Text.ToString() + "',\nLName = '" + lname.Text.ToString() + "',\nAge = " + ageValue + ",\nCome = '" + from.Text.ToString() + "',\nTo = '" + to.Text.ToString() + "' Where Age=" + ageValue + ";";
MessageBox.Show(updateQuery);
OleDbConnection con = new OleDbConnection("provider=Microsoft.JET.OLEDB.4.0; Data Source = Database5.mdb");
OleDbCommand com = new OleDbCommand(updateQuery, con);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
catch (FormatException ex)
{
MessageBox.Show(ex.Message);
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
}
I received that error
Syntax error in Update statement
What is wrong in that SQL Update?
Tools:
Microsoft Access 2003
Microsoft Visual Studio 2010 C#
Please help and thanks in advance
Try getting rid of the \n junk.
string updateQuery = "Update MyTable Set FName = '" + fname.Text.ToString() + "',LName = '" + lname.Text.ToString() + "',Age = " + ageValue + ",Come = '" + from.Text.ToString() + "',To = '" + to.Text.ToString() + "' Where Age=" + ageValue;
Output the result of the concatination and try to run it. If that doesn't work, post the result of the concatination here and someone should be able to help. Without knowing the result of the concatination, it's difficult to know what's wrong.
Try changing the query like this (removing \ns and the final ;)
string updateQuery = "Update MyTable Set FName = '" + fname.Text.ToString() +
"', LName = '" + lname.Text.ToString() + "', Age = " + ageValue +
", Come = '" + from.Text.ToString() + "', To = '" + to.Text.ToString() +
"' Where Age=" + ageValue;
I would suggest you put the Sql Profiler on and trace your update query because it is easy to read the concatenated query string
Hello you can try with this code
StringBuilder stringBuilder = new StringBuilder() ;
stringBuilder.Append("Update MyTable Set FName = ") ;
stringBuilder.Append(fname.Text.ToString()) ;
stringBuilder.Append(",\nLName = ") ;
stringBuilder.Append(lname.Text.ToString()) ;
stringBuilder.Append(",\nAge = ") ;
stringBuilder.Append(ageValue) ;
stringBuilder.Append(",\nCome = ") ;
stringBuilder.Append(from.Text.ToString()) ;
stringBuilder.Append(",\nTo = ") ;
stringBuilder.Append(to.Text.ToString()) ;
stringBuilder.Append(" Where Age=") ;
stringBuilder.Append(ageValue) ;
stringBuilder.Append(";") ;
var result = stringBuilder.ToString();
This is how I write my inline SQL in C sharp:
string strSQL = "";
strSQL += " Update MyTable Set ";
strSQL += " FName = '" + fname.Text.ToString() + "' ";
strSQL += " ,LName = '" + lname.Text.ToString() + "' ";
strSQL += " ,Age = '" + ageValue + "' ";
strSQL += " ,Come = '" + from.Text.ToString() + "' ";
strSQL += " ,To = '" + to.Text.ToString() + "' ";
strSQL += " Where Age = '" + ageValue + "' ";
Easy to read and works fine.
You can also add this just below your query before you connent to your database:
Response.Write(strSQL);
return;
this will show you whats being posted to the server and makes it a little easier to find errors.