Search Results

Search found 114 results on 5 pages for 'preparedstatement'.

Page 4/5 | < Previous Page | 1 2 3 4 5  | Next Page >

  • Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

    - by Mulmoth
    It is said to be a good habit to close all JDBC resources after usage. But if I have the following code, is it necessary to close the Resultset and the Statement? Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = // Retrieve connection stmt = conn.prepareStatement(// Some SQL); rs = stmt.executeQuery(); } catch { // Error Handling } finally { try { if (rs != null) rs.close(); } catch (Exception e) {}; try { if (stmt != null) stmt.close(); } catch (Exception e) {}; try { if (conn != null) conn.close(); } catch (Exception e) {}; } The question is if the closing of the connection does the job or if it leaves some resources in use.

    Read the article

  • JDBC batch insert performance

    - by wo_shi_ni_ba_ba
    I need to insert a couple hundreds of millions of records into the mysql db. I'm batch inserting it 1 million at a time. Please see my code below. It seems to be slow. Is there any way to optimize it? try { // Disable auto-commit connection.setAutoCommit(false); // Create a prepared statement String sql = "INSERT INTO mytable (xxx), VALUES(?)"; PreparedStatement pstmt = connection.prepareStatement(sql); Object[] vals=set.toArray(); for (int i=0; i

    Read the article

  • How to inherit from the main class in java

    - by user225269
    I have two java classes. One is NewFrame.java where the forms(buttons, textfields) are located. And the other one is Main.java where I have put the connection string for mysql: Main.java looks like this: public class Main { /** * @param args the command line arguments */ public static void main(String[] args) throws Exception { // TODO code application logic here Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employee_record", "root", "password"); PreparedStatement statement = con.prepareStatement("select * from employee"); ResultSet result = statement.executeQuery(); } } How do I inherit from the main.java so that the declarations in it would be universally accessible to the forms in NewFrame.java? Please help. Thanks

    Read the article

  • Fastest way for inserting very large number of records into a Table in SQL

    - by Irchi
    The problem is, we have a huge number of records (more than a million) to be inserted into a single table from a Java application. The records are created by the Java code, it's not a move from another table, so INSERT/SELECT won't help. Currently, my bottleneck is the INSERT statements. I'm using PreparedStatement to speed-up the process, but I can't get more than 50 recods per second on a normal server. The table is not complicated at all, and there are no indexes defined on it. The process takes too long, and the time it takes will make problems. What can I do to get the maximum speed (INSERT per second) possible? Database: MS SQL 2008. Application: Java-based, using Microsoft JDBC driver.

    Read the article

  • Store date object in sqlite database

    - by bnabilos
    Hello, I'm using a database in my Java project and I want to store date in it, the 5th and the 6th parameter are Date Object. I used the solution below but I have errors in these 2 lines : creerFilm.setDate(5, new Date (getDateDebut().getDate())); creerFilm.setDate(6, new Date (getDateFin().getDate())); PreparedStatement creerFilm = connecteur.getConnexion().prepareStatement("INSERT INTO FILM (ID, REF, NOM, DISTRIBUTEUR, DATEDEBUT, DATEFIN) VALUES (?, ?, ?, ?, ?, ?)"); creerFilm.setInt(1, getId()); creerFilm.setString(2, getReference()); creerFilm.setString(3, getNomFilm()); creerFilm.setString(4, getDistributeur()); creerFilm.setDate(5, new Date (getDateDebut().getDate())); creerFilm.setDate(6, new Date (getDateFin().getDate())); creerFilm.executeUpdate(); creerFilm.close(); Can you help me to fix that please ? Thank you

    Read the article

  • JAVA-SQL- Data Migration - ResultSets comparing Failing JUnit test

    - by user1865053
    I CANNOT get this JUnit Test to pass for the life of me. Can somebody point out where this has gone wrong. I am doing a data migration(MSSQL SERVER 2005), but I have the sourceDBUrl and the targetDCUrl the same URL so to narrow it down to syntax errors. So that is what I have, a syntax error. I am comparing the results of a table for the query SELECT programmeapproval, resourceapproval FROM tr_timesheet WHERE timesheetid = ? and the test always fails, but passes for other junit tests I have developed. I created 3 diffemt resultSetsEqual methods and none work. Yet, some other JUnit tests I have developed have PASSED. THE QUERY: SELECT timesheetid, programmeapproval, resourceapproval FROM tr_timesheet Returns three columns timesheetid (PK,int, not null) (populated with a range of numbers 2240 - 2282) programmeapproval (smallint,not null) (populated with the number 1 in every field) resourceapproval (smallint, not null) (populated with a number 1 in every field) When I run the query that is embedded in the code it only returns one row with the programmeapproval and resourceapproval columns and both field populated with the number 1. I have all jdbc drivers correctly installed and tested for connectivity. The JUnit Test is failing at this point according to the IDE. assertTrue(helper.resultSetsEqual2(sourceVal,targetVal)); This is the code: /*THIS IS A JUNIT CLASS****? package a7.unittests.dao; import static org.junit.Assert.assertTrue; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Types; import org.junit.Test; import artemispm.tritonalerts.TimesheetAlert; public class UnitTestTimesheetAlert { @Test public void testQUERY_CHECKALERT() throws Exception{ UnitTestHelper helper = new UnitTestHelper(); Connection con = helper.getConnection(helper.sourceDBUrl); Connection conTarget = helper.getConnection(helper.targetDBUrl); PreparedStatement stmt = con.prepareStatement("select programmeapproval, resourceapproval from tr_timesheet where timesheetid = ?"); stmt.setInt(1, 2240); ResultSet sourceVal = stmt.executeQuery(); stmt = conTarget.prepareStatement("select programmeapproval, resourceapproval from tr_timesheet where timesheetid = ?"); stmt.setInt(1,2240); ResultSet targetVal = stmt.executeQuery(); assertTrue(helper.resultSetsEqual2(sourceVal,targetVal)); }} /*END**/ /*THIS IS A REGULAR CLASS**/ package a7.unittests.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; public class UnitTestHelper { static String sourceDBUrl = "jdbc:sqlserver://127.0.0.1:1433;databaseName=a7itm;user=a7user;password=a7user"; static String targetDBUrl = "jdbc:sqlserver://127.0.0.1:1433;databaseName=a7itm;user=a7user;password=a7user"; public Connection getConnection(String url)throws Exception{ return DriverManager.getConnection(url); } public boolean resultSetsEqual3 (ResultSet rs1, ResultSet rs2) throws SQLException { int col = 1; //ResultSetMetaData metadata = rs1.getMetaData(); //int count = metadata.getColumnCount(); while (rs1.next() && rs2.next()) { final Object res1 = rs1.getObject(col); final Object res2 = rs2.getObject(col); // Check values if (!res1.equals(res2)) { throw new RuntimeException(String.format("%s and %s aren't equal at common position %d", res1, res2, col)); } // rs1 and rs2 must reach last row in the same iteration if ((rs1.isLast() != rs2.isLast())) { throw new RuntimeException("The two ResultSets contains different number of columns!"); } } return true; } public boolean resultSetsEqual (ResultSet source, ResultSet target) throws SQLException{ while(source.next()) { target.next(); ResultSetMetaData metadata = source.getMetaData(); int count = metadata.getColumnCount(); for (int i =1; i<=count; i++) { if(source.getObject(i) != target.getObject(i)) { return false; } } } return true; } public boolean resultSetsEqual2 (ResultSet source, ResultSet target) throws SQLException{ while(source.next()) { target.next(); ResultSetMetaData metadata = source.getMetaData(); int count = metadata.getColumnCount(); for (int i =1; i<=count; i++) { if(source.getObject(i).equals(target.getObject(i))) { return false; } } } return true; } } /END***/ /*PASTED NEW CLASS - THIS IS A JUNIT TEST CLASS*/ package a7.unittests.dao; import static org.junit.Assert.*; import java.sql.Connection; import java.sql.DriverManager; import org.junit.Test; public class TestDatabaseConnection { @Test public void testConnection() throws Exception{ UnitTestHelper helper = new UnitTestHelper(); Connection con = helper.getConnection(helper.sourceDBUrl); Connection conTarget = helper.getConnection(helper.targetDBUrl); assertTrue(con != null && conTarget != null); } } /**END***/

    Read the article

  • mysql mass insert data

    - by user12145
    Edit: I realized that if I construct a large query in memory, the speed has increased almost 10 times of magnitude "insert ignore into xxx(col1, col2) values('a',1), values('b',1), values('c',1)..." Edit: since I have an index on the first column, the insert time creeps up as I insert more. Can I delay the index until the end? Original: I'm using the following to batch insert 10 million rows into mysql db(not all at once, since they don't all fit into memory), it's too slow(taking many hours). should I use load file to improve performance? I would have to create a second file to store all the 10 million rows, then load that into db. are there better ways? PreparedStatement st=con.prepareStatement("insert ignore into xxx (col1, col2) "+ " values (?, 1)"); Iterator d=data.iterator(); while(d.hasNext()){ st.clearParameters(); st.setString(1, (d.next()).toLowerCase()); st.addBatch(); } int[]updateCounts=st.executeBatch();

    Read the article

  • hibernate validationQuery.. proper way to use it

    - by cometta
    sometime the connection from application to database will drop and i get SQLState: 08006 error Code: 17002. Below is my configuration for database pooling <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.use_sql_comments">true</prop> <prop key="hibernate.cglib.use_reflection_optimizer">true</prop> <!-- true ==start up slower, but performacen on runtime good--> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.c3p0.min_size">5</prop> <prop key="hibernate.c3p0.max_size">20</prop> <prop key="hibernate.c3p0.timeout">1800</prop> <prop key="hibernate.c3p0.max_statements">100</prop> <!-- c3p0's PreparedStatement cache. Zero means statement caching is turned off. --> Can anyone advise, should i use validationQuery, onBorrow.. and why need to use it? what other properties should i use to enhance stability of the connection from my application to oracle10g?

    Read the article

  • Problem with Informix JDBC, MONEY and decimal separator in string literals

    - by Michal Niklas
    I have problem with JDBC application that uses MONEY data type. When I insert into MONEY column: insert into _money_test (amt) values ('123.45') I got exception: Character to numeric conversion error The same SQL works from native Windows application using ODBC driver. I live in Poland and have Polish locale and in my country comma separates decimal part of number, so I tried: insert into _money_test (amt) values ('123,45') And it worked. I checked that in PreparedStatement I must use dot separator: 123.45. And of course I can use: insert into _money_test (amt) values (123.45) But some code is "general", it imports data from csv file and it was safe to put number into string literal. How to force JDBC to use DBMONEY (or simply dot) in literals? My workstation is WinXP. I have ODBC and JDBC Informix client in version 3.50 TC5/JC5. I have set DBMONEY to just dot: DBMONEY=. EDIT: Test code in Jython: import sys import traceback from java.sql import DriverManager from java.lang import Class Class.forName("com.informix.jdbc.IfxDriver") QUERY = "insert into _money_test (amt) values ('123.45')" def test_money(driver, db_url, usr, passwd): try: print("\n\n%s\n--------------" % (driver)) db = DriverManager.getConnection(db_url, usr, passwd) c = db.createStatement() c.execute("delete from _money_test") c.execute(QUERY) rs = c.executeQuery("select amt from _money_test") while (rs.next()): print('[%s]' % (rs.getString(1))) rs.close() c.close() db.close() except: print("there were errors!") s = traceback.format_exc() sys.stderr.write("%s\n" % (s)) print(QUERY) test_money("com.informix.jdbc.IfxDriver", 'jdbc:informix-sqli://169.0.1.225:9088/test:informixserver=ol_225;DB_LOCALE=pl_PL.CP1250;CLIENT_LOCALE=pl_PL.CP1250;charSet=CP1250', 'informix', 'passwd') test_money("sun.jdbc.odbc.JdbcOdbcDriver", 'jdbc:odbc:test', 'informix', 'passwd') Results when I run money literal with dot and comma: C:\db_examples>jython ifx_jdbc_money.py insert into _money_test (amt) values ('123,45') com.informix.jdbc.IfxDriver -------------- [123.45] sun.jdbc.odbc.JdbcOdbcDriver -------------- there were errors! Traceback (most recent call last): File "ifx_jdbc_money.py", line 16, in test_money c.execute(QUERY) SQLException: java.sql.SQLException: [Informix][Informix ODBC Driver][Informix]Character to numeric conversion error C:\db_examples>jython ifx_jdbc_money.py insert into _money_test (amt) values ('123.45') com.informix.jdbc.IfxDriver -------------- there were errors! Traceback (most recent call last): File "ifx_jdbc_money.py", line 16, in test_money c.execute(QUERY) SQLException: java.sql.SQLException: Character to numeric conversion error sun.jdbc.odbc.JdbcOdbcDriver -------------- [123.45]

    Read the article

  • "Parameter type conflict" when calling Java Stored Procedure within another Java Stored Procedure

    - by GuiPereira
    Here's the problem (sorry for the bad english): i'm working with JDeveloper and Oracle10g, and i have a Java Stored Procedure that is calling another JSP like the code: int sd = 0; try { CallableStatement clstAddRel = conn.prepareCall(" {call FC_RJS_INCLUIR_RELACAO_PRODCAT(?,?)} "); clstAddRel.registerOutParameter(1, Types.INTEGER); clstAddRel.setString(1, Integer.toString(id_produto_interno)); clstAddRel.setString(2, ac[i].toString()); clstAddRel.execute(); sd = clstAddRel.getInt(1); } catch(SQLException e) { String sqlTeste3 = "insert into ateste values (SQ_ATESTE.nextval, ?)"; PreparedStatement pstTeste3 = conn.prepareStatement(sqlTeste3); pstTeste3.setString(1,"erro: "+e.getMessage()+ ac[i]); pstTeste3.execute(); pstTeste3.close(); } I'm recording the error in a table called ATESTE because this JavaSP is a procedure and not a function, I've to manipulate DML inside. So, the error message I'm getting is: 'parameter type conflict'... the function "FC_RJS_INCLUIR_RELACAO_PRODCAT" it's a Java Stored Procedure too, it's already exported to Oracle, and returns an int variable, and i have to read this to decide which webservice i will call from this JavaSP. I have already tried the OracleTyep.NUMBER in the registerOutParameter. Anyone knows what i'm doing wrong?

    Read the article

  • Hibernate: how to call a stored function returning a varchar?

    - by Péter Török
    I am trying to call a legacy stored function in an Oracle9i DB from Java using Hibernate. The function is declared like this: create or replace FUNCTION Transferlocation_Fix (mnemonic_code IN VARCHAR2) RETURN VARCHAR2 After several failed tries and extensive googling, I found this thread on the Hibernate forums which suggested a mapping like this: <sql-query name="TransferLocationFix" callable="true"> <return-scalar column="retVal" type="string"/> select Transferlocation_Fix(:mnemonic) as retVal from dual </sql-query> My code to execute it is Query query = session.getNamedQuery("TransferLocationFix"); query.setParameter("mnemonic", "FC3"); String result = (String) query.uniqueResult(); and the resulting log is DEBUG (org.hibernate.jdbc.AbstractBatcher:366) - - about to open PreparedStatement (open PreparedStatements: 0, globally: 0) DEBUG (org.hibernate.SQL:401) - - select Transferlocation_Fix(?) as retVal from dual TRACE (org.hibernate.jdbc.AbstractBatcher:484) - - preparing statement TRACE (org.hibernate.type.StringType:133) - - binding 'FC3' to parameter: 2 TRACE (org.hibernate.type.StringType:133) - - binding 'FC3' to parameter: 2 java.lang.NullPointerException at oracle.jdbc.ttc7.TTCAdapter.newTTCType(TTCAdapter.java:300) at oracle.jdbc.ttc7.TTCAdapter.createNonPlsqlTTCColumnArray(TTCAdapter.java:270) at oracle.jdbc.ttc7.TTCAdapter.createNonPlsqlTTCDataSet(TTCAdapter.java:231) at oracle.jdbc.ttc7.TTC7Protocol.doOall7(TTC7Protocol.java:1924) at oracle.jdbc.ttc7.TTC7Protocol.parseExecuteDescribe(TTC7Protocol.java:850) at oracle.jdbc.driver.OracleStatement.doExecuteQuery(OracleStatement.java:2599) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2963) at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:658) at oracle.jdbc.driver.OraclePreparedStatement.execute(OraclePreparedStatement.java:736) at com.mchange.v2.c3p0.impl.NewProxyCallableStatement.execute(NewProxyCallableStatement.java:3044) at org.hibernate.dialect.Oracle8iDialect.getResultSet(Oracle8iDialect.java:379) at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:193) at org.hibernate.loader.Loader.getResultSet(Loader.java:1784) at org.hibernate.loader.Loader.doQuery(Loader.java:674) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236) at org.hibernate.loader.Loader.doList(Loader.java:2220) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2104) at org.hibernate.loader.Loader.list(Loader.java:2099) at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:289) at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1695) at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:142) at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:152) at org.hibernate.impl.AbstractQueryImpl.uniqueResult(AbstractQueryImpl.java:811) at com.my.project.SomeClass.method(SomeClass.java:202) ... Any clues what am I doing wrong? Or any better ways to call this stored function?

    Read the article

  • Oracle T4CPreparedStatement memory leaks?

    - by Jay
    A little background on the application that I am gonna talk about in the next few lines: XYZ is a data masking workbench eclipse RCP application: You give it a source table column, and a target table column, it would apply a trasformation (encryption/shuffling/etc) and copy the row data from source table to target table. Now, when I mask n tables at a time, n threads are launched by this app. Here is the issue: I have run into a production issue on first roll out of the above said app. Unfortunately, I don't have any logs to get to the root. However, I tried to run this app in test region and do a stress test. When I collected .hprof files and ran 'em through an analyzer (yourKit), I noticed that objects of oracle.jdbc.driver.T4CPreparedStatement was retaining heap. The analysis also tells me that one of my classes is holding a reference to this preparedstatement object and thereby, n threads have n such objects. T4CPreparedStatement seemed to have character arrays: lastBoundChars and bindChars each of size char[300000]. So, I researched a bit (google!), obtained ojdbc6.jar and tried decompiling T4CPreparedStatement. I see that T4CPreparedStatement extends OraclePreparedStatement, which dynamically manages array size of lastBoundChars and bindChars. So, my questions here are: Have you ever run into an issue like this? Do you know the significance of lastBoundChars / bindChars? I am new to profiling, so do you think I am not doing it correct? (I also ran the hprofs through MAT - and this was the main identified issue - so, I don't really think I could be wrong?) I have found something similar on the web here: http://forums.oracle.com/forums/thread.jspa?messageID=2860681 Appreciate your suggestions / advice.

    Read the article

  • Using prepared statements with JDBCTemplate

    - by Bernhard V
    Hi. I'm using the Jdbc template and want to read from the database using prepared statements. I iterate over many lines in a csv file and on every line I execute some sql select queries with it's values. Now I want to speed up my reading from the database but I just can't get the Jdbc template to work with prepared statements. Actually I even don't know how to do it. There is the PreparedStatementCreator and the PreparedStatementCreator. As in this example both of them are created with anonymous inner classes. But inside the PreparedStatementCreator class I don't have access to the values I want to set in the prepared statement. Since I'm iterating through a csv file I can't hard code them as a String because I don't know them. I also can't pass them to the PreparedStatementCreator because there are no arguments for the constructor. I was used to the creation of prepared statements being fairly simple. Something like PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ? "); updateSales.setInt(1, 75); updateSales.setString(2, "Colombian"); updateSales.executeUpdate(): as in the Java tutorial. Your help would be very appreciated.

    Read the article

  • JDBC ODBC.. (Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException)

    - by enthudrives
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { PreparedStatement p1; String s="insert into reg values(?,?)"; try { p1 = conn.prepareStatement(s); System.out.println("hi?"); p1.setString(1, num.getText()); p1.setString(2, name.getText()); p1.executeUpdate(); // TODO add your handling code here: } catch (SQLException ex) { Logger.getLogger(sample.class.getName()).log(Level.SEVERE, null, ex); } } This is my insert module.. This works in my friend's laptop. But not in mine :( I get the following error: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at sample.jButton1ActionPerformed(sample.java:197) at sample.access$200(sample.java:20) at sample$3.actionPerformed(sample.java:92) at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995) at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318) at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387) at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236) at java.awt.Component.processMouseEvent(Component.java:6263) at javax.swing.JComponent.processMouseEvent(JComponent.java:3267) at java.awt.Component.processEvent(Component.java:6028) at java.awt.Container.processEvent(Container.java:2041) at java.awt.Component.dispatchEventImpl(Component.java:4630) at java.awt.Container.dispatchEventImpl(Container.java:2099) at java.awt.Component.dispatchEvent(Component.java:4460) at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574) at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238) at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168) at java.awt.Container.dispatchEventImpl(Container.java:2085) at java.awt.Window.dispatchEventImpl(Window.java:2478) at java.awt.Component.dispatchEvent(Component.java:4460) at java.awt.EventQueue.dispatchEvent(EventQueue.java:599) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) Java Result: 1 PS: I am totally new to java. Is it a problem with my ODBC?

    Read the article

  • Struts DB query execution problem

    - by henderunal
    Hello, I am trying to insert a data to my db2 9.7 database from IBM RAD 7.5 using struts 1.3 But when i execute the query i got this errors: http://pastebin.com/3UPTVKbh KayitBean kayit=(KayitBean)form; //String name = kayit.getName(); String name="endee"; DBConn hb = new DBConn(); Connection conn =hb.getConnection(); System.out.println("basarili"); //String sql = "SELECT * FROM ENDER.\"MEKANDENEME\""; String sql = "INSERT INTO ENDER.\"MEKANDENEME\" VALUES (\'endere\' ,\'bos\');"; System.out.println(sql); System.out.println("basarili2"); PreparedStatement ps = conn.prepareStatement(sql); System.out.println("basarili3"); ResultSet rs = ps.executeQuery(); // String ender=rs.getArray(1).toString(); System.out.println("basarili4"); // System.out.println(rs); conn.close(); I am receiving this after System.out.println("basarili3");" Please help me.

    Read the article

  • How to use SQLErrorCodeSQLExceptionTranslator and DAO class with @Repository in Spring?

    - by GuidoMB
    I'm using Spring 3.0.2 and I have a class called MovieDAO that uses JDBC to handle the db. I have set the @Repository annotations and I want to convert the SQLException to the Spring's DataAccessException I have the following example: @Repository public class JDBCCommentDAO implements CommentDAO { static JDBCCommentDAO instance; ConnectionManager connectionManager; private JDBCCommentDAO() { connectionManager = new ConnectionManager("org.postgresql.Driver", "postgres", "postgres"); } static public synchronized JDBCCommentDAO getInstance() { if (instance == null) instance = new JDBCCommentDAO(); return instance; } @Override public Collection<Comment> getComments(User user) throws DAOException { Collection<Comment> comments = new ArrayList<Comment>(); try { String query = "SELECT * FROM Comments WHERE Comments.userId = ?"; Connection conn = connectionManager.getConnection(); PreparedStatement stmt = conn.prepareStatement(query); stmt = conn.prepareStatement(query); stmt.setInt(1, user.getId()); ResultSet result = stmt.executeQuery(); while (result.next()) { Movie movie = JDBCMovieDAO.getInstance().getLightMovie(result.getInt("movie")); comments.add(new Comment(result.getString("text"), result.getInt("score"), user, result.getDate("date"), movie)); } connectionManager.closeConnection(conn); } catch (SQLException e) { e.printStackTrace(); //CONVERT TO DATAACCESSEXCEPTION } return comments; } } I Don't know how to get the Translator and I don't want to extends any Spring class, because that is why I'm using the @Repository annotation

    Read the article

  • Why is log4j not behaving as expected?

    - by Kieveli
    I have a co-worker who is trying to get log4j to behave as follows: Log to Stdout By default, disable most output Show only messages from java.sql.PrepareStatement at level debug and up He's getting caught up in the 'level' vs 'priority'. Here is his config file: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE log4j:configuration SYSTEM "D:/Java/apache-log4j-1.2.15/src/main/resources/org/apache/log4j/xml/log4j.dtd" > <log4j:configuration> <!-- Appenders --> <appender name="stdout" class="org.apache.log4j.ConsoleAppender"> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%5p %d{ISO8601} [%t][%x] %c - %m%n" /> </layout> </appender> <!-- Loggers for ibatus and JDBC database --> <logger name="java.sql.PreparedStatement"> <level value="debug"/> </logger> <!-- The Root Logger --> <root> <level value="error"/> <appender-ref ref="stdout"/> </root> </log4j:configuration> The output from this shows no messages in the log output. How does he need to change his log4j.xml config file to make it behave as he's expecting?

    Read the article

  • Sturts DB query execution problem

    - by henderunal
    Hello, I am trying to insert a data to my db2 9.7 database from IBM RAD 7.5 using struts 1.3 But when i execute the query i got this errors [Pastebin link][1] Here is my code KayitBean kayit=(KayitBean)form; //String name = kayit.getName(); String name="endee"; DBConn hb = new DBConn(); Connection conn =hb.getConnection(); System.out.println("basarili"); //String sql = "SELECT * FROM ENDER.\"MEKANDENEME\""; String sql = "INSERT INTO ENDER.\"MEKANDENEME\" VALUES (\'endere\' ,\'bos\');"; System.out.println(sql); System.out.println("basarili2"); PreparedStatement ps = conn.prepareStatement(sql); System.out.println("basarili3"); ResultSet rs = ps.executeQuery(); // String ender=rs.getArray(1).toString(); System.out.println("basarili4"); // System.out.println(rs); conn.close(); I am receiving this after System.out.println("basarili3");" Please help me.

    Read the article

  • Problems with string parameter insertion into prepared statement

    - by c0d3x
    Hi, I have a database running on an MS SQL Server. My application communicates via JDBC and ODBC with it. Now I try to use prepared statements. When I insert a numeric (Long) parameter everything works fine. When I insert a string parameter it does not work. There is no error message, but an empty result set. WHERE column LIKE ('%' + ? + '%') --inserted "test" -> empty result set WHERE column LIKE ? --inserted "%test%" -> empty result set WHERE column = ? --inserted "test" -> works But I need the LIKE functionality. When I insert the same string directly into the query string (not as a prepared statement parameter) it runs fine. WHERE column LIKE '%test%' It looks a little bit like double quoting for me, but I never used quotes inside a string. I use preparedStatement.setString(int index, String x) for insertion. What is causing this problem? How can I fix it? Thanks in advance.

    Read the article

  • Java: ResultSet exception - before start of result set

    - by Rosarch
    I'm having trouble getting data from a ResultSet object. Here is my code: String sql = "SELECT type FROM node WHERE nid = ?"; PreparedStatement prep = conn.prepareStatement(sql); int meetNID = Integer.parseInt(node.get(BoutField.field_meet_nid)); prep.setInt(1, meetNID); ResultSet result = prep.executeQuery(); result.beforeFirst(); String foundType = result.getString(1); if (! foundType.equals("meet")) { throw new IllegalArgumentException(String.format("Node %d must be of type 'meet', but was %s", meetNID, foundType)); } The error trace: Exception in thread "main" java.sql.SQLException: Before start of result set at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1072) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:986) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:981) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926) at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:841) at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5656) at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5576) at nth.cumf3.nodeImport.Validator.validate(Validator.java:43) at nth.cumf3.nodeImport.Main.main(Main.java:38) What am I doing wrong here?

    Read the article

  • SELECT * FROM <table> BETWEEN <value typed in a JTextField> AND <idem>

    - by Rodrigo Sieja Bertin
    In this part of the program, the JInternalFrame file FrmMovimento, I made a button called Visualizar ("View"). Based on what we type on the text fields, it must show the interval the user defined. There are these JTextFields: Code from: _ To: _ Asset: _ And these JFormattedTextFields: Date from: _ To: _ There are registers appearing already in the JDesktopPane from JInternalFrame FrmListarMov, if I use another SELECT statement selecting all registers, for example. But not if I type as I did in the title: public List<MovimentoVO> Lista() throws ErroException, InformacaoException{ List<MovimentoVO> listaMovimento = new ArrayList<> (); try { MySQLDAO.getInstancia().setAutoCommit(false); try (PreparedStatement stmt = MySQLDAO.getInstancia().prepareStatement( "SELECT * FROM Cadastro2 WHERE Codigo BETWEEN "+ txtCodDeMov +" AND "+ txtCodAteMov +";") { ResultSet registro = stmt.executeQuery(); while(registro.next()){ MovimentoVO Movimento = new MovimentoVO(); Movimento.setCodDeMov(registro.getInt(1)); Movimento.setCodAteMov(registro.getInt(2)); Movimento.setAtivoMov(registro.getString(3)); Movimento.setDataDeMov(registro.getString(4)); Movimento.setDataAteMov(registro.getString(5)); listaMovimento.add(Movimento); } } } catch (SQLException ex) { throw new ErroException(ex.getMessage()); } catch (InformacaoException ex) { throw ex; } return listaMovimento; } In the SELECT line, txtCodDeMov is how I named the JTextField of "Code from" and txtCodAtemov is how I named the JTextField of the first "To". Oh, I'm using NetBeans 7.1.2 (Build 201204101705) and MySQL Ver 14.14 Distrib 5.1.63 in a Linux Mint 12 64-bits.

    Read the article

  • Can not issue data manipulation statements with executeQuery in java

    - by user225269
    I'm trying to insert records in mysql database using java, What do I place in this code so that I could insert records: String id; String name; String school; String gender; String lang; Scanner inputs = new Scanner(System.in); System.out.println("Input id:"); id=inputs.next(); System.out.println("Input name:"); name=inputs.next(); System.out.println("Input school:"); school= inputs.next(); System.out.println("Input gender:"); gender= inputs.next(); System.out.println("Input lang:"); lang=inputs.next(); Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/employee_record", "root", "MyPassword"); PreparedStatement statement = con.prepareStatement("insert into employee values('id', 'name', 'school', 'gender', 'lang');"); statement.executeUpdate();

    Read the article

  • When to use @Singleton in a Jersey resource

    - by dexter
    I have a Jersey resource that access the database. Basically it opens a database connection in the initialization of the resource. Performs queries on the resource's methods. I have observed that when I do not use @Singleton, the database is being open at each request. And we know opening a connection is really expensive right? So my question is, should I specify that the resource be singleton or is it really better to keep it at per request especially when the resource is connecting to the database? My resource code looks like this: //Use @Singleton here or not? @Path(/myservice/) public class MyResource { private ResponseGenerator responser; private Log logger = LogFactory.getLog(MyResource.class); public MyResource() { responser = new ResponseGenerator(); } @GET @Path("/clients") public String getClients() { logger.info("GETTING LIST OF CLIENTS"); return responser.returnClients(); } ... // some more methods ... } And I connect to the database using a code similar to this: public class ResponseGenerator { private Connection conn; private PreparedStatement prepStmt; private ResultSet rs; public ResponseGenerator(){ Class.forName("org.h2.Driver"); conn = DriverManager.getConnection("jdbc:h2:testdb"); } public String returnClients(){ String result; try{ prepStmt = conn.prepareStatement("SELECT * FROM hosts"); rs = prepStmt.executeQuery(); ... //do some processing here ... } catch (SQLException se){ logger.warn("Some message"); } finally { rs.close(); prepStmt.close(); // should I also close the connection here (in every method) if I stick to per request // and add getting of connection at the start of every method // conn.close(); } return result } ... // some more methods ... } Some comments on best practices for the code will also be helpful.

    Read the article

  • How to convert a list object to bigdecimal in prepared statement?

    - by user1103504
    I am using prepared statement for bulk insertion of records. Iam iterating a list which contains values and their dataTypes differ. One of the data type is BigDecimal and when i try to set calling preparedstatement, it is throwing null pointer exception. My code int count = 1; for (int j = 0; j < list.size(); j++) { if(list.get(j) instanceof Timestamp) { ps.setTimestamp(count, (Timestamp) list.get(j)); } else if(list.get(j) instanceof java.lang.Character) { ps.setString(count, String.valueOf(list.get(j))); } else if(list.get(j) instanceof java.math.BigDecimal) { ps.setBigDecimal(count, (java.math.BigDecimal)list.get(j)); } else { ps.setObject(count, list.get(j)); } count++; } I tried 2 ways to convert, casting the object and tried to create a new object of type BigDecimal ps.setBigDecimal(count, new BigDecimal(list.get(j).toString)); both donot solve my problem. It is throwing null pointer exception. help is appreciated. Thanks

    Read the article

  • Best way to run multiple queries per second on database, performance wise?

    - by Michael Joell
    I am currently using Java to insert and update data multiple times per second. Never having used databases with Java, I am not sure what is required, and how to get the best performance. I currently have a method for each type of query I need to do (for example, update a row in a database). I also have a method to create the database connection. Below is my simplified code. public static void addOneForUserInChannel(String channel, String username) throws SQLException { Connection dbConnection = null; PreparedStatement ps = null; String updateSQL = "UPDATE " + channel + "_count SET messages = messages + 1 WHERE username = ?"; try { dbConnection = getDBConnection(); ps = dbConnection.prepareStatement(updateSQL); ps.setString(1, username); ps.executeUpdate(); } catch(SQLException e) { System.out.println(e.getMessage()); } finally { if(ps != null) { ps.close(); } if(dbConnection != null) { dbConnection.close(); } } } And my DB connection private static Connection getDBConnection() { Connection dbConnection = null; try { Class.forName(DB_DRIVER); } catch (ClassNotFoundException e) { System.out.println(e.getMessage()); } try { dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER,DB_PASSWORD); return dbConnection; } catch (SQLException e) { System.out.println(e.getMessage()); } return dbConnection; } This seems to be working fine for now, with about 1-2 queries per second, but I am worried that once I expand and it is running many more, I might have some issues. My questions: Is there a way to have a persistent database connection throughout the entire run time of the process? If so, should I do this? Are there any other optimizations that I should do to help with performance? Thanks

    Read the article

< Previous Page | 1 2 3 4 5  | Next Page >