ASP.NET C# Missing Expression Error during Oracle insert - c#
May I start off by saying this is my 1st assigned database project in 10 years... and 1st time doing it in C#. I am "simply" trying to insert form data into an Oracle table using OleDB.
I keep getting "ORA-00936: missing expression". Below is my code... any idea what's missing?
public string getConnString()
{
//set the connection string from web config file
return WebConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
}
private void executeInsert(string EventType, string EventSubType, string DeptName, string EventDate, string Duration, string EventName, string EventAdd, string WardNo, string Program, string NumAtt, string StTime, string EndTime, string MngName, string RecKeeper)
{
OleDbConnection conn = new OleDbConnection(getConnString());
string sql = "INSERT INTO APPS.CLV_EVENT_TRACK (EVENTTYPE, EVENTSUBTYPE, DEPTNAME, EVENTDATE, DURATION, EVENTNAME, EVENTADD, WARDNO, PROGRAM, NUMATT, STARTTIME, ENDTIME, MNGNAME, RECORDKEEPER) VALUES "
+ "(#EventType, #EventSubType, #DeptName, TO_DATE(#EventDate, 'Month dd, YYYY'), #Duration, #EventName, #EventAdd, #WardNo, #Program, #NumAtt, TO_DATE(#StTime, 'HH:MI:SS PM'), TO_DATE(#EndTime, 'HH:MI:SS PM'), #MngName, #RecKeeper)";
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(sql, conn);
OleDbParameter[] param = new OleDbParameter[14];
param[0] = new OleDbParameter("#EventType", OleDbType.VarChar, 25);
param[1] = new OleDbParameter("#EventSubType", OleDbType.VarChar, 80);
param[2] = new OleDbParameter("#DeptName", OleDbType.VarChar, 240);
param[3] = new OleDbParameter("#EventDate", OleDbType.Date);
param[4] = new OleDbParameter("#Duration", OleDbType.Numeric);
param[5] = new OleDbParameter("#EventName", OleDbType.VarChar, 80);
param[6] = new OleDbParameter("#EventAdd", OleDbType.VarChar, 150);
param[7] = new OleDbParameter("#WardNo", OleDbType.VarChar, 25);
param[8] = new OleDbParameter("#Program", OleDbType.VarChar, 150);
param[9] = new OleDbParameter("#NumAtt", OleDbType.Numeric);
param[10] = new OleDbParameter("#StTime", OleDbType.Date);
param[11] = new OleDbParameter("#EndTime", OleDbType.Date);
param[12] = new OleDbParameter("#MngName", OleDbType.VarChar, 150);
param[13] = new OleDbParameter("#RecKeeper", OleDbType.VarChar, 150);
param[0].Value = EventType;
param[1].Value = EventSubType;
param[2].Value = DeptName;
param[3].Value = EventDate;
param[4].Value = Duration;
param[5].Value = EventName;
param[6].Value = EventAdd;
param[7].Value = WardNo;
param[8].Value = Program;
param[9].Value = NumAtt;
param[10].Value = StTime;
param[11].Value = EndTime;
param[12].Value = MngName;
param[13].Value = RecKeeper;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (Exception ex) { throw ex; }
finally
{
conn.Close();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
var start = DateTime.Parse(txtStTime.Text);
var end = DateTime.Parse(txtEndTime.Text);
TimeSpan duration = end.Subtract(start);
string meetDuration = duration.TotalMinutes.ToString();
executeInsert(rbEventType.SelectedItem.Text, ddVolType.SelectedItem.Text,
txtDept.Text, txtEventDate.Text, meetDuration, txtEventName.Text,
txtEventAdd.Text, ddWard.SelectedItem.Value, txtSBPlan.Text, txtNumVol.Text,
txtStTime.Text, txtEndTime.Text, txtEventMgr.Text, txtRecording.Text);
}
UPDATE to code:
public string getConnString()
{
//set the connection string from web config file
return WebConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
}
private void executeInsert(string EventType, string EventSubType, string DeptName, string EventDate, string Duration, string EventName, string EventAdd, string WardNo, string Program, string NumAtt, string StTime, string EndTime, string MngName, string RecKeeper)
{
OleDbConnection conn = new OleDbConnection(getConnString());
string sql = "INSERT INTO APPS.CLV_EVENT_TRACK (EVENTTYPE, EVENTSUBTYPE, DEPTNAME, EVENTDATE, DURATION, EVENTNAME, EVENTADD, WARDNO, PROGRAM, NUMATT, STARTTIME, ENDTIME, MNGNAME, RECORDKEEPER) VALUES "
+ "(#EventType, #EventSubType, #DeptName, TO_DATE(#EventDate, 'Month dd, YYYY'), #Duration, #EventName, #EventAdd, #WardNo, #Program, #NumAtt, TO_DATE(#StTime, 'HH:MI:SS PM'), TO_DATE(#EndTime, 'HH:MI:SS PM'), #MngName, #RecKeeper)";
try
{
conn.Open();
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#EventType", EventType),
new OleDbParameter("#EventSubType", EventSubType),
new OleDbParameter("#DeptName", DeptName),
new OleDbParameter("#EventDate", EventDate),
new OleDbParameter("#Duration", Duration),
new OleDbParameter("#EventName", EventName),
new OleDbParameter("#EventAdd", EventAdd),
new OleDbParameter("#WardNo", WardNo),
new OleDbParameter("#Program", Program),
new OleDbParameter("#NumAtt", NumAtt),
new OleDbParameter("#StTime", StTime),
new OleDbParameter("#EndTime", EndTime),
new OleDbParameter("#MngName", MngName),
new OleDbParameter("#RecKeeper", RecKeeper)
});
cmd.ExecuteNonQuery();
}
}
catch (Exception ex) { throw ex; }
finally
{
conn.Close();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
var start = DateTime.Parse(txtStTime.Text);
var end = DateTime.Parse(txtEndTime.Text);
TimeSpan duration = end.Subtract(start);
string meetDuration = duration.TotalMinutes.ToString();
executeInsert(rbEventType.SelectedItem.Text, ddVolType.SelectedItem.Text,
txtDept.Text, txtEventDate.Text, meetDuration, txtEventName.Text,
txtEventAdd.Text, ddWard.SelectedItem.Value, txtSBPlan.Text, txtNumVol.Text,
txtStTime.Text, txtEndTime.Text, txtEventMgr.Text, txtRecording.Text);
}
What a lesson to learn. Apparently an ORACLE parameter has to be presented as a "?"
So, my final code... that actually successfully inserts a record is:
public string getConnString()
{
//set the connection string from web config file
return WebConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
}
private void executeInsert()
{
OleDbConnection conn = new OleDbConnection(getConnString());
string sql = "INSERT INTO APPS.CLV_EVENT_TRACK (EVENTTYPE, EVENTSUBTYPE, DEPTNAME, EVENTDATE, DURATION, EVENTNAME, EVENTADD, WARDNO, PROGRAM, NUMATT, STARTTIME, ENDTIME, MNGNAME, RECORDKEEPER) ";
sql += "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try
{
var start = DateTime.Parse(txtStTime.Text);
var end = DateTime.Parse(txtEndTime.Text);
TimeSpan duration = end.Subtract(start);
string meetDuration = duration.TotalMinutes.ToString();
conn.Open();
using (OleDbCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sql;
cmd.Parameters.Add("?", OleDbType.VarChar).Value = rbEventType.SelectedItem.Text;
cmd.Parameters.Add("?", OleDbType.VarChar).Value = ddVolType.SelectedItem.Text;
cmd.Parameters.Add("?", OleDbType.VarChar).Value = txtDept.Text;
cmd.Parameters.Add("?", OleDbType.Date).Value = txtEventDate.Text;
cmd.Parameters.Add("?", OleDbType.Numeric).Value = meetDuration;
cmd.Parameters.Add("?", OleDbType.VarChar).Value = txtEventName.Text;
cmd.Parameters.Add("?", OleDbType.VarChar).Value = txtEventAdd.Text;
cmd.Parameters.Add("?", OleDbType.VarChar).Value = ddWard.SelectedItem.Value;
cmd.Parameters.Add("?", OleDbType.VarChar).Value = txtSBPlan.Text;
cmd.Parameters.Add("?", OleDbType.Numeric).Value = txtNumVol.Text;
cmd.Parameters.Add("?", OleDbType.Date).Value = txtStTime.Text;
cmd.Parameters.Add("?", OleDbType.Date).Value = txtEndTime.Text;
cmd.Parameters.Add("?", OleDbType.VarChar).Value = txtEventMgr.Text;
cmd.Parameters.Add("?", OleDbType.VarChar).Value = txtRecording.Text;
cmd.ExecuteNonQuery();
}
}
catch (Exception ex) { throw ex; }
finally
{
conn.Close();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
executeInsert();
}
Related
Session inside datatable in c#.net
In the below code , Session["FirstName"] = SCode.ToString(); is having error (the name session does not exist in current context).thanks public DataTable Searchup(string SiteCode = "", string EmployeeRole = "") { DbConnection conn = _dataFactory.CreateConnection(); DbDataAdapter da = _dataFactory.CreateDataAdapter(); DataTable dt = null; try { conn.ConnectionString = _connectionString; conn.Open(); da.SelectCommand = conn.CreateCommand(); da.SelectCommand.CommandType = CommandType.Text; DbParameter param = null; string sql = "SELECT ID,SITECODE,EMPLOYEEROLE,EMPLOYEEID, FROM " + _tblnpf + "User WHERE Empl <> 'Admin' "; if (!String.IsNullOrEmpty(SiteCode.Trim())) { sql += "AND SiteCode = #SiteCode "; OracleHelper.CreateParameter(ref da, ref param, "#SiteCode", DbType.String, ParameterDirection.Input, SiteCode); Session["FirstName"] = SCode.ToString(); } da.SelectCommand.CommandText = OracleHelper.FixCommandText(sql); DataTable dt1 = new DataTable("User"); da.Fill(dt1);
Error in registration form code
I'm creating a registration form using using Visual Studio 2015, but when I run my code some problem occurs. I receive the error as stated bellow: I could not found the problem with my code: private void execution(string RNumber, string fname, string lname, string Password, string Gender, string CPassword, string Email) { SqlConnection conn = new SqlConnection(GetConnectionString()); string sql = "INSERT INTO Table(RNumber, fname, lname, Password, Gender, CPassword, Email) VALUES " + " (#RNumber, #fname, #lname, #Password, #Gender, #CPassword, #Email)"; try { conn.Open(); SqlCommand cmd = new SqlCommand(sql, conn); SqlParameter[] pram = new SqlParameter[7]; pram[0] = new SqlParameter("#RNumber", SqlDbType.VarChar, 50); pram[1] = new SqlParameter("#fname", SqlDbType.VarChar, 50); pram[2] = new SqlParameter("#lname", SqlDbType.VarChar, 50); pram[3] = new SqlParameter("#Password", SqlDbType.VarChar, 50); pram[4] = new SqlParameter("#Gender", SqlDbType.VarChar, 50); pram[5] = new SqlParameter("#CPassword", SqlDbType.VarChar, 50); pram[6] = new SqlParameter("#Email", SqlDbType.VarChar, 50); pram[0].Value = RNumber; pram[1].Value = fname; pram[2].Value = lname; pram[3].Value = Password; pram[4].Value = Gender; pram[5].Value = CPassword; pram[6].Value = Email; for (int i = 0; i < pram.Length; i++) { cmd.Parameters.Add(pram[i]); } cmd.CommandType = CommandType.Text; cmd.ExecuteNonQuery(); } catch (System.Data.SqlClient.SqlException ex_msg) { string msg = "Error occured while inserting"; msg += ex_msg.Message; throw new Exception(msg); } finally { //Here will be fially elements conn.Close(); } } protected void Page_Load(object sender, EventArgs e) { this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None; } protected void Buttonsubmit_Click(object sender, EventArgs e) { if (TextBoxregstr.Text == "") { Response.Write("Please complete the form."); } else { execution(TextBoxregstr.Text, TextBoxfirst.Text, TextBoxlast.Text, TextBoxpswrd.Text, TextBoxcnfrmpswrd.Text, TextBoxgender.Text, TextBoxemail.Text); Confirm.Visible = true; TextBoxfirst.Text = ""; TextBoxlast.Text = ""; TextBoxpswrd.Text = ""; TextBoxgender.Text = ""; TextBoxcnfrmpswrd.Text = ""; TextBoxemail.Text = ""; TextBoxregstr.Text = ""; } }
As the error indicates, Incorrect syntax near the keyword 'Table' It happens because TABLE is a reserved keyword for T-SQL. your query should enclose TABLE in square brackets string sql = "INSERT INTO [Table] Better way to handle is you change the name and use a more descriptive word for the table
Update in C# using repository, new window and main window
This is my code used for updating a customer in c#, can someone help me correcting the code, so that it will work smoothly? This is my repository code: public static void KlantWijzigen(Klant klan) { string commandString = string.Format("UPDATE tblKlanten (Adres, Postcode, Gemeente, Email, Telefoonnummer) SET('{0}','{1}','{2}','{3}','{4}')", klan.Adres, klan.Postcode, klan.Gemeente, klan.Email, klan.Telefoonnummer); OleDbConnection conn = new OleDbConnection(connectionString); OleDbCommand command = new OleDbCommand(); OleDbDataAdapter adapter = new OleDbDataAdapter(); conn.Open(); //commandstring toevoegen aan adapter command.Connection = conn; command.CommandText = commandString; adapter.UpdateCommand = command; //command uitvoeren adapter.UpdateCommand.ExecuteNonQuery(); //databank connect conn.Close(); } My new window code: public partial class WindowKlantWijzig : Window { public WindowKlantWijzig() { InitializeComponent(); } private void buttonSlaOp_Click(object sender, RoutedEventArgs e) { Klant upda = new Klant(); upda.Naam = textBoxNieuweNaam.Text; upda.Adres = textBoxAdresNieuw.Text; upda.Postcode = Convert.ToInt32(textBoxPostcodeNieuw.Text); upda.Gemeente = textBoxGemeenteNieuw.Text; upda.Email = textBoxEmailNieuw.Text; upda.Telefoonnummer = textBoxTelefoonnummerNieuw.Text; KlantRepository.KlantWijzigen(upda); MessageBox.Show("De klant werd succesvol gewijzigd"); } } And this is my main window code private void buttonWijzigKlant_Click(object sender, RoutedEventArgs e) { if (comboBoxKlanten.SelectedIndex == -1) { MessageBox.Show("Selecteer de klant die je wil wijzigen"); } else { // TODO: gebruiker eerst om bevestiging vragen Klant klan = (Klant)comboBoxKlanten.SelectedItem; KlantRepository.KlantWijzigen(klan); MessageBox.Show("De klant werd succesvol gewijzigd"); //combobox wordt vernieuwd comboBoxKlanten.ItemsSource = null; comboBoxKlanten.ItemsSource = KlantRepository.AlleKlanten(); } }
As response on the question from the comments, I would do it like this: (untested/pseudo) So this is NOT the answer, but a response to prevent SQL-injections. public static void KlantWijzigen(Klant klan) { string commandString = "UPDATE tblKlanten (Adres, Postcode, Gemeente, Email, Telefoonnummer) SET(#Adres, #Postcode, #Gemeente, #Email, #Telefoonnummer)"; using(OleDbConnection conn = new OleDbConnection(connectionString)) using(OleDbCommand command = new OleDbCommand()) { conn.Open(); //commandstring toevoegen aan adapter command.Connection = conn; command.CommandText = commandString; // de velden zetten via de parameters, zodat SQL-injection niet werkt. command.Parameters.Add("Adres", OleDbType.VarChar).Value = klan.Adres; command.Parameters.Add("Postcode", OleDbType.VarChar).Value = klan.Postcode; command.Parameters.Add("Gemeente", OleDbType.VarChar).Value = klan.Gemeente; command.Parameters.Add("Email", OleDbType.VarChar).Value = klan.Email; command.Parameters.Add("Telefoonnummer", OleDbType.VarChar).Value = klan.Telefoonnummer; OleDbDataAdapter adapter = new OleDbDataAdapter(); adapter.UpdateCommand = command; //command uitvoeren adapter.UpdateCommand.ExecuteNonQuery(); } } Don't forget... you're missing a Where clause.. so you are updating ALL records. You might change (something like): string commandString = #" UPDATE tblKlanten (Adres, Postcode, Gemeente, Email, Telefoonnummer) SET(#Adres, #Postcode, #Gemeente, #Email, #Telefoonnummer) WHERE id = #Id"; // <<-------------- command.Parameters.Add("Id", OleDbType.Integer).Value = klan.Id;
remote database not updating after entering fields
I had made a registration page of the following code & when ever i run the code for enter data i am getting no errors , but when i refresh my remote database the field/information is not updated, I don't know where i am making mistake... Here i am calling out my connection string from my web.config file. public string GetConnectionString() { //sets the connection string from your web config file "ConnString" is the name of your Connection String return System.Configuration.ConfigurationManager.ConnectionStrings["RN_DBConnectionString"].ConnectionString; } below is the code, i am getting no errors in it but my remote database is been not updated. Iam doing something wrong..???? private void ExecuteInsert(string FName, string LName, string EID, string Password, string RPassword, string Organization, string WPhone, string CPhone, string Country, string City, string State, string Address) { SqlConnection conn = new SqlConnection(GetConnectionString()); string sql = "INSERT INTO RN_DB.dbo.Table (FName, LName, EID, Password, RPassword, Organization, WPhone,CPhone,Country, City, State, Address) VALUES " + " (#FName,#LName,#EID,#Password,#RPassword,#Organization,#WPhone,#CPhone,#Country,#City,#State,#Addess)"; try { conn.Open(); SqlCommand cmd = new SqlCommand(sql, conn); SqlParameter[] param = new SqlParameter[12]; //param[0] = new SqlParameter("#id", SqlDbType.NVarChar, 50); param[0] = new SqlParameter("#FName", SqlDbType.NVarChar, 50); param[1] = new SqlParameter("#LName", SqlDbType.NVarChar, 50); param[2] = new SqlParameter("#EID", SqlDbType.NVarChar, 50); param[3] = new SqlParameter("#Password", SqlDbType.NVarChar, 50); param[4] = new SqlParameter("#RPassword", SqlDbType.NVarChar, 50); param[5] = new SqlParameter("#Organization", SqlDbType.NVarChar, 50); param[6] = new SqlParameter("#WPhone", SqlDbType.NVarChar, 50); param[7] = new SqlParameter("#CPhone", SqlDbType.NVarChar, 50); param[8] = new SqlParameter("#Country", SqlDbType.NVarChar, 50); param[9] = new SqlParameter("#City", SqlDbType.NVarChar, 50); param[10] = new SqlParameter("#State", SqlDbType.NVarChar, 50); param[11] = new SqlParameter("#Address", SqlDbType.Text); param[0].Value = FName; param[1].Value = LName; param[2].Value = EID; param[3].Value = Password; param[4].Value = RPassword; param[5].Value = Organization; param[6].Value = WPhone; param[7].Value = CPhone; param[8].Value = City; param[9].Value = Country; param[10].Value = State; param[11].Value = Address; for (int i = 0; i < param.Length; i++) { cmd.Parameters.Add(param[i]); } cmd.CommandType = CommandType.Text; cmd.ExecuteNonQuery(); } catch (System.Data.SqlClient.SqlException ex) { string msg = "Insert Error:"; msg += ex.Message; } finally { conn.Close(); } } protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { if (Pass.Text == RPass.Text) { Guid newGUID = Guid.NewGuid(); //call the method to execute insert to the database ExecuteInsert(FName.Text, LName.Text, EID.Text, Pass.Text, RPass.Text, Org.Text, WPhone.Text, CPhone.Text, Country.Text, City.Text, State.Text, Address.Text); Response.Write("Record was successfully added!"); } else { Response.Write("Password's didnot match"); Pass.Focus(); }
You probably have an error message, but you lose it here: catch (System.Data.SqlClient.SqlException ex) { string msg = "Insert Error:"; msg += ex.Message; } Your msg local variable gets the message you need, but you do not show it anywhere. You need to do something: either show it somewhere or throw the exception further.
Updating records
private void button1_Click(object sender, EventArgs e) { using (SqlConnection sqlConn = new SqlConnection("Data Source=TANYA-PC;Initial Catalog=biore1;Integrated Security=True")) { string sqlQuery = #"UPDATE cottonpurchase SET #slipNo, #basicprice, #weight, #totalamountbasic, #premium, #totalamountpremium, #totalamountpaid, #yeildestimates WHERE farmercode = #farmercode"; { SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn); cmd.Parameters.Add("#slipNo", SqlDbType.Int).Value = TxtSlipNo.Text; cmd.Parameters.Add("#basicprice", SqlDbType.Int).Value = TxtBasicPrice.Text; cmd.Parameters.Add("#weight", SqlDbType.Int).Value = TxtWeight.Text; cmd.Parameters.Add("#totalamountbasic", SqlDbType.Int).Value = TxtTotalAmountBasic.Text; cmd.Parameters.Add("#premium", SqlDbType.Int).Value = TxtPremium.Text; cmd.Parameters.Add("#totalamountpremium", SqlDbType.Int).Value = TxtTotalAmountPremium.Text; cmd.Parameters.Add("#totalamountpaid", SqlDbType.Int).Value = TxtTotalAmountPaid.Text; cmd.Parameters.Add("#yeildestimates", SqlDbType.Int).Value = TxtYeildEstimates.Text; sqlConn.Open(); try { cmd.ExecuteNonQuery(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } It's giving me an error even though everything seems fine with my code: error : incorrect syntax near ','
You need to specify column names that you are trying to set. string sqlQuery = #" UPDATE cottonpurchase SET slipNo = #slipNo, basicprice= #basicprice, weight = #weight, totalamountbasic = #totalamountbasic, premium = #premium, totalamountpremium = #totalamountpremium, totalamountpaid = #totalamountpaid, yeildestimates = #yeildestimates WHERE farmercode = #farmercode"; Also, you didn't provide #farmercode parameter: cmd.Parameters.AddWithValue("#farmercode", <someValue>);
You forgot to mention the column names in the set. string sqlQuery = #"UPDATE cottonpurchase SET slipNo=#slipNo, basicprice=#basicprice, ... WHERE farmercode = #farmercode";