Search Results

Search found 429 results on 18 pages for 'sqlexception'.

Page 5/18 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • SimpleJdbcCall ignoring JdbcTemplate fetch size

    - by user289429
    We are calling the pl/sql stored procedure through Spring SimpleJdbcCall, the fetchsize set on the JdbcTemplate is being ignored by SimpleJdbcCall. The rowmapper resultset fetch size is set to 10 even though we have set the jdbctemplate fetchsize to 200. Any idea why this happens and how to fix it? Have printed the fetchsize of resultset in the rowmapper in the below code snippet - Once it is 200 and other time it is 10 even though I use the same JdbcTemplate on both occassion. This direct execution through jdbctemplate returns fetchsize of 200 in the row mapper jdbcTemplate = new JdbcTemplate(ds); jdbcTemplate.setResultsMapCaseInsensitive(true); jdbcTemplate.setFetchSize(200); List temp = jdbcTemplate.query("select 1 from dual", new ParameterizedRowMapper() { public Object mapRow(ResultSet resultSet, int i) throws SQLException { System.out.println("Direct template : " + resultSet.getFetchSize()); return new String(resultSet.getString(1)); } }); This execution through SimpleJdbcCall is always returning fetchsize of 10 in the rowmapper jdbcCall = new SimpleJdbcCall(jdbcTemplate).withSchemaName(schemaName) .withCatalogName(catalogName).withProcedureName(functionName); jdbcCall.returningResultSet((String) outItValues.next(), new ParameterizedRowMapper<Map<String, Object>>() { public Map<String, Object> mapRow(ResultSet rs, int row) throws SQLException { System.out.println("Through simplejdbccall " + rs.getFetchSize()); return extractRS(rs, row); } }); outputList = (List<Map<String, Object>>) jdbcCall.executeObject(List.class, inParam);

    Read the article

  • Conversion failed when converting datetime from character string. Linq To SQL & OpenXML

    - by chobo2
    Hi I been following this tutorial on how to do a linq to sql batch insert. http://www.codeproject.com/KB/linq/BulkOperations_LinqToSQL.aspx However I have a datetime field in my database and I keep getting this error. System.Data.SqlClient.SqlException was unhandled Message="Conversion failed when converting datetime from character string." Source=".Net SqlClient Data Provider" ErrorCode=-2146232060 Class=16 LineNumber=7 Number=241 Procedure="spTEST_InsertXMLTEST_TEST" Server="" State=1 StackTrace: at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) I am not sure why when I just take the datetime in the generated xml file and manually copy it into sql server 2005 it has no problem with it and converts it just fine. This is my SP CREATE PROCEDURE [dbo].[spTEST_InsertXMLTEST_TEST](@UpdatedProdData nText) AS DECLARE @hDoc int exec sp_xml_preparedocument @hDoc OUTPUT,@UpdatedProdData INSERT INTO UserTable(CreateDate) SELECT XMLProdTable.CreateDate FROM OPENXML(@hDoc, 'ArrayOfUserTable/UserTable', 2) WITH ( CreateDate datetime ) XMLProdTable EXEC sp_xml_removedocument @hDoc C# code using (TestDataContext db = new TestDataContext()) { UserTable[] testRecords = new UserTable[1]; for (int count = 0; count < 1; count++) { UserTable testRecord = new UserTable() { CreateDate = DateTime.Now }; testRecords[count] = testRecord; } StringBuilder sBuilder = new StringBuilder(); System.IO.StringWriter sWriter = new System.IO.StringWriter(sBuilder); XmlSerializer serializer = new XmlSerializer(typeof(UserTable[])); serializer.Serialize(sWriter, testRecords); db.spTEST_InsertXMLTEST_TEST(sBuilder.ToString()); } Rendered XML Doc <?xml version="1.0" encoding="utf-16"?> <ArrayOfUserTable xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <UserTable> <CreateDate>2010-05-19T19:35:54.9339251-07:00</CreateDate> </UserTable> </ArrayOfUserTable>

    Read the article

  • Struts2 example, not inserting records in mysql database because connection object is getting null

    - by Jugal
    This Code is working fine with simple application so the drivers are fine. so why the connection object is not able to initialise with drivers. import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import com.opensymphony.xwork2.ActionSupport; public class Insert extends ActionSupport { public String execute() throws Exception, SQLException { String sql = ""; String url = "jdbc:mysql://localhost:3306/test"; //String dbName = "test"; String driverName = "org.gjt.mm.mysql.Driver"; String userName = "root"; String password = "root"; Connection con=null; Statement stmt=null; try { Class.forName(driverName).newInstance(); con = DriverManager.getConnection(url, userName, password); stmt = con.createStatement(); } catch (Exception e) { System.out.println(e.getMessage()); } }

    Read the article

  • Problem connecting to Apache Derby using Hibernate configuration file in Netbeans (ERROR XSDB6)

    - by me_here
    I've created a local Apache Derby database in Netbeans, but am having problems when I try and autogenerate the POJO files, using the "Hibernate Reverse Engineering Wizard". My Hibernate configuration (generated by Netbeans from the database connection, then I added a few bits): <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Default Netbeans generated parameters --> <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.EmbeddedDriver</property> <property name="hibernate.connection.url">jdbc:derby:C:/CerealDatabase</property> <property name="hibernate.connection.username">cerealuser</property> <property name="hibernate.connection.password">cerealpass</property> <!-- Additional parameters --> <property name="hibernate.dialect">org.hibernate.dialect.DerbyDialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.default_schema">CEREALUSER</property> </session-factory> </hibernate-configuration> When I try and generate the POJOs using this configuration file, I get the message to check my configuration file, and the derby.log gives the errors: java.sql.SQLException: Failed to start database 'C:/CerealDatabase', see the next exception for details. Caused by: java.sql.SQLException: Failed to start database 'C:/CerealDatabase', see the next exception for details. Caused by: ERROR XSDB6: Another instance of Derby may have already booted the database C:\CerealDatabase. I've closed any other connections to the database before trying this, and there is no "db.lck" lock file at the time, which indicates there are no connections to the database as I understand it. Does anyone have any ideas? Help gratefully received.

    Read the article

  • how to restrict a jsp hit counter?

    - by user261002
    I am writing a hot counter in jsp, for my coursework. I have write the code, and there is not error and its working, but the problem is that: if the user have open the website and try to user different page, when ever that the user get back to the home page the counter still is adding a number , how can I restrict this part??? shall restrict it with session?? this is my code : The current count for the counter bean is: <% counter.saveCount(); int _numberofvisitors=counter.getVisitorsNumber(); out.println(_numberofvisitors); % Bean: package counter; import java.sql.*; import java.sql.SQLException; public class CounterBean implements java.io.Serializable { int coun = 0; public CounterBean() { database.DatabaseManager.getInstance().getDatabaseConnection(); } public int getCoun() { return this.coun; } public void setCoun(int coun) { this.coun += coun; } public boolean saveCount() { boolean _save = false; database.SQLUpdateStatement sqlupdate = new database.SQLUpdateStatement("counter", "hitcounter"); sqlupdate.addColumn("hitcounter", getCoun()); if (sqlupdate.Execute()) { _save = true; } return _save; } public int getVisitorsNumber() throws SQLException { int numberOfVisitors = 0; if (database.DatabaseManager.getInstance().connectionOK()) { database.SQLSelectStatement sqlselect = new database.SQLSelectStatement("counter", "hitcounter", "0"); ResultSet _userExist = sqlselect.executeWithNoCondition(); if (_userExist.next()) { numberOfVisitors = _userExist.getInt("hitcounter"); } } return numberOfVisitors; } }

    Read the article

  • ASP.NET Sql Timeout

    - by Petoj
    Well we have this Asp.Net application that we installed at a customer but now some times we get a SqlException that says "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding." now the wired thing is that the exception comes instantly when i press the button, this does not happen every time i press the button so its random.. any idea what i could try to pinpoint the problem? We are using the EnterpriseLibrary Database block if that matters... Stack trace: at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlDataReader.ConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at Microsoft.Practices.EnterpriseLibrary.Data.Database.DoExecuteReader(DbCommand command, CommandBehavior cmdBehavior) at Microsoft.Practices.EnterpriseLibrary.Data.Database.ExecuteReader(DbCommand command)

    Read the article

  • ADO.NET Batch Insert with over 2000 parameters

    - by Liming
    Hello all, I'm using Enterprise library, but the idea is the same. I have a SqlStringCommand and the sql is constructed using StringBuilder in the forms of "insert into table (column1, column2, column3) values (@param1-X, @param2-X, @parm3-X)"+" " where "X" represents a "for loop" about 700 rows StringBuilder sb = new StringBuilder(); for(int i=0; i<700; i++) { sb.Append("insert into table (column1, column2, column3) values (@param1-"+i+", @param2-"+i, +",@parm3-"+i+") " ); } followed by constructing a command object injecting all the parameters w/ values into it. Essentially, 700 rows with 3 parameters, I ended up with 2100 parameters for this "one sql" Statement. It ran fine for about a few days and suddenly I got this error =============================================================== A severe error occurred on the current command. The results, if any, should be discarded. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.InternalExecuteNon Any pointers are greatly appreciated.

    Read the article

  • using JMock to write unit test for a simple spring JDBC DAO

    - by Quincy
    I'm writing an unit test for spring jdbc dao. The method to test is: public long getALong() { return simpleJdbcTemplate.queryForObject("sql query here", new RowMapper<Long>() { public Long mapRow(ResultSet resultSet, int i) throws SQLException { return resultSet.getLong("a_long"); } }); } Here is what I have in the test: public void testGetALong() throws Exception { final Long result = 1000L; context.checking(new Expectations() {{ oneOf(simpleJdbcTemplate).queryForObject("sql_query", new RowMapper<Long>() { public Long mapRow(ResultSet resultSet, int i) throws SQLException { return resultSet.getLong("a_long"); } }); will(returnValue(result)); }}); Long seq = dao.getALong(); context.assertIsSatisfied(); assertEquals(seq, result); } Naturally, the test doesn't work (otherwise, I wouldn't be asking this question here). The problem is the rowmapper in the test is different from the rowmapper in the DAO. So the expectation is not met. I tried to put with around the sql query and with(any(RowMapper.class)) for the rowmapper. It wouldn't work either, complains about "not all parameters were given explicit matchers: either all parameters must be specified by matchers or all must be specified by values, you cannot mix matchers and values"

    Read the article

  • executing stored procedure from Spring-Hibernate using Annotations

    - by HanuAthena
    I'm trying to execute a simple stored procedure with Spring/Hibernate using Annotations. Here are my code snippets: DAO class: public class UserDAO extends HibernateDaoSupport { public List selectUsers(final String eid){ return (List) getHibernateTemplate().execute(new HibernateCallback() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Query q = session.getNamedQuery("SP_APPL_USER"); System.out.println(q); q.setString("eid", eid); return q.list(); } }); } } my entity class: @Entity @Table(name = "APPL_USER") @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorFormula(value = "SUBSCRIBER_IND") @DiscriminatorValue("N") @NamedQuery(name = "req.all", query = "select n from Requestor n") @org.hibernate.annotations.NamedNativeQuery(name = "SP_APPL_USER", query = "call SP_APPL_USER(?, :eid)", callable = true, readOnly = true, resultClass = Requestor.class) public class Requestor { @Id @Column(name = "EMPL_ID") public String getEmpid() { return empid; } public void setEmpid(String empid) { this.empid = empid; } @Column(name = "EMPL_FRST_NM") public String getFirstname() { return firstname; } ... } public class Test { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext( "applicationContext.xml"); APFUser user = (APFUser)ctx.getBean("apfUser"); List selectUsers = user.getUserDAO().selectUsers("EMP456"); System.out.println(selectUsers); } } and the stored procedure: create or replace PROCEDURE SP_APPL_USER (p_cursor out sys_refcursor, eid in varchar2) as empId varchar2(8); fname varchar2(50); lname varchar2(50); begin empId := null; fname := null; lname := null; open p_cursor for select l.EMPL_ID, l.EMPL_FRST_NM, l.EMPL_LST_NM into empId, fname, lname from APPL_USER l where l.EMPL_ID = eid; end; If i enter invalid EID, its returning empty list which is OK. But when record is there, following exception is thrown: Exception in thread "main" org.springframework.jdbc.BadSqlGrammarException: Hibernate operation: could not execute query; bad SQL grammar [call SP_APPL_USER(?, ?)]; nested exception is java.sql.SQLException: Invalid column name Do I need to modify the entity(Requestor.class) ? How will the REFCURSOR be converted to the List? The stored procedure is expected to return more than one record.

    Read the article

  • Help with Exception Handling in ASP.NET C# Application

    - by Shrewd Demon
    hi, yesterday i posted a question regarding the Exception Handling technique, but i did'nt quite get a precise answer, partly because my question must not have been precise. So i will ask it more precisely. There is a method in my BLL for authenticating user. If a user is authenticated it returns me the instance of the User class which i store in the session object for further references. the method looks something like this... public static UsersEnt LoadUserInfo(string email) { SqlDataReader reader = null; UsersEnt user = null; using (ConnectionManager cm = new ConnectionManager()) { SqlParameter[] parameters = new SqlParameter[1]; parameters[0] = new SqlParameter("@Email", email); try { reader = SQLHelper.ExecuteReader(cm.Connection, "sp_LoadUserInfo", parameters); } catch (SqlException ex) { //this gives me a error object } if (reader.Read()) user = new UsersDF(reader); } return user; } now my problem is suppose if the SP does not exist, then it will throw me an error or any other SQLException for that matter. Since this method is being called from my aspx.cs page i want to return some meaning full message as to what could have gone wrong so that the user understands that there was some problem and that he/she should retry logging-in again. but i can't because the method returns an instance of the User class, so how can i return a message instead ?? i hope i made it clear ! thank you.

    Read the article

  • SQL Express under IIS 7.5

    - by fampinheiro
    I´m developing a web service that access a SQL Express database, it works very well in the Visual Studio host but when i deploy it to IIS 7.5 i get this exception. Please help me. Stack Trace: System.Data.EntityException: The underlying provider failed on Open. ---> System.Data.SqlClient.SqlException: Failed to generate a user instance of SQL Server due to failure in retrieving the user's local application data path. Please make sure the user has a local user profile on the computer. The connection will be closed. at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) at System.Data.SqlClient.SqlConnection.Open() at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) --- End of inner exception stack trace --- at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure) at System.Data.EntityClient.EntityConnection.Open() at System.Data.Objects.ObjectContext.EnsureConnection() at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source) at WSCinema.CinemaService.Movie() in D:\Documents\My Dropbox\Projects\sd.v0910\trab3\code\WSCinema\CinemaService.asmx.cs:line 46

    Read the article

  • handling DATETIME values 0000-00-00 00:00:00 in JDBC

    - by Jason S
    I get an exception (see below) if I try to do resultset.getString("add_date"); for a JDBC connection to a MySQL database containing a DATETIME value of 0000-00-00 00:00:00 (the quasi-null value for DATETIME), even though I'm just trying to get the value as string, not as an object. I got around this by doing SELECT CAST(add_date AS CHAR) as add_date which works, but seems silly... is there a better way to do this? My point is that I just want the raw DATETIME string, so I can parse it myself as is. note: here's where the 0000 comes in: (from http://dev.mysql.com/doc/refman/5.0/en/datetime.html) Illegal DATETIME, DATE, or TIMESTAMP values are converted to the “zero” value of the appropriate type ('0000-00-00 00:00:00' or '0000-00-00'). The specific exception is this one: SQLException: Cannot convert value '0000-00-00 00:00:00' from column 5 to TIMESTAMP. SQLState: S1009 VendorError: 0 java.sql.SQLException: Cannot convert value '0000-00-00 00:00:00' from column 5 to TIMESTAMP. at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926) at com.mysql.jdbc.ResultSetImpl.getTimestampFromString(ResultSetImpl.java:6343) at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5670) at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5491) at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5531)

    Read the article

  • Conversion failed: SqlParameter and DateTime

    - by Tim
    I'm changing old,vulnerable sqlcommands with SqlParameters but get a SqlException: System.Data.SqlClient.SqlException {"Conversion failed when converting datetime from character string."} on sqlCommand.ExecuteScalar() Dim sqlString As String = _ "SELECT TOP 1 " & _ "fiSL " & _ "FROM " & _ "tabData AS D " & _ "WHERE " & _ "D.SSN_Number = '@SSN_Number' " & _ "AND D.fiProductType = 1 " & _ "AND D.Repair_Completion_Date > '@Repair_Completion_Date' " & _ "ORDER BY " & _ "D.Repair_Completion_Date ASC" Dim obj As Object Dim sqlCommand As SqlCommand Try sqlCommand = New SqlCommand(sqlString, Common.MyDB.SqlConn_RM2) sqlCommand.CommandTimeout = 120 sqlCommand.Parameters.AddWithValue("@SSN_Number", myClaim.SSNNumber) sqlCommand.Parameters.AddWithValue("@Repair_Completion_Date", myClaim.RepairCompletionDate) If Common.MyDB.SqlConn_RM2.State <> System.Data.ConnectionState.Open Then Common.MyDB.SqlConn_RM2.Open() obj = sqlCommand.ExecuteScalar() Catch ex As Exception Dim debug As String = ex.ToString Finally Common.MyDB.SqlConn_RM2.Close() End Try myClaim.RepairCompletionDate is a SQLDateTime. Do i have to remove the quotes in the sqlString to compare Date columns? But then i dont get a exception but incorrect results.

    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

  • Oracle doesn't remove cursors after closing result set

    - by Vladimir
    Note: we reuse single connection. ************************************************ public Connection connection() {                try {            if ((connection == null) || (connection.isClosed()))            {               if (connection!=null) log.severe("Connection was closed !");                connection = DriverManager.getConnection(jdbcURL, username, password);            }        } catch (SQLException e) {            log.severe("can't connect: " + e.getMessage());        }        return connection;            } ************************************************** public IngisObject[] select(String query, String idColumnName, String[] columns) { Connection con = connection(); Vector<IngisObject> objects = new Vector<IngisObject>(); try {     Statement stmt = con.createStatement();     String sql = query;     ResultSet rs =stmt.executeQuery(sql);//oracle increases cursors count here     while(rs.next()) {        IngisObject o = new IngisObject("New Result");        o.setIdColumnName(idColumnName);                    o.setDatabase(this);        for(String column: columns) o.attrs().put(column, rs.getObject(column));        objects.add(o);        }     rs.close();// oracle don't decrease cursor count here, while it's expected     stmt.close();     } catch (SQLException ex) {     System.out.println(query);     ex.printStackTrace(); }

    Read the article

  • connecting to MySQL using JDBC in eclipse

    - by Noona
    Hello, So I want to create a JDBC connection to MySQL server that is installed on my pc, here are the steps, I installed MySQL with the username and password "root", downloaded mysql-connector-java and from theere I coped the JAR "mysql-connector-java-5.1.12-bin" to "C:\Sun\SDK\jdk\jre\lib\ext", I then added it as an external JAR in my project in eclipse, now in my class I have this code: public void initialiseDatabase() { try { // Load the Driver class. Class.forName("com.mysql.jdbc.Driver"); //Create the connection using the static getConnection method databaseConnection = DriverManager.getConnection (databaseUrl+databaseName, dbUserName, dbPassword); sqlStatement = databaseConnection.createStatement(); } catch (SQLException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();} } (this is going to be psuedocode cause I am reading from a properties file and don't want the one helping me reading through long lines of code from main to figure out all the variables), where databaseUrl = "127.0.0.1" dbUserName = "root" dbPassword = "root" databaseName = "MySQL" //this one I am not sure of, do I need to create it or is it set inherenrly? now the MySQL server is up and running, but when I call the method initialiseDatabase the following exception is thrown: "java.sql.SQLException: No suitable driver found for rootroot at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at Proxy$JDBCConnection.initialiseDatabase(Proxy.java:721)" when line 721 is: sqlStatement = databaseConnection.createStatement(); Where have I gone wrong? thanks

    Read the article

  • Deployment problems of asp.net 3.5 in iis 5.1

    - by peter
    i have microsoft.net 3.5 application and have IIS5.1,,for deploying website do i need to do any thing aother than this 1.In IIS i created virtual directory named SPA and i browsed in to the location where my project is lacated and i added entire project file there( Do i need to add only bin file and login page or i need to add all pages???) 2.In asp.net folder i selected tab version 2.0,, 3.when i browsed i can see all pages when i click login.aspx i am getting this error [SqlException (0x80131904): User does not have permission to perform this action.] System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +821651 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +186 System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1932 System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK) +33 System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject) +172 System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart) +381 System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance) +181 System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance) +173 System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection) +133 System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options) +30 System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject) +424 System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject) +66 System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject) +494 System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection) +82 System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) +105 System.Data.SqlClient.SqlConnection.Open() +111 ChatTool.LoginForm.Page_Load(Object sender, EventArgs e) in D:\Chat tool_Ameya\ProjectCode\Unisys Project Testing\Unisys Project\Login.aspx.cs:25 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436

    Read the article

  • Netbeans with Oracle connection java.lang.ClassNotFoundException

    - by Attilah
    I use NetBeans 6.5 . When I try to run the following code : package com.afrikbrain.numeroteur16; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author */ public class NumeroteurTest { public NumeroteurTest() { } public void doIt() throws ClassNotFoundException{ try { Class.forName("oracle.jdbc.OracleDriver"); Connection connection = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","user","pwd"); String newNUMERO = new Numeroteur16("MATCLI", connection).numeroter(); System.out.println("NUMERO GENERE : "+newNUMERO.toString()); } catch (SQLException ex) { Logger.getLogger(NumeroteurTest.class.getName()).log(Level.SEVERE, null, ex); ex.printStackTrace(); } catch (NumException ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); } } public static void main(String[] args){ try { new NumeroteurTest().doIt(); } catch (ClassNotFoundException ex) { Logger.getLogger(NumeroteurTest.class.getName()).log(Level.SEVERE, null, ex); System.out.println("Driver not found."); } } } when running it, I get this error : java.lang.ClassNotFoundException: oracle.jdbc.OracleDriver at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:307) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:252) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:169) at com.afrikbrain.numeroteur16.NumeroteurTest.doIt(NumeroteurTest.java:27) at com.afrikbrain.numeroteur16.NumeroteurTest.main(NumeroteurTest.java:45) Driver not found. how do I solve this problem ?

    Read the article

  • Requirements for connecting to Oracle with JDBC?

    - by Lord Torgamus
    I'm a newbie to Java-related web development, and I can't seem to get a simple program with JDBC working. I'm using off-the-shelf Oracle 10g XE and the Eclipse EE IDE. From the books and web pages I've checked so far, I've narrowed the problem down to either an incorrectly written database URL or a missing JAR file. I'm getting the following error: java.sql.SQLException: No suitable driver found for jdbc:oracle://127.0.0.1:8080 with the following code: import java.sql.*; public class DatabaseTestOne { public static void main(String[] args) { String url = "jdbc:oracle://127.0.0.1:8080"; String username = "HR"; String password = "samplepass"; String sql = "SELECT EMPLOYEE_ID FROM EMPLOYEES WHERE LAST_NAME='King'"; Connection connection; try { connection = DriverManager.getConnection(url, username, password); Statement statement = connection.createStatement(); System.out.println(statement.execute(sql)); connection.close(); } catch (SQLException e) { System.err.println(e); } } } What is the proper format for a database URL, anyways? They're mentioned a lot but I haven't been able to find a description. Thanks! EDIT (the answer): Based on duffymo's answer, I got ojdbc14.jar from http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/htdocs/jdbc_10201.html and dropped it in the Eclipse project's Referenced Libraries. Then I changed the start of the code to ... try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { System.err.println(e); } // jdbc:oracle:thin:@<hostname>:<port>:<sid> String url = "jdbc:oracle:thin:@GalacticAC:1521:xe"; ... and it worked.

    Read the article

  • MySQL Stored Procedures : Use a variable as the database name in a cursor declaration

    - by Justin
    I need to use a variable to indicate what database to query in the declaration of a cursor. Here is a short snippet of the code : CREATE PROCEDURE `update_cdrs_lnp_data`(IN dbName VARCHAR(25), OUT returnCode SMALLINT) cdr_records:BEGIN DECLARE cdr_record_cursor CURSOR FOR SELECT cdrs_id, called, calling FROM dbName.cdrs WHERE lrn_checked = 'N'; # Setup logging DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN #call log_debug('Got exception in update_cdrs_lnp_data'); SET returnCode = -1; END; As you can see, I'm TRYING to use the variable dbName to indicate in which database the query should occur within. However, MySQL will NOT allow that. I also tried things such as : CREATE PROCEDURE `update_cdrs_lnp_data`(IN dbName VARCHAR(25), OUT returnCode SMALLINT) cdr_records:BEGIN DECLARE cdr_record_cursor CURSOR FOR SET @query = CONCAT("SELECT cdrs_id, called, calling FROM " ,dbName, ".cdrs WHERE lrn_checked = 'N' "); PREPARE STMT FROM @query; EXECUTE STMT; # Setup logging DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN #call log_debug('Got exception in update_cdrs_lnp_data'); SET returnCode = -1; END; Of course this doesn't work either as MySQL only allows a standard SQL statement in the cursor declaration. Can anyone think of a way to use the same stored procedure in multiple databases by passing in the name of the db that should be affected?

    Read the article

  • How to make Spring load a JDBC Driver BEFORE initializing Hibernate's SessionFactory?

    - by Bill_BsB
    I'm developing a Spring(2.5.6)+Hibernate(3.2.6) web application to connect to a custom database. For that I have custom JDBC Driver and Hibernate Dialect. I know for sure that these custom classes work (hard coded stuff on my unit tests). The problem, I guess, is with the order on which things get loaded by Spring. Basically: Custom Database initializes Spring load beans from web.xml Spring loads ServletBeans(applicationContext.xml) Hibernate kicks in: shows version and all the properties correctly loaded. Hibernate's HbmBinder runs (maps all my classes) LocalSessionFactoryBean - Building new Hibernate SessionFactory DriverManagerConnectionProvider - using driver: MyCustomJDBCDriver at CustomDBURL I get a SQLException: No suitable driver found for CustomDBURL Hibernate loads the Custom Dialect My CustomJDBCDriver finally gets registered with DriverManager (log messages) SettingsFactory runs SchemaExport runs (hbm2ddl) I get a SQLException: No suitable driver found for CustomDBURL (again?!) Application get successfully deployed but there are no tables on my custom Database. Things that I tried so far: Different techniques for passing hibernate properties: embedded in the 'sessionFactory' bean, loaded from a hibernate.properties file. Nothing worked but I didn't try with hibernate.cfg.xml file neither with a dataSource bean yet. MyCustomJDBCDriver has a static initializer block that registers it self with the DriverManager. Tried different combinations of lazy initializing (lazy-init="true") of the Spring beans but nothing worked. My custom JDBC driver should be the first thing to be loaded - not sure if by Spring but...! Can anyone give me a solution for this or maybe a hint for what else I could try? I can provide more details (huge stack traces for instance) if that helps. Thanks in advance.

    Read the article

  • JDBC going to the wrong address

    - by DCSoft
    When I try and connect it my mysql database with JDBC in java, it doesn't go to my web server. Here is the code String dbtime; String dbUrl = "jdbc:mysql://184.172.176.18:3306/dcsoft_dcsoft_balloon"; String dbUser = "myuser"; String dcPass = "mypass"; String dbClass = "com.mysql.jdbc.Driver"; String query = "Select * FROM users"; try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(dbUrl, dbUser, dcPass); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { dbtime = rs.getString(1); System.out.println(dbtime); } //end while con.close(); } //end try catch(ClassNotFoundException e) { e.printStackTrace(); } catch(SQLException e) { e.printStackTrace(); } This code is supposed to go to my web server but it gives this error java.sql.SQLException: Access denied for user 'dcsoft_dcsoft_java'@'jamesposse.force9.co.uk' (using password: YES) jamesposse.force9.co.uk is the not the address im trying to connect to I'm trying to connect to 184.172.176.18:3306. Thanks.

    Read the article

  • Storing Result set into an array

    - by OVERTONE
    i know this should be simpel and im probably staring straight at the problem but once again im stuck and need the help of the code gurus. im trying too take one row from a column in jdbc, and put them in an array. i do this as follows: public void fillContactList() { createConnection(); try { Statement stmt = conn.createStatement(); ResultSet namesList = stmt.executeQuery("SELECT name FROM Users"); try { while (namesList.next()) { contactListNames[1] = namesList.getString(1); System.out.println("" + contactListNames[1]); } } catch(SQLException q) { } conn.commit(); stmt.close(); conn.close(); } catch(SQLException e) { } creatConnection is an already defined method that does what it obviously does. i creat my result set while theres another one, i store the string of that column into an array. then print it out for good measure. too make sure its there. the problem is that its storing the entire column into contactListNames[1] i wanted to make it store column1 row 1 into [1] then column 1 row 2 into [2] i know i could do this with a loop. but i dont know too take only one row at a time from a single column. any ideas? p.s ive read the api, i jsut cant see anything that fits.

    Read the article

  • Java doest run prepare statements with parameter

    - by Zaiman Noris
    If using PreparedStatement to query my table. Unfortunately, I have not been able to do so. My code is as simple as this :- PreparedStatement preparedStatement = connection.prepareStatement( "Select favoritefood from favoritefoods where catname = ?"); preparedStatement.setString(1, "Cappuccino"); ResultSet resultSet = preparedStatement.executeQuery(); Error thrown is java.sql.SQLException: ORA-00911: invalid character. As if it never run through the parameter given. Thanks for your time. I've spend a day to debug this yet still unsuccessful. As mention by Piyush, if I omit the semicolon at the end of statement, new error is thrown. java.sql.SQLException: ORA-00942: table or view does not exist. But I can assure you this table is indeed exist. UPDATE shoot. i edited the wrong sql. now it is successful. thx for your time.

    Read the article

  • Java program will read from database, but not write to it

    - by ck1221
    I have a Java program that successfully connects to a mysql database that is hosted on godaddy's server. I can read from that db with out issue, however, when I try to write to it with INSERT or UPDATE for example, the query does not execute. I am using the 'admin' account that I set up through godaddy, I realize this is not the root account. I have checked and verified that the connection is not read only, and have logged out of phpmyadmin while the query ran. I'm not sure what else I can try or if anyone has experienced this issue. Maybe a setting to the connection I have failed to set? Or maybe its not possible since the db is hosted on godaddy's servers? Any help is great! Thanks. Here is some relevant code: Connection to db: Connection con; public DBconnection(String url, String user, String pass) { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); con = DriverManager.getConnection (url,user,pass); if(!con.isClosed()) System.out.println("connecton open"); } catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();} } Send Query: public ResultSet executeQuery(String query) { ResultSet rs = null; try { Statement stmt = (Statement) con.createStatement(); rs = stmt.executeQuery(query); //while(rs.next()) //System.out.println(rs.getString("ticket_num")); } catch (SQLException e) {} return rs; } Insert Query (works in phpmyadmin): conn.executeQuery("INSERT INTO tickets VALUES(55555,'12/01/2012','me','reports','test','','','0','Nope')");

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >