SQL Command not properly ended Exception - sql

Pretty basic sql Command. Just want to get the count from different tables I am looping through. However, if I alter the sqlCommand and add a ';' at the end I get exception, SQL command not properly ended.
sqlCommand = String.Format("SELECT COUNT(1) FROM SO.{0} where DR_ADDRESS_ID = {1};", table, drAddr);
I am curious why this semi-colon makes this exception thrown since commands are suppose to end with a ';'
sqlCommand = String.Format("SELECT COUNT(1) FROM SO.{0} where DR_ADDRESS_ID = {1}", table, drAddr);
try
{
using(OracleCommand ocCommand = new OracleCommand(sqlCommand,CommandType.Text))
{
ocCommand.Connection = dbConnection;
recordCounter = Convert.ToInt64(ocCommand.ExecuteScalar());
}
}
catch (Exception er)
{
MessageBox.Show(String.Format("Error in RecordCount for table {0}: Reference {1} for log. err = {2}",table, logFilePath,er.ToString()));
recordCounter = -1;
using (StreamWriter writer = new StreamWriter(logFilePath, true))
{
writer.WriteLine(String.Format("Table: {0}. Command {1}", table,sqlCommand.ToString()));
}
}

Semi colons are usually just used as a command terminator for interactive tools like sqlplus.

Related

Groovy SQL Execute Parameters not getting replaced

This problem is frustrating me so much, that I've finally created a Stackoverflow Account - this is my first question here, go easy on me.
I've got an SQL Script like this:
select * from d_table
where id = :line;
I'd like to execute that query from a groovy script. So far I've written this:
static void main(String[] args) {
String dbURL = 'some.db:Port:serviceName'
String dbUser = 'dbUser'
String dbPw = 'aReallyStrongPassword'
// connect to SQL Instance and DB
def sql = Sql.newInstance(dbURL, dbUser, dbPw, 'oracle.jdbc.OracleDriver')
// read Inputfile from local dir
new File("inputfile.csv").eachLine { inputLine ->
// loop over Inputfile
try {
// read SQL Script from local dir
String sqlString = new File("script.sql").getText("UTF-8")
// execute SQL Script, replace :line with input-ID
resp = sql.execute sqlString, line: inputLine
} catch(Exception e) {
println(e)
}
}
// close SQL Session
sql.close()
}
But I'll always get an error like this:
WARNING: Failed to execute: select * from d_table
where id = :line; because: ORA-00933: SQL command not properly ended
I've got the feeling the query is not built properly, but I don't know whats the problem?
Using groovy 3.0.4.

How to solve "ORA-00933 & ORA-00936" in SQL/Oracle?

Im creating a student profile for our project in school and it's my first time to make this.
This is my query for my jTable (mouseclicked) I've created in netbeans
int row = jTable1.getSelectedRow();
String tc = jTable1.getModel().getValueAt(row, 0).toString();
try {
String query ="select * from CAREPOINT_STUDENT where NAME="+tc+" ";
pst= (OraclePreparedStatement) ungabelio1.prepareStatement(query);
rs = (OracleResultSet) pst.executeQuery();
if(rs.next()){
String NAME_ID = rs.getString("NAME");
String AGE_ID = rs.getString("AGE");
String ADDRESS_ID = rs.getString("ADDRESS");
String NUM_ID = rs.getString("NUM");
String COURSE_ID = rs.getString("COURSE");
String SPECIAL_ID = rs.getString("SPECIAL");
String SCHOOL_ID = rs.getString("SCHOOL");
String DOWNPAY_ID = rs.getString("DOWNPAY");
String DISCOUNT_ID = rs.getString("DISCOUNT");
String BALANCE_ID = rs.getString("BALANCE");
String REVSCHED_ID = rs.getString("REVSCHED");
String EMAIL_ID = rs.getString("EMAIL");
NAME.setText(NAME_ID);
AGE.setText(AGE_ID);
ADDRESS.setText(ADDRESS_ID);
NUM.setText(NUM_ID);
COURSE.setText(COURSE_ID);
SPECIAL.setText(SPECIAL_ID);
SCHOOL.setText(SCHOOL_ID);
DOWNPAY.setText(DOWNPAY_ID);
DISCOUNT.setText(DISCOUNT_ID);
BALANCE.setText(BALANCE_ID);
REVSCHED.setText(REVSCHED_ID);
EMAIL.setText(EMAIL_ID);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
When I run the program and tried to click the data (A Student Profile like name,age,school, etc..) that I created and printed inside the jtable (mouseclicked), I get this problem "ORA-00933: SQL command not properly ended"
Aside from that, I also have another problem which I created 2 jbutton called "DELETE" which means it will delete the data(Student profile) that I filled up and "UPDATE" which means to reedit the data(Student profile) that I filled up.
this is the query of my "DELETE" jbutton in netbeans
try {
String query;
query = "DELETE FROM CAREPOINT_STUDENT where NAME="+NAME.getText()+" ";
pst= (OraclePreparedStatement) ungabelio1.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Successfully deleted!");
fetch();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
and this is the query of my "UPDATE" jbutton in netbeans
try {
String query;
query = "update CAREPOINT_STUDENT set AGE=?,ADDRESS=?,NUM=?,COURSE=?,SPECIAL=?,SCHOOL=?,DOWNPAY=?,DISCOUNT=?,BALANCE=?,REVSCHED=?,EMAIL=? where NAME="+NAME.getText()+"";
pst= (OraclePreparedStatement) ungabelio1.prepareStatement(query);
pst.setString(1,AGE.getText());
pst.setString(2,ADDRESS.getText());
pst.setString(3, NUM.getText());
pst.setString(4, COURSE.getText());
pst.setString(5, SPECIAL.getText());
pst.setString(6, SCHOOL.getText());
pst.setString(7, DOWNPAY.getText());
pst.setString(8, DISCOUNT.getText());
pst.setString(9, BALANCE.getText());
pst.setString(10, REVSCHED.getText());
pst.setString(11, EMAIL.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Successfully updated!");
fetch();
} catch (Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
when I run the program and click those 2 buttons, I get the same problem "ORA-00936: missing expression"
I really appreciate and I hope that somebody would help me to fix this problem. So that I can gain some little knowledge about sql/oracle.
Sorry for my bad english.
Avoid concatenating parameters as strings; use prepared statements.
Otherwise you'll run in all kind of troubles, like escaping issues for special characters, SQL Injection, etc.
For example, a safer way of running your SQL statement could be:
String query = "select * from CAREPOINT_STUDENT where NAME = ?";
pst = (OraclePreparedStatement) ungabelio1.prepareStatement(query);
pst.setString(1, tc);
rs = (OracleResultSet) pst.executeQuery();
Note: Assembling a SQL statement as a string is still useful for cases when you want to do some dynamic SQL. Even then, use ? for parameters and apply them as shown above.
You may need some extra single quotes so you query will read:
select * from CAREPOINT_STUDENT where NAME='Entered name';
Adjust your code:
String query ="select * from CAREPOINT_STUDENT where NAME='"+tc+"' ";

result of an oracle command

I'm doing a graphical user interface using Windows Form Application, using an oracle database.
I'm trying to bind to a label in my UI the result of an oracle command.
This is my code :
OracleCommand cmd = conn.CreateCommand();
string city = comboBox1.SelectedItem.ToString();
cmd.CommandText ="select c.companynum,c.namec from flight f, company c where f.companynum=c.companynum AND f.name1=&param1 order by f.name1;";
cmd.Parameters.AddWithValue("param1", city);
cmd.Parameters.Add("result", OracleType.VarChar, 200);
cmd.Parameters["result"].Direction = ParameterDirection.ReturnValue;
try
{
cmd.ExecuteNonQuery();
if (cmd.Parameters["result"].Value.ToString() == "")
label2.Text = "No destinations.";
else
label2.Text = cmd.Parameters["result"].Value.ToString();
da.SelectCommand.Parameters.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Exception Caught");
}
But when it runs there's an exception : ORA-01036 : illegal variable name/number.
I don't know how to fix my code ?
NB : For my homework I have to use here the '&' method.
maybe it is done a little misunderstanding.. :)
I think that the original trace of your homework intended to that it should create a stored procedure where put into the select sql statement that you have passed to the command.
Stored proc should have 2 parameters: "city" and "result" ;)
Good homework!

how to use 'try catch finally' block to display message when mysql query is executed successfully

I have been using a 'try catch finally' in the code for a C# Windows form to query a MySQL database. The code works well: when the catch block flags errors, a message box will display error messages.
In the finally block, I coded a message box that will show when the database is successfully updated.
If there is no error message it all works well. The success message shows.
But if there is an error, the error message in the catch block is displayed, followed by the success message in the finally block.
Does anyone know a solution to get a program to display either an error message or a success message when mysql is updated?
Thanks,
Peter
Here is a code sample:
private void btnUpdateEmployeeTable_Click(object sender, EventArgs e) //Update record in Employee table
{
String myConnection = #"server=localhost; database=shopdb; username=**; password=**; convert zero datetime=True";
MySqlConnection Connect = null;
try
{
Connect = new MySqlConnection(myConnection);
Connect.Open(); //Open the connection
//This is the mysql command that we will query into the db.
//It uses Prepared statements and the Placeholders for faster, more secure processing.
String updateQuery = "UPDATE employee SET emp_lName = #empLastName, emp_fName = #empFirstName WHERE emp_number = #empNum";
MySqlCommand cmdInsertEmployeeToDataBase = new MySqlCommand(updateQuery, Connect);
cmdInsertEmployeeToDataBase.Prepare();
//Bind the value to the placeholder
cmdInsertEmployeeToDataBase.Parameters.AddWithValue("#empNum", this.txtEmployeeNo.Text);
cmdInsertEmployeeToDataBase.Parameters.AddWithValue("#empLastName", this.txtEmployeeLastName.Text);
cmdInsertEmployeeToDataBase.Parameters.AddWithValue("#empFirstName", this.txtEmployeeFirstName.Text);
cmdInsertEmployeeToDataBase.ExecuteNonQuery(); //Execute the mysql command
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\nDatabase could not be updated \n" + "Please try again");
}
finally
{
if (Connect != null)
{
Connect.Close(); //Close the connection
}
MessageBox.Show("Database update successful");
}
}
You can easily move the success code up higher. If an exception is thrown before the MessageBox.Show("Database update successful"); line, then it will never get executed.
try
{
Connect = new MySqlConnection(myConnection);
Connect.Open(); //Open the connection
//This is the mysql command that we will query into the db.
//It uses Prepared statements and the Placeholders for faster, more secure processing.
String updateQuery = "UPDATE employee SET emp_lName = #empLastName, emp_fName = #empFirstName WHERE emp_number = #empNum";
MySqlCommand cmdInsertEmployeeToDataBase = new MySqlCommand(updateQuery, Connect);
cmdInsertEmployeeToDataBase.Prepare();
//Bind the value to the placeholder
cmdInsertEmployeeToDataBase.Parameters.AddWithValue("#empNum", this.txtEmployeeNo.Text);
cmdInsertEmployeeToDataBase.Parameters.AddWithValue("#empLastName", this.txtEmployeeLastName.Text);
cmdInsertEmployeeToDataBase.Parameters.AddWithValue("#empFirstName", this.txtEmployeeFirstName.Text);
cmdInsertEmployeeToDataBase.ExecuteNonQuery(); //Execute the mysql command
MessageBox.Show("Database update successful");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\nDatabase could not be updated \n" + "Please try again");
}
finally
{
if (Connect != null)
{
Connect.Close(); //Close the connection
}
}

SQL - OleDbCommand not changing Sql Parameter

Below is the code for my Select * Function - It WORKS well and does everything great until i change the SQL string from Select * From Company to
query = "Select * From #1";
and then do the following
query = "Select * From #1";
OleDbCommand Command = new OleDbCommand(query, sqlConnStr);
DataTable Table = new DataTable();
DataSet dataSet = new DataSet();
Table = null;
//Add Parameters
Command.Parameters.AddWithValue("#1", SQLTables.Company);
try
{
Command.ExecuteNonQuery();
adapter.SelectCommand = Command;
adapter.Fill(dataSet);
Table = dataSet.Tables[0];
}
catch (Exception e)
{
MessageBox.Show("A Error occured whilst trying to execute the command.\n" + e.Message);
}
return Table;
The DBMS keeps sending back "Query incomplete" - I assume The Command variable is sending the string query through without changing the Parameter from #1 to Company
Here is a piece of code (mine) where this does work. This is an insert statement rather that a select - Correct me if i am wrong but should it not also work with the SELECT aswell
private void MainActionsInsert(string Action, bool Checked)
{
OleDbCommand Command = new OleDbCommand("INSERT INTO MainActions Values (ID, Action, BoolValue)", DataBaseConnection);
//Add Parameters
Command.Parameters.AddWithValue("ID", GenerateID());
Command.Parameters.AddWithValue("Action", Action);
Command.Parameters.AddWithValue("BoolValue",Checked);
//Add Command
MainActionsAdapter.InsertCommand = Command;
//Execute Agains DataBase
Command.ExecuteNonQuery();
//Accept Changes
}
`
OLEdb doesn't recognize named parameters. You must use ? in the query text.
However, you also can't use dynamic table names with parameterized queries, so even using a ? will not help.
You need to use full dynamic SQL, though that can open you up to SQL Injection. Make sure you read the full article I linked.
OleDbCommand Does accept Parameterized SQL just not in the From Clause - It Has to be either in a WHERE clause or something like that. Like you said it Worked with the insert function because it expects "parameters" there. For example this will work
query = "Select * From Company Where #param = 1";
OleDbCommand Command = new OleDbCommand(query, sqlConnStr);
DataTable Table = new DataTable();
DataSet dataSet = new DataSet();
Table = null;
//Add Parameters
Command.Parameters.AddWithValue("param", "ID");
try
{
Command.ExecuteNonQuery();
adapter.SelectCommand = Command;
adapter.Fill(dataSet);
Table = dataSet.Tables[0];
}
catch (Exception e)
{
MessageBox.Show("A Error occured whilst trying to execute the command.\n" + e.Message);
}
return Table;
Funny though that it doesn't work for the Select part though