JdbcTemplate 'IN' search not working properly - mysql

I am trying to perform IN search using JbdcTemplate in Spring. Here goes my code
#Override
public Map<String, List> dataRetriveForAsset(String type) {
List<Integer> interfaceIdList = new ArrayList<Integer>();
List<Integer> fileList = new ArrayList<Integer>();
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sql2 = "select interface_id from tbl_interface_asset where asset_id in ( :ids )";
//fileList is populated with a different query
Set<Integer> ids = new HashSet(Arrays.asList(new Integer[fileList.size()] ));
for(int i=0; i<fileList.size();i++)
{
ids.add(fileList.get(i));
}
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("ids", ids);
interfaceIdList = jdbcTemplate.query(sql2,new ListMapper1(),parameters );
and the sql2 query part executes it throws the following error.
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/iccdashboard] threw exception [Request processing failed; nested exception is org.springframework.dao.TransientDataAccessResourceException: PreparedStatementCallback; SQL [select interface_id from tbl_interface_asset where asset_id in ( :ids )]; Invalid argument value: java.io.NotSerializableException; nested exception is java.sql.SQLException: Invalid argument value: java.io.NotSerializableException] with root cause
java.io.NotSerializableException: org.springframework.jdbc.core.namedparam.MapSqlParameterSource
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at com.mysql.jdbc.PreparedStatement.setSerializableObject(PreparedStatement.java:4401)
at com.mysql.jdbc.PreparedStatement.setObject(PreparedStatement.java:4083)
at org.springframework.jdbc.core.StatementCreatorUtils.setValue(StatementCreatorUtils.java:351)
at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValueInternal(StatementCreatorUtils.java:216)
at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValue(StatementCreatorUtils.java:144)
But if I use NamedParameterJdbcTemplate, I am getting a BadSQLGrammarError because the 'ids' value my sql query goes emplty like below.
select interface_id from tbl_interface_asset where asset_id in ( )

java.io.NotSerializableException: org.springframework.jdbc.core.namedparam.MapSqlParameterSource
I was able to fix this problem by replacing my usage of
org.springframework.jdbc.core.JdbcTemplate
with the:
org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
I was using the MapSqlParameterSource class but using the standard template which may have been the problem.
But if I use NamedParameterJdbcTemplate, I am getting a BadSQLGrammarError because the 'ids' value my sql query goes empty like below.
Can you make the SQL generation conditional on whether or not there are entries in your IN collection?
if (!ids.isEmpty()) {
parameters.addValue("ids", ids);
}

Related

How to transfer POJO object to Ignite table?

public class JSONmapper {
public static class Person{
#QuerySqlField(index = true)
int id;
#QuerySqlField(index = true)
String name;
}
public static void main(String[] args) {
Map<String,Object> serdeProps = new HashMap<>();
serdeProps.put("json.value.type",Person.class);
final Deserializer<Person> PersonDeserializer = new KafkaJsonDeserializer<>();
PersonDeserializer.configure(serdeProps, false);
Properties prop = new Properties();
prop.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"localhost:9092");
prop.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
prop.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, PersonDeserializer.getClass().getName());
prop.put(ConsumerConfig.GROUP_ID_CONFIG,"JSONmapper1");
prop.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG,"earliest");
KafkaConsumer<String,Person> consumer = new KafkaConsumer<>(prop);
consumer.subscribe(Collections.singleton("JsonMapper1"));
IgniteConfiguration config = new IgniteConfiguration();
Ignite ignite = Ignition.start(config);
CacheConfiguration<String, Person> cc = new CacheConfiguration<>("PersonCache");
cc.setCacheMode(CacheMode.PARTITIONED);
cc.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL);
cc.setIndexedTypes(String.class,Person.class);
IgniteCache<java.lang.String,Person> cache = ignite.getOrCreateCache(cc);
Map<String, Person> batch = new HashMap<>();
while(true)
{
ConsumerRecords<String, Person> records = consumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, Person> record:records){
batch.put(record.key(),record.value());
}
cache.putAll(batch);
batch.clear();
}
}
}
Hi all I am trying to send JSON data coming out of Kafka to Ignite cache and view it as a table. After running this code I could observe that data is transferred to cache, confirmed this with visorcmd. I triggered sqlline.bat from setup with PersonCache schema as it was showing !tables. But unable to query "Select * from Person". It is giving me error that "Failed to set schema for DB connection for thread".
Please enlight and help regarding this.
SEVERE: Failed to execute SQL query [reqId=2, req=JdbcQueryExecuteRequest [schemaName=PERSONCACHE, pageSize=1024, maxRows=0, sqlQry=select * from PersonCache.PERSON, args=Object[] [], stmtType=ANY_STATEMENT_TYPE, autoCommit=true, partResReq=false, super=JdbcRequest [type=2, reqId=2]]]
class org.apache.ignite.internal.processors.query.IgniteSQLException: Failed to set schema for DB connection for thread [schema=PERSONCACHE]
at org.apache.ignite.internal.processors.query.h2.H2ConnectionWrapper.connection(H2ConnectionWrapper.java:81)
at org.apache.ignite.internal.processors.query.h2.QueryParser.parseH2(QueryParser.java:319)
at org.apache.ignite.internal.processors.query.h2.QueryParser.parse0(QueryParser.java:210)
at org.apache.ignite.internal.processors.query.h2.QueryParser.parse(QueryParser.java:131)
at org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing.querySqlFields(IgniteH2Indexing.java:1103)
at org.apache.ignite.internal.processors.query.GridQueryProcessor$3.applyx(GridQueryProcessor.java:2406)
at org.apache.ignite.internal.processors.query.GridQueryProcessor$3.applyx(GridQueryProcessor.java:2402)
at org.apache.ignite.internal.util.lang.IgniteOutClosureX.apply(IgniteOutClosureX.java:36)
at org.apache.ignite.internal.processors.query.GridQueryProcessor.executeQuery(GridQueryProcessor.java:2919)
at org.apache.ignite.internal.processors.query.GridQueryProcessor.lambda$querySqlFields$1(GridQueryProcessor.java:2422)
at org.apache.ignite.internal.processors.query.GridQueryProcessor.executeQuerySafe(GridQueryProcessor.java:2460)
at org.apache.ignite.internal.processors.query.GridQueryProcessor.querySqlFields(GridQueryProcessor.java:2396)
at org.apache.ignite.internal.processors.query.GridQueryProcessor.querySqlFields(GridQueryProcessor.java:2354)
at org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequestHandler.executeQuery(JdbcRequestHandler.java:615)
at org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequestHandler.doHandle(JdbcRequestHandler.java:310)
at org.apache.ignite.internal.processors.odbc.jdbc.JdbcRequestHandler.handle(JdbcRequestHandler.java:247)
at org.apache.ignite.internal.processors.odbc.ClientListenerNioListener.onMessage(ClientListenerNioListener.java:195)
at org.apache.ignite.internal.processors.odbc.ClientListenerNioListener.onMessage(ClientListenerNioListener.java:49)
at org.apache.ignite.internal.util.nio.GridNioFilterChain$TailFilter.onMessageReceived(GridNioFilterChain.java:279)
at org.apache.ignite.internal.util.nio.GridNioFilterAdapter.proceedMessageReceived(GridNioFilterAdapter.java:109)
at org.apache.ignite.internal.util.nio.GridNioAsyncNotifyFilter$3.body(GridNioAsyncNotifyFilter.java:97)
at org.apache.ignite.internal.util.worker.GridWorker.run(GridWorker.java:120)
at org.apache.ignite.internal.util.worker.GridWorkerPool$1.run(GridWorkerPool.java:70)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.h2.jdbc.JdbcSQLException: Schema "PERSONCACHE" not found [90079-197]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:357)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.engine.Database.getSchema(Database.java:1808)
at org.h2.engine.Session.setCurrentSchemaName(Session.java:1317)
at org.h2.jdbc.JdbcConnection.setSchema(JdbcConnection.java:1989)
at org.apache.ignite.internal.processors.query.h2.H2ConnectionWrapper.connection(H2ConnectionWrapper.java:76)
... 25 more
At SQLline end :
Error: Failed to set schema for DB connection for thread [schema=PERSONCACHE] (state=50000,code=1)
java.sql.SQLException: Failed to set schema for DB connection for thread [schema=PERSONCACHE]
at org.apache.ignite.internal.jdbc.thin.JdbcThinConnection.sendRequest(JdbcThinConnection.java:901)
at org.apache.ignite.internal.jdbc.thin.JdbcThinStatement.execute0(JdbcThinStatement.java:231)
at org.apache.ignite.internal.jdbc.thin.JdbcThinStatement.execute(JdbcThinStatement.java:559)
at sqlline.Commands.execute(Commands.java:823)
at sqlline.Commands.sql(Commands.java:733)
at sqlline.SqlLine.dispatch(SqlLine.java:795)
at sqlline.SqlLine.begin(SqlLine.java:668)
at sqlline.SqlLine.start(SqlLine.java:373)
at sqlline.SqlLine.main(SqlLine.java:265)
First of all, in order to have an Apache Ignite SQL table based on some POJO, you must do one of the following:
1)If you are going to configure the cache via XML, you must create a custom QueryEntity based on the required POJO types:
https://ignite.apache.org/docs/latest/SQL/sql-api#query-entities
Or you can use special annotations in your POJO object:
https://ignite.apache.org/docs/latest/SQL/sql-api#querysqlfield-annotation
2)Using SQL syntax, you must set the correct key and value types using the following properties:
CREATE TABLE IF NOT EXISTS Person (
id int,
city_id int,
name varchar,
age int,
company varchar,
PRIMARY KEY (id, city_id)
) WITH "template=partitioned,backups=1,affinity_key=city_id, key_type=com.test.PersonKey, value_type=com.test.MyPerson"
https://ignite.apache.org/docs/latest/sql-reference/ddl

SnappyData JDBC driver raising SQLState=XCL14 error

SnappyData v.0-5 w/ ClientDriver JDBC driver.
I have a persistent row table in SnappyData called: sensor_data.
From the snappy> shell, this query returns thousands for rows.
snappy> select * from sensor_data where year_num = 2013 and
month_num = 1;
When run from a JDBC connection in SpringBoot, I get this error:
PreparedStatementCallback; uncategorized SQLException for SQL [select
* from sensor_data where year_num = ? and month_num = ?]; SQL state [XCL14]; error code [20000]; (SQLState=XCL14 Severity=20000) The
column position '1' is out of range. The number of columns for this
ResultSet is '0'.
Java Code is:
List<SensorData> list = jdbcTemplateBean.query("select * from sensor_data where year_num = ? and month_num = ?",
new Object[] {year, month}, new SensorDataRowMapper());
What do I need to do to fix this JDBC issue?
Trimmed Stacktrace on Spring boot:
org.springframework.jdbc.UncategorizedSQLException:
PreparedStatementCallback; uncategorized SQLException for SQL [select
* from sensor_data where year_num = ? and month_num = ?]; SQL state [XCL14]; error code [20000]; (SQLState=XCL14 Severity=20000) The
column position '1' is out of range. The number of columns for this
ResultSet is '0'.; nested exception is java.sql.SQLException:
(SQLState=XCL14 Severity=20000) The column position '1' is out of
range. The number of columns for this ResultSet is '0'. at
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:84)
at
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at
org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81)
at
org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:645)
at
org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:680)
at
org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:707)
at
org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:757)
at
org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.query(NamedParameterJdbcTemplate.java:192)
at
org.kritek.scalability.repository.SensorDataRepository.findByYearAndMonth(SensorDataRepository.java:58)
...
at
org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
at java.lang.Thread.run(Thread.java:745) Caused by:
java.sql.SQLException: (SQLState=XCL14 Severity=20000) The column
position '1' is out of range. The number of columns for this
ResultSet is '0'.
...
Caused by: ERROR XCL14: The column position '1' is out of
range. The number of columns for this ResultSet is '0'. at
com.pivotal.gemfirexd.internal.client.am.ColumnMetaData.checkForValidColumnIndex(ColumnMetaData.java:856)
at
com.pivotal.gemfirexd.internal.client.am.ColumnMetaData.getColumnType(ColumnMetaData.java:638)
... 72 more
From the stack it looks like NamedParameterJdbcTemplate is being used but '?' placeholders are being used. For NamedParameterJdbcTemplate you need to use named parameters like here.
I will recommend using the standard '?' placeholder mechanism with JdbcTemplate like:
private JdbcTemplate jdbcTemplateBean;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplateBean = new JdbcTemplate(dataSource);
}
List<SensorData> list = jdbcTemplateBean.query(
"select * from sensor_data where year_num = ? and month_num = ?",
new Object[] { year, month }, new SensorDataRowMapper());
The issue has been resolved. Here is what happened.... SnappyData routed the query to Spark because it determined it could not handle it. Spark knows nothing about JDBC PreparedStatements or bind variables and raised the error. To fix, I had to set the SnappyData JDBC property "route-query = false" in my DataSource configuration. This ensured it was not routed to Spark.

Getting multiple variables in URL for JSON

I am trying to retrieve multiple variables in the URL, so I could send a query to database to select a specific object, but it seems that it picks up the first object and others are null.
#RequestMapping(value = "getGroup/{Name}/{StartDate}/{EndDate}/{Status_GroupID}", method = RequestMethod.GET)
public #ResponseBody List<GroupsDetails> getGroupList(
#PathVariable String Name, String StartDate, String EndDate,
Integer Status_GroupID) {
return musicStoreService.getGroupList(Name, StartDate, EndDate, Status_GroupID);
}
The error I am recieving:
Hibernate: select groupsdeta0_.Status_GroupID as Status1_1_, groupsdeta0_.GroupsID as GroupsID1_, groupsdeta0_.EndDate as EndDate1_, groupsdeta0_.Name as Name1_, groupsdeta0_.StartDate as StartDate1_ from Groups groupsdeta0_ where groupsdeta0_.Name=Gamma and (groupsdeta0_.StartDate is null) and (groupsdeta0_.EndDate is null) and (groupsdeta0_.Status_GroupID is null)
Sep 12, 2014 2:41:40 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [SpringDispatcher] in context with path [/ATS] threw exception [Request processing failed; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'Gamma' in 'where clause'
The table is named Groups and it has rows : Name, StartDate, EndDate, Status_GroupID and GroupsID
Update:
I am trying to retrieve a primarykey by giving the rows details, but it is not working.
#Override
public List<GroupsDetails> getGroupList(String Name, String StartDate, String EndDate, Integer Status_GroupID) {
SessionFactory sessionFactory=HibernateSessionManager.getSessionFactory();
Session session=sessionFactory.getCurrentSession();
Transaction transaction=session.beginTransaction();
try{
transaction.begin();
#SuppressWarnings("unchecked")
List<GroupsDetails> groupList=session.createSQLQuery("FROM Groups WHERE Name=" + Name + " AND StartDate=" + StartDate + " AND EndDate=" + EndDate + " AND Status_GroupID=" + Status_GroupID).list();
return groupList;
}finally{
session.close();
}
}
But it throws the exception that is badly syntax, even tho I can not see the error in syntax.
The error is :
Hibernate: FROM Groups WHERE Name=Gamma AND StartDate=01-06-2014 AND EndDate=01-09-2014 AND Status_GroupID=1
Sep 12, 2014 3:35:51 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [SpringDispatcher] in context with path [/ATS] threw exception [Request processing failed; nested exception is org.hibernate.exception.SQLGrammarException: could not execute query] with root cause
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM Groups WHERE Name=Gamma AND StartDate=01-06-2014 AND EndDate=01-09-2014 AND' at line 1
As per the error details :
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use near
'FROM Groups WHERE Name=Gamma AND StartDate=01-06-2014 AND EndDate=01-09-2014 AND' at line 1
it clearly shows that you are missing quotes, eg: Name=Gamma should be Name='Gamma'
Alternatively you can create the Query by using Parameters for example:
query = sess.createSQLQuery("SELECT * FROM Groups
WHERE NAME=:name AND StartDate=:startDate AND EndDate=:endDate
AND Status_GroupID=:status_GroupID").addEntity(Groups.class);
query.setString("name", name);
query.setDate("startDate", StartDate);
query.setString("endDate", EndDate);
query.setString("status_GroupID", Status_GroupID);
List<GroupsDetails> groupList = query.list();
You need to have #PathVariable infront of all parameters. Like
public #ResponseBody List<GroupsDetails> getGroupList(
#PathVariable String Name, #PathVariable String StartDate, #PathVariable String EndDate,
#PathVariable Integer Status_GroupID)

Column 'orderId' not found. com.liferay.portal.kernel.dao.orm.ORMException: org.hibernate.exception.SQLGrammarException: could not execute query

Following is a custom SQL:
SELECT COUNT(*)
FROM EEC_Order
WHERE DATE(EEC_Order.createDate) = CURDATE()
AND EEC_Order.status = ?
AND EEC_Order.companyId = ?
above sql query working in mysql but not working custom sql login liferay
public class OrderFinderImpl extends BasePersistenceImpl<Order> implements OrderFinder {
public int getTodayOrderCount(String status,long companyId) {
Session session = null;
SQLQuery query = null;
try {
String sql = CustomSQLUtil.get(GET_TODAY_ORDER_COUNT);
session = openSession();
query = session.createSQLQuery(sql);
query.addEntity("Order", OrderImpl.class);
QueryPos qPos = QueryPos.getInstance(query);
qPos.add(status);
qPos.add(companyId);
Iterator<Long> itr = query.list().iterator();
if (itr.hasNext()) {
Long count = itr.next();
if (count != null) {
return count.intValue();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
closeSession(session);
}
return 0;
}
public static String GET_TODAY_ORDER_COUNT = "getTodayOrderCount";
}
Console Exception:
04:56:56,520 ERROR [http-bio-8080-exec-6][JDBCExceptionReporter:76] Column 'orderId' not found.
com.liferay.portal.kernel.dao.orm.ORMException: org.hibernate.exception.SQLGrammarException: could not execute query
at com.liferay.portal.dao.orm.hibernate.ExceptionTranslator.translate(ExceptionTranslator.java:30)
at com.liferay.portal.dao.orm.hibernate.SQLQueryImpl.list(SQLQueryImpl.java:111)
at com.liferay.portal.dao.orm.hibernate.SQLQueryImpl.list(SQLQueryImpl.java:88)
at com.esquare.ecommerce.service.persistence.OrderFinderImpl.getTodayOrderCount(OrderFinderImpl.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:320)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at com.liferay.portal.dao.shard.advice.ShardPersistenceAdvice.invoke(ShardPersistenceAdvice.java:52)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy426.getTodayOrderCount(Unknown Source)
This is happening because of the following line in your code:
query.addEntity("Order", OrderImpl.class);
this is used when the sql query returns all columns to construct the Order entity, for example to use the above statement the query should be:
SELECT * FROM EEC_ORDER
And since your query is only returning an aggregate function COUNT which would return a scalar value, single value and so you can't use the addEntity method with your count query.
The addEntity method will get the result-set and try to set it in the Order entity by setting all the columns one by one, using something like order.setOrderId(resultSet.getLong("orderId")) and since your sql query is not returning any orderId or other columns this fails and you get the exception as above.
So now what to do? Read on for the solution:
To return a scalar of type long as you are doing in your query you can use the following instead of the addEntity method:
query.addScalar("countOfOrder", Type.LONG);
where countOfOrder is nothing but the alias of count in the sql query such as
SELECT count(*) as "countOfOrder" FROM EEC_ORDER

SQL: 4 classes must reference one central class which provides database access

I want to make several entries into a MySQL database. Because Some of the tables reference others via foreign key I have to get back the inserted ID to inject them in my next statements.
I have 4 classes:
LodgerFormTest
RentForm
RentObject
House
and the class which inserts the MySQL statements into the db: sql_statements
When I want to send a SQL statement I am getting a nullPointer Exception!
The Action listener of the House-class (this is the first sql-statement I have to send) looks like this:
saveButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.out.println("saveButton");
// sql_statements statements = new sql_statements();
sql_statements.performHouse(strasse.getText(), plz.getText(), ort.getText());
mainmenu.create();
rentnerFrame.dispose();
}
});
all methods and variables I am using in sql_statements are static! Therefore I am not instantiating an object.
here is the method "performHouse" in sql_statements
public static void performHouse(String strasse, String plz, String ort) {
String sql = "insert into haus(strasse, plz, ort) values (?,?,?)";
System.out.println(sql);
try{
ps = connect.prepareStatement(sql, ps.RETURN_GENERATED_KEYS);
ps.setString(1, strasse);
ps.setString(2, plz);
ps.setString(3, ort);
ps.execute();
rs = ps.getGeneratedKeys();
if(rs != null && rs.next()) {
// Retrieve the auto generated key(s).
key_idhaus = rs.getLong(1);
System.out.println("idhaus: " + key_idhaus);
}
}catch(Exception ex){
System.out.println(ex);
}
} // close performHouse-methode
I cant debug because I get a "Source not found." error in the debug view.
Can anybody help please?
okay I just wanted to finish the task so I implemented a solution which surely is all but not OO:
I implemented redundant code into all of the 4 classes and every class implements their own sql statements. quick and dirty ;)