Search Results

Search found 214 results on 9 pages for 'executequery'.

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

  • Simple select not working on JDBC MSSQL ?

    - by Xinus
    I am trying to move project which was using MySQL database to the one that uses MSSQL 2008, But the select that was working in mysql is no longer working in MSSQL PreparedStatement statement = connection .prepareStatement("select u.user_firstname,u.user_lastname from user_details u, login l where l.username=? and l.login_user = u.user_id"); statement.setString(1, userName); ResultSet resultSet = (ResultSet) statement.executeQuery(); It always gives me empty resultset even when there are values corresponding to that username, When I run query using MSSQL management studio - query works properly i.e. it gives non-zero rows, Are there any MSSQL specific change I need to do ?

    Read the article

  • java.sql.SQLException: Operation not allowed after ResultSet closed

    - by javatraniee
    Why am I getting an Resultset already closed error? public class Server implements Runnable { private static int port = 1600, maxConnections = 0; public static Connection connnew = null; public static Connection connnew1 = null; public static Statement stnew, stnew1, stnew2, stnew3, stnew4; public void getConnection() { try { Class.forName("org.gjt.mm.mysql.Driver"); connnew = DriverManager.getConnection("jdbc:mysql://localhost/db_alldata", "root", "flashkit"); connnew1 = DriverManager.getConnection("jdbc:mysql://localhost/db_main", "root", "flashkit"); stnew = connnew.createStatement(); stnew1 = connnew.createStatement(); stnew2 = connnew1.createStatement(); stnew3 = connnew1.createStatement(); stnew4 = connnew1.createStatement(); } catch (Exception e) { System.out.print("Get Connection Exception---" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "----- > " + e); } } public void closeConnection() { try { if (!(connnew.isClosed())) { stnew.close(); stnew1.close(); connnew.close(); } if (!(connnew1.isClosed())) { stnew2.close(); stnew3.close(); stnew4.close(); connnew1.close(); } } catch (Exception e) { System.out.print("Close Connection Closing Exception-----" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "------->" + e); } } Server() { try { } catch (Exception ee) { System.out.print("Server Exceptions in main connection--" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "------>" + ee); } } public static void main(String[] args) throws SQLException { int i = 0; Server STUD = new Server(); STUD.getConnection(); try { ServerSocket listener = new ServerSocket(port); Socket server; while ((i++ < maxConnections) || (maxConnections == 0)) { @SuppressWarnings("unused") doComms connection; server = listener.accept(); try { ResultSet checkconnection = stnew4 .executeQuery("select count(*) from t_studentdetails"); if (checkconnection.next()) { // DO NOTHING IF EXCEPTION THEN CLOSE ALL CONNECTIONS AND OPEN NEW // CONNECTIONS } } catch (Exception e) { System.out.print("Db Connection Lost Closing And Re-Opning It--------" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "--------" + e); STUD.closeConnection(); STUD.getConnection(); } doComms conn_c = new doComms(server, stnew, stnew1, stnew2, stnew3); Thread t = new Thread(conn_c); t.start(); } } catch (IOException ioe) { System.out.println("Main IOException on socket listen: " + ioe); } } public void run() { } } class doComms implements Runnable { private Socket server; private String input; static Connection conn = null; static Connection conn1 = null; static Statement st, st1, st2, st3; doComms(Socket server, Statement st, Statement st1, Statement st2, Statement st3) { this.server = server; doComms.st = st; doComms.st1 = st1; doComms.st2 = st2; doComms.st3 = st3; } @SuppressWarnings("deprecation") public void run() { input = ""; // char ch; try { DataInputStream in = new DataInputStream(server.getInputStream()); OutputStreamWriter outgoing = new OutputStreamWriter(server.getOutputStream()); while (!(null == (input = in.readLine()))) { savetodatabase(input, server.getPort(), outgoing); } } catch (IOException ioe) { System.out.println("RUN IOException on socket listen:-------" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "----- " + ioe); ioe.printStackTrace(); } } public void savetodatabase(String line, int port1, OutputStreamWriter outgoing) { try { String Rollno = "-", name = "-", div = "-", storeddate = "-", storedtime = "-", mailfrom = ""; String newline = line; String unitid = "-"; storeddate = new SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date()); storedtime = new SimpleDateFormat("HH:mm:ss").format(new java.util.Date()); String sql2 = "delete from t_currentport where PortNumber='" + port1 + "''"; st2.executeUpdate(sql2); sql2 = "insert into t_currentport (unitid, portnumber,thedate,thetime) values >('" + unitid + "','" + port1 + "','" + storeddate + "','" + storedtime + "')"; st2.executeUpdate(sql2); String tablename = GetTable(); String sql = "select * from t_studentdetails where Unitid='" + unitid + "'"; ResultSet rst = st2.executeQuery(sql); if (rst.next()) { Rollno = rst.getString("Rollno"); name = rst.getString("name"); div = rst.getString("div"); } String sql1 = "insert into studentInfo StoredDate,StoredTime,Subject,UnitId,Body,Status,Rollno,div,VehId,MailDate,MailTime,MailFrom,MailTo,Header,UnProcessedStamps) values('" + storeddate + "','" + storedtime + "','" + unitid + "','" + unitid + "','" + newline + "','Pending','" + Rollno + "','" + div + "','" + name + "','" + storeddate + "','" + storedtime + "','" + mailfrom + "','" + mailfrom + "','-','-')"; st1.executeUpdate(sql1); } catch (Exception e) { System.out.print("Save to db Connection Exception--" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "-->" + e); } } }

    Read the article

  • Tomcat, Hibernate and the java.io.EOFException

    - by Marco
    Hi, My Java application, which uses Hibernate and it's hosted by Tomcat 6.0, gets the following exception after a long time of inactivity when it tries to access the DB: com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: ** BEGIN NESTED EXCEPTION ** java.io.EOFException STACKTRACE: java.io.EOFException at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1963) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2375) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2874) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1623) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1715) at com.mysql.jdbc.Connection.execSQL(Connection.java:3249) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1268) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1403) at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208) at org.hibernate.loader.Loader.getResultSet(Loader.java:1812) at org.hibernate.loader.Loader.doQuery(Loader.java:697) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259) at org.hibernate.loader.Loader.doList(Loader.java:2232) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129) at org.hibernate.loader.Loader.list(Loader.java:2124) at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:401) at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:363) at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196) at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1149) at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102) Any tips? Thanks

    Read the article

  • ODP.NET Code Example Critque or best practices

    - by andrewWinn
    I currently have a DataAccess Layer in Vb.Net. I am not too happy with my implementation of both my ExecuteQuery (as DataSet) and ExecuteNonQuery functions. Does anyone have any code that I could see? My code just doesn't look clean. Any thoughts or critiques on it would be appreciated also. Using odpConn As OracleConnection = New OracleConnection(_myConnString) odpConn.Open() If _beginTransaction Then txn = odpConn.BeginTransaction(IsolationLevel.Serializable) End If Try Using odpCmd As OracleCommand = odpConn.CreateCommand() odpCmd.CommandType = CommandType.Text odpCmd.CommandText = sSql For i = 0 To parameters.Parameters.Count - 1 Dim prm As New OracleParameter prm = DirectCast(parameters.Parameters(i), ICloneable).Clone odpCmd.Parameters.Add(prm) Next If (odpConn.State = ConnectionState.Closed) Then odpConn.Open() End If iToReturn = odpCmd.ExecuteNonQuery() If _beginTransaction Then txn.Commit() End If End Using Catch txn.Rollback() End Try End Using

    Read the article

  • What's the cause of (and treatment for) this java MySQL exception?

    - by justkevin
    I'm getting the following exception when executing the first preparedstatement after a period of inactivity: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure The last packet successfully received from the server was 2,855,054 milliseconds ago. The last packet sent successfully to the server was 123 milliseconds ago. at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) at java.lang.reflect.Constructor.newInstance(Unknown Source) at com.mysql.jdbc.Util.handleNewInstance(Util.java:406) at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1074) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3052) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2938) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3481) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2109) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2648) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2077) at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2228) This only shows up if my application hasn't communicated with MySQL recently. Subsequent queries execute normally. I suspect it's some kind of timeout issue, but the periods of inactivity are way below the 8 hour timeout for MySQL. Any suggestions?

    Read the article

  • Input array is longer than the number of columns in this table

    - by Adam
    I've recently started to use SQLite and began to integrate it into a C# project I'm working on. However, randomly my project will throw the exception: Input array is longer than the number of columns in this table I'm having a hard time trying the trace the problem because it seems to be thrown on a random basis. DataTable table = new DataTable(); //exception is thrown here table = Global.db.ExecuteQuery("SELECT * FROM vm_manager"); Some of the data that gets returned from this query is as follows: http://i.imgur.com/9rlLN.png If anyone has any advice, I'd be grateful. EDIT: I'm unable to show the execute query function as it resides inside a dll from the following sql lite wrapper http://www.codeproject.com/KB/database/cs_sqlitewrapper.aspx

    Read the article

  • Converting "is null" into a linq to sql statement

    - by Darryl Braaten
    I am having trouble replicating the following sql as a LINQ statement select TableA.* from TableA left outer join TableAinTableB on TableA.Id = TableAId where TableBId is null The following returns no lines from TableA in db.TableA join AinB in db.TableAinTableB on TableA.Id equals TableAId where AinB.TableBId == null select TableA Also tried and a few other things that didn't work. from TableA in db.TableA join AinB in db.TableAinTableB on TableA.Id equals TableAId where AinB == null select TableA TableAinTableB is a many to many table. The query I want will pull all the records from TableA that have no records in the middle table. My sql does what I want but I have no idea how to convert it to LINQ to SQL. I ended up working around it by just doing a db.ExecuteQuery("working sql"); But I would like to know if the query is possible in LINQ and how to write it, or a pointer to a document that covers this scenario. My searching did not uncover anything I found useful.

    Read the article

  • How to query a date in HQL (Hibernate) with Joda Time?

    - by fabien7474
    I am sure that someone familiar with HQL (I am myself a newbie) can easily answer this question. In my Grails application, I have the following domain class. class Book { org.joda.time.DateTime releaseDate //I use the PersistentDateTime for persisting via Hibernate (that use a DATETIME type for MySQL DB) } In my HQL query, I want to retrieve books whose release date is included in range date1..date2 For instance I tried: DateTime date1, date2 ... def queryStr = "select * from Book as b where b.releaseDate > $date1 and b.releaseDate < $date2" def res = Book.executeQuery(queryStr) But I got the exception ...caused by: org.springframework.orm.hibernate3.HibernateQueryException: unexpected token: The error token points to date format (for instance 2009-11-27T21:57:18.010+01:00 or Fri Nov 27 22:01:20 CET 2009) I have also tried to convert date1 into a Date class without success So what is the correct HQL code ? Should I convert to a specific format (which one?) using the patternForStyle method or is there another -cleaner- way to do it? Thanks, Fabien.

    Read the article

  • Safe HttpContext.Current.Cache Usage

    - by Burak SARICA
    Hello there, I use Cache in a web service method like this : var pblDataList = (List<blabla>)HttpContext.Current.Cache.Get("pblDataList"); if (pblDataList == null) { var PBLData = dc.ExecuteQuery<blabla>( @"SELECT blabla"); pblDataList = PBLData.ToList(); HttpContext.Current.Cache.Add("pblDataList", pblDataList, null, DateTime.Now.Add(new TimeSpan(0, 0, 15)), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); } I wonder is it thread safe? I mean the method is called by multiple requesters And more then one requester may hit the second line at the same time while the cache is empty. So all of these requesters will retrieve the data and add to cache. The query takes 5-8 seconds. May a surrounding lock statement around this code prevent that action? (I know multiple queries will not cause error but i want to be sure running just one query.)

    Read the article

  • How do I get output into Java from a SELECT stored procedure in Oracle?

    - by Ventrue
    I'm using Java to connect to an Oracle 10 Database. I want to create a stored procedure (don't ask why) that takes no arguments and returns a lot of rows. Specifically, in Java I want to be able to get this data with something like: ResultSet rs = stmt.executeQuery("call getChildless"); where getChildless is the query: SELECT objectid FROM Object WHERE objectid NOT IN (SELECT parent FROM subparts); However, I just cannot for the life of me figure out how to get my output from the stored procedure. I've googled it and I get all this sample code that Oracle won't compile, presumably it's for a previous version. Refcursors seem to come up a lot, but I'm not sure if that's what I actually want, to use it with a ResultSet.

    Read the article

  • ResultSet Already closed error

    - by javatraniee
    why am i getting an error of resultset already closed error public class Server implements Runnable { private static int port=1600, maxConnections=0; public static Connection connnew=null; public static Connection connnew1=null; public static Statement stnew,stnew1,stnew2,stnew3,stnew4; public void getConnection() { try{ Class.forName("org.gjt.mm.mysql.Driver"); connnew= DriverManager.getConnection("jdbc:mysql://localhost/db_alldata","root","flashkit"); connnew1= DriverManager.getConnection("jdbc:mysql://localhost/db_main","root","flashkit"); stnew=connnew.createStatement(); stnew1=connnew.createStatement(); stnew2=connnew1.createStatement(); stnew3=connnew1.createStatement(); stnew4=connnew1.createStatement(); }catch (Exception e) { System.out.print("Get Connection Exception---"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"----- "+e); } } public void closeConnection() { try{ if(!(connnew.isClosed())) { stnew.close(); stnew1.close(); connnew.close(); } if(!(connnew1.isClosed())) { stnew2.close(); stnew3.close(); stnew4.close(); connnew1.close(); } }catch (Exception e) { System.out.print("Close Connection Closing Exception-----"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"-------"+e); } } Server() { try{ }catch(Exception ee) { System.out.print("Server Exceptions in main connection--"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"------"+ee); } } public static void main(String[] args) throws SQLException { int i=0; Server STUD= new Server(); STUD.getConnection(); try { ServerSocket listener = new ServerSocket(port); Socket server; while((i++ < maxConnections) || (maxConnections == 0)) { @SuppressWarnings("unused") doComms connection; server = listener.accept(); try{ ResultSet checkconnection=stnew4.executeQuery("select count(*) from t_studentdetails"); if(checkconnection.next()) { //DO NOTHING IF EXCEPTION THEN CLOSE ALL CONNECTIONS AND OPEN NEW CONNECTIONS } }catch (Exception e) { System.out.print("Db Connection Lost Closing And Re-Opning It--------"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"--------"+e); STUD.closeConnection(); STUD.getConnection(); } doComms conn_c= new doComms(server,stnew,stnew1,stnew2,stnew3); Thread t = new Thread(conn_c); t.start(); } }catch (IOException ioe) { System.out.println("Main IOException on socket listen: " + ioe); } } public void run() { } } class doComms implements Runnable { private Socket server; private String input; static Connection conn=null; static Connection conn1=null; static Statement st,st1,st2,st3; doComms(Socket server, Statement st,Statement st1,Statement st2,Statement st3 ) { this.server=server; doComms.st=st; doComms.st1=st1; doComms.st2=st2; doComms.st3=st3; } @SuppressWarnings("deprecation") public void run () { input=""; //char ch; try { DataInputStream in = new DataInputStream (server.getInputStream()); OutputStreamWriter outgoing=new OutputStreamWriter(server.getOutputStream()); while(!(null==(input=in.readLine()))) { savetodatabase(input,server.getPort(),outgoing); } //server.close(); } catch (IOException ioe) { System.out.println("RUN IOException on socket listen:-------"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"----- " + ioe); ioe.printStackTrace(); } } public void savetodatabase(String line, int port1, OutputStreamWriter outgoing) { try { String Rollno="-",name="-",div="-",storeddate="-",storedtime="-",mailfrom=""; String newline=line; String unitid="-"; storeddate=new SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date()); storedtime=new SimpleDateFormat("HH:mm:ss").format(new java.util.Date()); String sql2="delete from t_currentport where PortNumber='"+port1+"''"; st2.executeUpdate(sql2); sql2="insert into t_currentport (unitid, portnumber,thedate,thetime) values ('"+unitid+"','"+port1+"','"+storeddate+"','"+storedtime+"')"; st2.executeUpdate(sql2); String tablename=GetTable(); String sql="select * from t_studentdetails where Unitid='"+unitid+"'"; ResultSet rst=st2.executeQuery(sql); if(rst.next()) { Rollno=rst.getString("Rollno"); name=rst.getString("name"); div=rst.getString("div"); } String sql1="insert into studentInfo StoredDate,StoredTime,Subject,UnitId,Body,Status,Rollno,div,VehId,MailDate,MailTime,MailFrom,MailTo,Header,UnProcessedStamps) values('"+storeddate+"','"+storedtime+"','"+unitid+"','"+unitid+"','"+newline+"','Pending','"+Rollno+"','"+div+"','"+name+"','"+storeddate+"','"+storedtime+"','"+mailfrom+"','"+mailfrom+"','-','-')"; st1.executeUpdate(sql1); }catch(Exception e) { System.out.print("Save to db Connection Exception--"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"-->"+e); } } }

    Read the article

  • Speed up multiple JDBC SQL querys?

    - by paddydub
    I'm working on a shortest path a* algorithm in java with a mysql db. I'm executing the following SQL Query approx 300 times in the program to find route connections from a database of 10,000 bus connections. It takes approx 6-7 seconds to execute the query 300 times. Any suggestions on how I can speed this up or any ideas on a different method i can use ? Thanks ResultSet rs = stmt.executeQuery("select * from connections" + " where Connections.From_Station_stopID ="+StopID+";"); while (rs.next()) { int id = rs.getInt("To_Station_id"); String routeID = rs.getString("To_Station_routeID"); Double lat = rs.getDouble("To_Station_lat"); Double lng = rs.getDouble("To_Station_lng"); int time = rs.getInt("Time"); }

    Read the article

  • Problem with sqlite query when using the wrapper

    - by user285096
    - (IBAction)EnterButtonPressed:(id)sender { Sqlite *sqlite = [[Sqlite alloc] init]; NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"test.sqlite"]; if (![sqlite open:writableDBPath]) return; NSArray *query = [sqlite executeQuery:@"SELECT AccessCode FROM UserAccess"]; NSLog(@"%@",query); I am getting the output as : { ( AccessCode=abcd; ) } Where as in I want it as : abcd I am using the wrapper from : http://th30z.netsons.org/2008/11/objective-c-sqlite-wrapper/ Please help .

    Read the article

  • How do you access the value of an SQL count () query in a Java program

    - by Ankur
    I want to get to the value I am finding using the COUNT command of SQL. Normally I enter the column name I want to access into the getInt() getString() method, what do I do in this case when there is no specific column name. I have used 'AS' in the same manner as is used to alias a table, I am not sure if this is going to work, I would think not. Statement stmt3 = con.createStatement(); ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) FROM "+lastTempTable+") AS count"); while(rs3.next()){ count = rs3.getInt("count"); }

    Read the article

  • C# - Inserting multiple rows using a stored procedure

    - by user177883
    I have a list of objects, this list contains about 4 million objects. there is a stored proc that takes objects attributes as params , make some lookups and insert them into tables. what s the most efficient way to insert this 4 million objects to db? How i do : -- connect to sql - SQLConnection ... foreach(var item in listofobjects) { SQLCommand sc = ... // assign params sc.ExecuteQuery(); } THis has been really slow. is there a better way to do this?

    Read the article

  • How to get result size from an SQL query and check size

    - by Jimmy
    Hi I'm trying to write a piece of code for a simple verification method as part of a MVC. At present the SQL is not written as a prepared statement so obviously it is at risk to a SQL injection so any help in regards to writing the SQL as a prepared statement would be really helpful. The method which is in the User model. public boolean getLoginInfo() { try { DBAccess dbAccess = new DBAccess(); String sql = "SELECT username, password FROM owner WHERE username = '" + this.username + "'AND password = '" + this.password + "';"; dbAccess.close();dbAccess.executeQuery(sql); dbAccess.close(); return true; } catch (Exception e) { return false; } } I want to get the size of the result set which is generated by the SQL query and if the size of it is 1 return true else it's false. If you need more info on the rest of the MVC just post and I'll get it up here.

    Read the article

  • how to show image from ms access to jpanel in java netbeans

    - by Shiv
    I have used this code : private void okActionPerformed(java.awt.event.ActionEvent evt) { try { String Update = name.getText(); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection connection = DriverManager.getConnection("jdbc:odbc:NewPData"); PreparedStatement psmnt = connection.prepareStatement("SELECT Image FROM Table1 where Name='" + Update + "'"); ResultSet rs = psmnt.executeQuery(); Blob blob = rs.getBlob("Image"); int b; InputStream bis = rs.getBinaryStream("Image"); FileOutputStream f = new FileOutputStream("Image.jpg"); while ((b = bis.read()) >= 0) { f.write(b); } f.close(); bis.close(); icon = new ImageIcon(blob.getBytes(1L, (int) blob.length())); lblImage.setIcon(icon); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } Exception it show is java.lang.UnsupportedOperationException i have stored image first in ms access and now i want to show it on a label plz help

    Read the article

  • java.lang.OutOfMemoryError: Java heap space

    - by houlahan
    i get this error when calling a mysql Prepared Statement every 30 seconds this is the code which is been called: public static int getUserConnectedatId(Connection conn, int i) throws SQLException { pstmt = conn.prepareStatement("SELECT UserId from connection where ConnectionId ='" + i + "'"); ResultSet rs = pstmt.executeQuery(); int id = -1; if (rs.next()) { id = rs.getInt(1); } pstmt = null; rs = null; return id; } not sure what the problem is :s thanks in advanced.

    Read the article

  • 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

  • How to make DropDownList automatically be selected based on the Label.Text

    - by Archana B.R
    I have a DropDownlist in the GridView, which should be visible only when edit is clicked. I have bound the DropDownList from code behind. When I click on Edit, the label value of that cell should automatically get selected in the DropDownList. The code I have tried is: protected void GridView3_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { SqlCommand cmd = new SqlCommand("SELECT Location_Name FROM Location_Table"); DropDownList bind_drop = (e.Row.FindControl("DropList") as DropDownList); bind_drop.DataSource = this.ExecuteQuery(cmd, "SELECT"); bind_drop.DataTextField = "Location_Name"; bind_drop.DataValueField = "Location_Name"; bind_drop.DataBind(); string Loc_type = (e.Row.FindControl("id2") as Label).Text.Trim(); bind_drop.Items.FindByValue(Loc_type).Selected = true; } } When I run the code, it gives an exception error Object reference not set in the last line of the above code. Cannot find out whats wrong. Kindly help

    Read the article

  • PreparedStatement throws MySQLSyntaxErrorException

    - by sqlBugs
    I have the following Java code: String query = "Select 1 from myTable where name = ? and age = ?"; PreparedStatement stmt = conn.prepareStatement(query); stmt.setString(1, name); stmt.setInt(2, age); ResultSet rs = stmt.executeQuery(); Whenever I run the above code, it throws an exception on line 2 (where the PreparedStatement is declared): Error 0221202: SQLException = com.mysql.jdbc.exceptions.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 '? AND age = ?' at line 1 Does anyone have any suggestions about what I am doing wrong? Thanks!

    Read the article

  • Trouble Passing Parameter to LinqToSql Stored Procedure

    - by Webjedi
    public IEnumerable<T> ExecuteStoredProcedure<T>(params object[] parameters) { Type genericType = typeof(T); string commandthing = genericType.Name.Replace("Result", ""); //_db is my Linq To Sql database return _db.ExecuteQuery<T>(commandthing, parameters).AsEnumerable(); } The stored procedure is named GetOrder and has a single int parameter of orderid. I'm calling the above like so: SqlParameter parm1 = new SqlParameter("@orderid", SqlDbType.Int); parm1.Value = 123; var results = _session.ExecuteStoredProcedure<GetOrderResult>(parm1).Single(); I'm receiving the following error: A query parameter cannot be of type 'System.Data.SqlClient.SqlParameter' Thoughts? Or am I just missing something obvious?

    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

  • INSERT SQL in Java

    - by Pierre
    Hello. I have a Java application and I want to use SQL database. I have a class for my connection : public class SQLConnection{ private static String url = "jdbc:postgresql://localhost:5432/table"; private static String user = "postgres"; private static String passwd = "toto"; private static Connection connect; public static Connection getInstance(){ if(connect == null){ try { connect = DriverManager.getConnection(url, user, passwd); } catch (SQLException e) { JOptionPane.showMessageDialog(null, e.getMessage(), "Connection Error", JOptionPane.ERROR_MESSAGE); } } return connect; } } And now, in another class I succeeded to print my values but when I attempt to insert a value nothing is happening ... Here's my code : try { Statement state = SQLConnection.getInstance().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY); Statement state2 = SQLConnection.getInstance().createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); state2.executeUpdate("INSERT INTO table(field1) VALUES (\"Value\")"); // Here's my problem ResultSet res = state.executeQuery("SELECT * FROM plateau");

    Read the article

  • response.sendRedirect not working

    - by Amar
    response.sendRedirect method is not working in my program. String id="java"; try { query = "select Id from Users where Id= ?"; ps =Database.getConnection().prepareStatement(query); ps.setString(1, id); rs = ps.executeQuery(); if(rs.next()){ out.println(rs.getString(1)); }else { //out.println("wrong user"); response.sendRedirect("www.google.com"); } rs.close(); }catch(Exception e){ //e.printStackTrace(); System.out.print(e); } form the above i commented "out.println("wrong user");". when i remove this comment it works. but no redirect to the google page. Any answers?

    Read the article

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