Error when trying to insert input from user into SQL table - postgresql

I'm having a problem, whenever I try to run the code below and select the statement 2 to insert a tool and put a random tool name I get the error message : ProgrammingError('column "inserttool' does not exist\nLine 1: insert tools(tool_name, rental_days) values(#insertTool, '2') .
Here is the code :
if Menu == "2":
cursor = connection.cursor()
InsertTool = raw_input("Please insert the tool that you want to add.\n")
insert_tool = """insert into tools(tool_name, rental_days) values(#InsertTool, '2')"""
try:
cursor.execute( insert_tool);
connection.commit();
print("Tool is succesfully inserted!")
except Exception as e:
connection.rollback();
print("Exception Occured : ",e)
connection.close();

try this.
if Menu == "2":
cursor = connection.cursor()
InsertTool = raw_input("Please insert the tool that you want to add.\n")
insert_tool = """insert into tools(tool_name, rental_days) values(%s, %s)"""
val = (InsertTool, "2")
try:
cursor.execute(insert_tool, val);
connection.commit();
print("Tool is succesfully inserted!")
except Exception as e:
connection.rollback();
print("Exception Occured : ",e)
connection.close();

Related

Exception in thread "main" java.sql.SQLSyntaxErrorException: ORA-00936: missing expression

While executing insert and update command in oracle 11g I'm getting below error.
val stmt = con.createStatement()
//Insert
val query1 = "insert into audit values('D','abc','T','01-NOV-18','Inprogress')"
stmt.executeUpdate(query1)
//Update
val query2 = "Update audit Set status='test' where where product= = 'D'"
stmt.executeUpdate(query2)
I'm getting below error
//Error while updating record
Exception in thread "main" java.sql.SQLSyntaxErrorException: ORA-00936: missing expression
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531)
at oracle.jdbc.driver.T4CStatement.doOall8(T4CStatement.java:195)
at oracle.jdbc.driver.T4CStatement.executeForRows(T4CStatement.java:1036)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1336)
at oracle.jdbc.driver.OracleStatement.executeUpdateInternal(OracleStatement.java:1845)
at oracle.jdbc.driver.OracleStatement.executeUpdate(OracleStatement.java:1810)
at oracle.jdbc.driver.OracleStatementWrapper.executeUpdate(OracleStatementWrapper.java:294)
at com.oracle.OracleConnection$.main(OracleConnection.scala:21)
at com.oracle.OracleConnection.main(OracleConnection.scala)
Process finished with exit code 1
Any help will be appreciated. Thanks in advance
You have two where and two = in your update query.
val query2 = "Update audit Set status='test' where product='D'"

ORA-06550: PLS-00103: Encountered the symbol "" with mybatis TypeHandler

I am using Typehandler to map a List<Dep> to oracle array of ... here is the setPArameter method in the handler :
public void setParameter(PreparedStatement ps, int i, List<Dep> parameter, JdbcType jdbcType)
throws SQLException {
Connection connection = ps.getConnection();
// StructDescriptor structDescriptor = StructDescriptor.createDescriptor("MEMS_ARR", connection);
Struct[] structs = null;
if(parameter != null && parameter.size() >0) {
structs = new Struct[parameter.size()];
for (int index = 0; index < parameter.size(); index++)
{
Dep dep = parameter.get(index);
Object[] params = new Object[7];
params[0] = dep.getOrder();
params[1] = dep.getIdTp;
params[2] = dep.getId();
params[3] = " ";
params[4] = " ";
params[5] = " ";
params[6] = " ";
// STRUCT struct = new STRUCT(structDescriptor, ps.getConnection(), params);
structs[index] = connection.createStruct("MEMS", params);
}
// ArrayDescriptor desc = ArrayDescriptor.createDescriptor("MEMS_ARR", ps.getConnection());
// ARRAY oracleArray = new ARRAY(desc, ps.getConnection(), structs);
}else {
parameter = new ArrayList<DependentDTO>();
structs= new Struct[0];
}
this.parameter = parameter;
Array oracleArray = ((OracleConnection) connection).createOracleArray("MEMS_ARR", structs);
ps.setArray(i, oracleArray);
}
and here is the MEMS type :
create or replace TYPE MEMS AS OBJECT
( MEM1 NUMBER(2,0),
MEM2 VARCHAR2(1),
MEM3 VARCHAR2(15),
MEM4 VARCHAR2(60),
MEM5 VARCHAR2(1),
MEM6 VARCHAR2(40),
MEM7 VARCHAR2(10)
);
and here is the portion of the xml mapping file that uses the Typehandler :
#{nat,javaType=String,jdbcType=VARCHAR,mode=IN}, --nat
**#{deps,javaType=List,jdbcType=ARRAY,mode=IN,jdbcTypeName=MEMS_ARR,typeHandler=com.my.package.MyHandler}, --mems**
#{res,javaType=String,jdbcType=VARCHAR,mode=OUT} --res
the error log is as follows :
Error querying database. Cause: java.sql.SQLException: ORA-06550: line 31, column 5: PLS-00103: Encountered the symbol "" when expecting one of the following: . ( ) , * # % & = - + < / > at in is mod remainder not rem => <an exponent (**)> <> or != or ~= >= <= <> and or like like2 like4 likec between || indicator multiset member submultiset The symbol "(" was substituted for "" to continue. ORA-06550: line 44, column 4: PLS-00103: Encountered the symbol ";" when expecting one of the following: . ( ) , * % & = - + < / > at in is mod remainder not rem => <an exponent (**)> <> or != or ~= >= <= <> and or like like2 like4 likec between || multiset ### The error may exist in file [E:\path\to\mapper\ADao.xml] ### The error may involve my.package.ADao.mthodToCall -Inline ### The error occurred while setting parameters ### SQL: {call MY_PROC( ... , --nat?, **--mems? --res**)}
As you can see in the logs, the mems is replaced by empty string or is merged with the next arg res ... the comma is not there
Also kindly note that I already debugged inside the mybatis code and realized that the mapping setParameter method is called and the input List is mapped correctly to the oracle array ... the issue happens at the time of real calling
The issue actually was that I simply missed one comma between two previous parameters ... but the error pointed to the wrong parameter to look at

Not able to get all records in mongoDB using pymongo

I am having a program which uses pymongo to get the records in the mongoDB.
But, when I find records with a query I am getting blank cursor with no records.
Below is a code :
MongoDBConnection.py
import bottle
import pymongo
from pymongo import MongoClient
class MongoDBConnection():
def __init__(self):
pass
def getConnection(self,host):
try:
retConnection = MongoClient(host)
except Exception as e:
print 'Exception occurred while creating connection with mongoDB, value: \n '
print e
return retConnection
def showAllRecords(self,host,db,collection):
#pdb.set_trace()
hconn = self.getConnection(host)
hdb = self.getDBDetails(hconn,db)
hcoll = self.getCollectionDetails(hdb,collection)
#get all the details about the collection
query = {"name" : "SP"}
try:
cursor = hcoll.find(query)
except Exception as e:
print "Unexpected error:", type(e), e
return cursor
def getDBDetails(self,connection,db):
# create a database connection
try :
retDb = connection.db
except Exception as e:
print 'Exception occurred while connecting to database %s, value: \n ' % db
print e
return retDb
def getCollectionDetails(self,db,collection):
#create a handle for collection
try :
retCollection = db.collection
except Exception as e:
print 'Exception occurred while getting details for collection: %s, value: \n ' % collection
print e
return retCollection
A program which accesses this class:
runmongo.py
from MongoDBConnection import MongoDBConnection
a = MongoDBConnection()
test = a.showAllRecords("mongodb://localhost","test","documents")
print test
for i in test:
print i
The Output I am getting is a cursor object with no records in it.
[root#localhost tmp]# python runmongo.py
<pymongo.cursor.Cursor object at 0x288cd90>
[root#localhost tmp]#
Manually tried the same and I am getting proper output
> use test
switched to db test
> db.documents.find({'name':'SP'})
{ "_id" : "doc2", "name" : "SP" }
>
Can someone let me know, why am I not able to get the desired records from DB.
The problem is in accessing database and collection line itself.
When you try to access database and collection using attribute style like
retDb = connection.db
it assumes that 'db' is name of database instead of 'test' in your example.
Using dictionary style access will solve your problem something like this
retDb = connection[db]
Code goes like this :
import pymongo
from pymongo import MongoClient
class MongoDBConnection():
def __init__(self):
pass
def getConnection(self,host):
try:
retConnection = MongoClient(host)
except Exception as e:
print 'Exception occurred while creating connection with mongoDB, value: \n '
print e
return retConnection
def showAllRecords(self,host,db,collection):
#pdb.set_trace()
hconn = self.getConnection(host)
hdb = self.getDBDetails(hconn,'test')
hcoll = self.getCollectionDetails(hdb,'documents')
#get all the details about the collection
query = {"name" : "SP"}
try:
cursor = hcoll.find(query)
except Exception as e:
print "Unexpected error:", type(e), e
return cursor
def getDBDetails(self,connection,db):
# create a database connection
try :
retDb = connection[db] # NOTE : dictionary style access
except Exception as e:
print 'Exception occurred while connecting to database %s, value: \n ' % db
print e
return retDb
def getCollectionDetails(self,db,collection):
#create a handle for collection
try :
retCollection = db[collection] # NOTE : dictionary style access
except Exception as e:
print 'Exception occurred while getting details for collection: %s, value: \n ' % collection
print e
return retCollection

Error running update query in Postgres NPGSQL - ERROR: 42601: syntax error at or near "="

I am running the following update command:
NpgsqlCommand command = new NpgsqlCommand("UPDATE \"FPConfig_simulationresult\" SET key_name = :keyName WHERE id = :resultID", conn);
command.Parameters.Add(new NpgsqlParameter("keyName", DbType.String));
command.Parameters.Add(new NpgsqlParameter("resultID", DbType.Int32));
command.Parameters[0].Value = keyName;
command.Parameters[1].Value = resultID;
int rowsAffected = command.ExecuteNonQuery();
and get the error:
ERROR: 42601: syntax error at or near "="
I have checked everything in the update SQL statement, the table name and field names are correct.

DB2 v.10.1 RDF data deletion

Have anybody tried to remove data(triples) from the DB2 RDF simple store(Windows)? (INSERT works fine)
SPARQL DELETE statament:
DELETE { ?document ?property ?value} WHERE{ ?document <http://example.com#begin>
?begin .
FILTER(?begin > 200) ?document ?property ?value }
I've got the following exception:
com.ibm.rdf.store.exception.RdfStoreException: DB255006E ERRORCODE=-4499, SQLSTATE=08001. SQLSTATE: 08001.
at
com.ibm.rdf.store.internal.jena.impl.update.SingleTripleOperations.removeQuad(Unknown Source)
at com.ibm.rdf.store.internal.jena.impl.update.AbstractTripleOperation.removeQuad(Unknown Source)
.....
db2diag.log:
RETCODE : ZRC=0x87120007=-2028863481=SQLR_SEVERE_PGM_ERROR
"Severe programming error"
DIA8516C A severe internal processing error has occurred.
My Java code:
String queryString = "delete ...";
Dataset ds = RdfStoreFactory.connectDataset(storeP, conn);
GraphStore graphStore = GraphStoreFactory.create(ds) ;
UpdateAction.parseExecute(queryString, graphStore); // exception
//UpdateAction.parseExecute("DROP ALL", graphStore); // works fine
Thanks!
The problem solved by adding
prop.setProperty("enableExtendedIndicators", "2");
to the DB2 connection.