FAQ Database Discussion Community


Storing timestamp in PostgreSQL gives an error: “cannot cast type bigint to timestamp without time zone”

postgresql,jdbc
I've created my table with the following code: CREATE TABLE "STORES" ( "STOREGLOBALID" SERIAL NOT NULL , "STOREUPDATEDATETIME" TIMESTAMP NOT NULL, "CHAINID" BIGINT , "CHAINNAME" VARCHAR(50) , "SUBCHAINID" SMALLINT , "SUBCHAINNAME" VARCHAR(50) , "STOREID" SMALLINT , "STORENAME" VARCHAR(50) , "STORETYPE" SMALLINT , "ADDRESS" VARCHAR(50) , "CITY" VARCHAR(50) , PRIMARY KEY...

Connecting to database using Spring JDBC

java,spring,jdbc
I am trying to connect to my database using Spring JDBC Beans.xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="org.postgresql.Driver" /> <property name="url"...

Why isn't this Python JDBC connection working?

python,jdbc
I'm trying to connect to a sybase type DB via the jaydebeapi, but I'm running into problems. I'm getting a strange error when I try to connect and I can't figure out why... Here is the code: import jaydebeapi conn = jaydebeapi.connect('net.sourceforge.jtds.jdbc.Driver', ['jdbc:jtds:sybase://hostname:port/database','username','password'],['/home/homedirectory/jtds-1.2.5-dist/jtds-1.2.5.jar']) Here is the error produced: Traceback (most...

What happens if you close a closed connection?

java,jdbc,database-connection
I was reading my database access logic, and found that it was possible for the same connection to be closed twice in a row. Other than being a duplicate instruction, is there any reason I should be concerned about closing a connection after it's already been closed? ...

JDBC connect to host but not in database

java,sql,jdbc
I am creating an application where you can manage an mySql database, at first i want the user to connect to the host by suppling the hostname, username and password. here is my code: try { Class.forName(ServerConnect.JDBC_DRIVER); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block System.out.println("Cannot register JDBC...

Get the last record even when the table contains one record

java,mysql,jdbc
I am trying to get the last record in my table with prepared statement. I have tried both quieries below but I am facing problem to get it when the table just contains one record in it. I am getting result when I execute the query alone but when I...

Slick query for one to optional one (zero or one) relationship

sql,jdbc,slick
Given tables of: case class Person(id: Int, name: String) case class Dead(personId: Int) and populated with: Person(1, "George") Person(2, "Barack") Dead(1) is it possible to have a single query that would produce a list of (Person, Option[Dead]) like so? (Person(1, "George"), Some(Dead(1))) (Person(2, "Barack"), None) ...

JDBC closing a database connection

java,sql,jdbc,hsqldb
I'm not sure how to close the database through this method of database connection, it's opens and connects successfully, I don't know if it closes when I close the GUI it's coded to import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import javax.swing.JOptionPane; public class Database_link { Connection connect = null; Statement...

Connecting fo MySql from JDBC in java

java,mysql,jdbc
I have a program written in java. This program when run from dos prompt raises driver class not found import java.sql.*; public class SimpleDb { public static void main(String[] args)throws SQLException,ClassNotFoundException { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.get connection("jdbc:mysql://host/db"); Statement sta = con.create statement(); ResultSet rs = sta.executeQuery(query); con.close(); } }...

JDBC - PostgreSQL - batch insert + unique index

java,sql,database,postgresql,jdbc
I have a table with unique constraint on some field. I need to insert a large number of records in this table. To make it faster I'm using batch update with JDBC (driver version is 8.3-603). Is there a way to do the following: every batch execute I need to...

jdbc backed channel on a cluster mode

jdbc,cluster-computing,spring-integration
I want to use the jdbc backed message channel. Reading the doc says that it is supported but after that I found a thread in the forum that explicitly says don't. Could you please clarify me if it's supported? In this case, could you guide me to do so? thanks...

Insert into table using join to resolve a single element

java,sql-server,jdbc
I'm trying to insert into a table while avoiding a secondary query to lookup an id of a product which is contained in another table. My insert query: INSERT INTO prod_addfeatures (ProductID, ProdFeature, ProdFeatureTitle) VALUES (?, ?, ?); ProductID is a Long Integer, the other two are simple strings. At...

How to determine which type of sql query is entered by user in java

java,mysql,jdbc
I was working on simple project which takes sql query from user and displays the results in JTable I want to determine if select statement was entered or any other DML/DDL statement was entered so I can call executeQuery() or executeUpdate() accordingly. I thought of checking the query if it...

How to use a path relative to project root to H2 db-file configuration with Play Framework 2.4?

jdbc,h2,relative-path,persistent,playframework-2.4
We're developing a Play 2.4 application (Java API). For dev purposes, we'd like to use a persistent H2 database with DB file path relative to the project root directory. In How to use a persistent H2 database in the Play Framework instead of in-memory there was solution for Play 2.0:...

How to share an Access database to different pc's for a Java desktop application?

java,database,ms-access,jdbc,jdbc-odbc
I am creating a desktop application in JAVA (RCP plugin) and I am using MS Access as database for my application. I kept database file on some shared location but whenever I try to open it from different machine it throws exception saying database is already locked by someone else....

can anyone provide maven repository for XMLType xdb.jar and xmlparserv2.jar

java,oracle,jdbc,xmltype
i want to insert oracle XMLType into database through JDBC. i saw in some websites that we need xdb.jar and xmlparserv2.jar for this. can anyone provide the maven repositories and dependencies for these? thanks in advance!! plz reply fast.. its urgent...

Insert a new record inside the Java class [duplicate]

java,mysql,jdbc,sql-insert
This question already has an answer here: What is a Null Pointer Exception, and how do I fix it? 12 answers I have this method in my Java class, to insert a new record to my DB (a date and thee booleans values). private void setTodayInfo(HttpSession session, String date){...

java.sql.SQLException: Invalid cursor position

java,sql,jdbc,derby
I created a simple application which lets users purchase Tickets. However, I have run into this error whenever I try to purchase "n" number of tickets. Now, I know that you need the crs.next() statement while operating with databases, I have used it a number of times but for some...

Where should ? be placed in a PreparedStatement? [duplicate]

java,mysql,sql,jdbc,prepared-statement
This question already has an answer here: Having a Column name as Input Parameter of a PreparedStatement 1 answer I am using PreparedStatement to select records from a table: public static String getMemberInfo(String columnName, Integer memberId) { String memberInfo = ""; String sql = "SELECT ? FROM member WHERE...

@Resource datasource breaking DB connection

java,jpa,jdbc,jboss,wildfly
I recently wrote a class, in my web application, for parsing a huge XML file and feed a db table with its content. My application is running on Wildfly9, and uses JPA with Hibernate provider to handle a MySQL DB. The AS configuration is pretty standard, I just added my...

Retreiving image in a jtable

java,swing,jdbc,jtable
I use the following code to retrieve data and images from 2 different tables: try { Class.forName(classforname); Connection con = DriverManager.getConnection(Connectionurl, username, password); String sql = "Select * from teacherdata where teachername='" + tf1.getText() + "'"; PreparedStatement ps = con.prepareStatement(sql); ResultSet rs = ps.executeQuery(sql); rs.next(); String thename = rs.getString("teachername"); String...

How to get sequence.nextval from SQL in JDBC?

mysql,jdbc
I have 5 tables where I use the same sequence's next value. The problem is, the subsequent tables gets a bigger value than the previous ones. My code is like this: String sql = "INSERT INTO table1(id, name) VALUES (id_seq.nextval, ?)"; ps.setString(1, "bar"); ps.executeUpdate(); sql = "INSERT INTO table2(id, name)...

How to make available Oracle 11g database on one PC to another PC

java,jdbc,oracle11g
I have created a Java Eclipse app with database tables from Oracle 11g. It works fine but only in my local pc. How can I make these tables work into another pc? Maybe I have to put them in the application folder? The app is connected with the db via...

SSH Connection to MySQL

java,mysql,jdbc,ssh
I have hit an issue and I am unsure as to where it is going wrong. I am establishing an SSH connection to my remote server and from there I am trying to access a MySQL Database. The SSH connection connects properly however, when attempting to access the MySQL db...

Connecting from Spark/pyspark to PostgreSQL

postgresql,jdbc,jar,apache-spark,pyspark
I've installed Spark on a Windows machine and want to use it via Spyder. After some troubleshooting the basics seems to work: import os os.environ["SPARK_HOME"] = "D:\Analytics\Spark\spark-1.4.0-bin-hadoop2.6" from pyspark import SparkContext, SparkConf from pyspark.sql import SQLContext spark_config = SparkConf().setMaster("local[8]") sc = SparkContext(conf=spark_config) sqlContext = SQLContext(sc) textFile = sc.textFile("D:\\Analytics\\Spark\\spark-1.4.0-bin-hadoop2.6\\README.md") textFile.count() textFile.filter(lambda...

error : “java.sql.SQLException: No value specified for parameter 1 ”

java,jdbc
public class VerEstoque extends JFrame { Connection conexao; PreparedStatement pst; ResultSet rs; public void Adicionar() { String sql = "INSERT INTO Produtos (Nome, Marca, Loja, Estoque ,ValordeVenda) VALUES (?,?,?,?,?)"; try { pst = conexao.prepareStatement(sql); pst.setString(1,textNome.getText()); pst.setString(2,textMarca.getText()); pst.setString(3,textLoja.getText()); pst.setString(4,textEstoque.getText()); pst.setString(5,textValordeVenda.getText()); pst.execute(); JOptionPane.showMessageDialog(null,"Produto adicionado com...

What is the preferred method of ensuring that database objects are closed?

java,jdbc
I'm curious about best practices when it comes to database interaction. I've been using a pattern that I believe handles making sure all of the appropriate objects are closed when I'm done with them. However, a coworker recently refactored my code with a comment along the lines of, "making sure...

Embedding an H2 Database within the WEB-INF Directory

jdbc,h2,web-inf
I have an embedded H2 Database I'd like to put in the WEB-INF directory of a web application. What is the proper way to refer to this in a JDBC url? Ideally I'd like a solution that would work both for a WAR, and an expanded WAR (If possible). Thank-you...

How to configure JDBC Connection Pool in Tomcat 5.5 for Oracle R12?

jdbc,connection-pooling,tomcat5.5
My Database is an Oracle R12 instance i.e 11g. The Tutorial for configuring the JDBC Connection pool shows examples up to Oracle 10g only. Link Here How do I configure a JDBC connection pool for Oracle R12 in a Tomcat 5.5 instance ? More info:: My Machine is HP-UX PA-RISC...

Java JDBC-ODBC cannot load driver for Excel

java,excel,jdbc,odbc
import java.sql.Connection; import java.sql.DriverManager; public class ConnectionExample { public static void main(String args[]) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (Exception e) { System.out.println("JDBC-ODBC driver failed to load."); return; } try { Connection con = DriverManager.getConnection("jdbc:odbc:abcdefg", "", ""); con.close(); } catch (Exception e) { System.out.println(e); } } } This code always...

How to use CachedRowSet in Google App Engine?

java,google-app-engine,jdbc,resultset,google-cloud-endpoints
I am using Google App Engine (Endpoints) to generate a simple API service. I'm currently trying to make my queries to the database faster and more efficient, so I decided to double check where I was calling ResultSet and Connections and closing them. However I want to use CachedRowSet and...

Drools Stateful Knowledge Session using persistence

java,jpa,jdbc,drools,jbpm
I am creating a Drools stateful session as described in the JBPM persistence documentation: http://docs.jboss.org/jbpm/v5.1/javadocs/org/drools/persistence/jpa/JPAKnowledgeService.html However, I came across the following exception javax.persistence.TransactionRequiredException: joinTransaction has been called on a resource-local EntityManager which is unable to register for a JTA transaction. My code is : EntityManagerFactory emf = Persistence.createEntityManagerFactory("metadata.model"); Environment env...

Unknown column 'ROWNUM' in 'where clause'

java,mysql,jdbc
I read a lot of topics about this problem but most of them were having problem with some complex (at least for me) code; I have followed the oracle ROWNUM Pseudocolumn guide but when I write SELECT * FROM " + tableName + " WHERE ROWNUM < 12; I get...

Why have I diffrent timezone offset result in Oracle DB and in Java?

java,oracle,jdbc,timezone,offset
I have the following code to compare timezone offset of 'Asia/Novosibirsk' timezone in Oracle Database 11g (11.2.0.4.0) and in Java: import oracle.jdbc.pool.OracleDataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; public class TZTest { public static void main(String[] args) { try {...

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver [Eclipse, Tomcat]

java,mysql,eclipse,tomcat,jdbc
I know that's an over-asked question, but still I can't get this thing right. I'm running a web application on Eclipse who has to interact with a mysql database. It all runs on a tomcat 7.0.27 server on localhost. As much as I try to add my my mysql-connector-java-5.1.21-bin.jar to...

No suitable driver found for JDBC SQL server

java,sql-server,jdbc
I am building a GWT program that on the server side connects to a database named TheDatabase. I tested my code by running it in a Java project, and it worked beautifully. However, when I try running it as part of the GWT project, I get this error: java.sql.SQLException: No...

JDBC performance when connection is stablished [closed]

java,database,performance,jdbc,database-connection
I want to reduce the time of part of project that currently takes 2 hrs. How it has been coded is it goes and take out almost 700,000 UID from one table and pass it to 16 different threads. Each thread then connect to JDBC and fetch a row for...

Find tables in oracle that dont have composite primary key using DatabaseMetaData Java

java,oracle,jdbc
String [] tableTypes = { "TABLE" }; DatabaseMetaData md = (DatabaseMetaData) dbConnection.getMetaData(); ResultSet rs = md.getTables(null, null, "%", tableTypes); while (rs.next()) { System.out.println(rs.getString(3)); } Im using this part of the code to get all tables from my local oracle database but I need to change it in order to get...

DateUtils cannot be resolved

java,jdbc
I am trying to change the time of the server before executing the preparedStatement. The server time is EDT and I want to add 6 hours to it before using it in the preparedStatement. Currently I am getting this error: DateUtils cannot be resolved. How can I fix it? I...

Java DatabaseMetaData.getSchemas() returns empty ResultSet, expected non-empty ResultSet

java,mysql,jdbc,database-metadata
Trying to understand what is going on here. DatabaseMetaData is returning an empty result set, where as an SQL query that is effectively the same does not. Not a major issue as I am using the second code example as a work around. DatabaseMetaData dmd = this.connection.getMetaData(); ResultSet rs =...

Insert values from arraylist into database

java,jdbc,arraylist
I use addbatch() and executebatch() to insert values from ArrayList into database. But when I run the code this error message appeared: Exception in thread "main" java.sql.BatchUpdateException: Duplicate entry '5' for key 'PRIMARY' at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2020) at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1451) This is the data: 1 A R1 7 A R1 2 B R1...

Connecting to MS SQL database with Java JDBC

java,sql-server,jdbc
I have been working on this for quite a while and can't seem to get anything to work. Any time I try to connect to the database I get the following error if I don't try to reference a driver: Exception in thread "main" java.sql.SQLException: No suitable driver found for...

postgresql:Can't use query methods that take a query string on a prepared statement [closed]

java,postgresql,jdbc
I am trying to create a java application that inserts into postgresqldatabase. This is my code import java .sql.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.util.*; public class insert { public static void main(String args[]) { try { Class.forName("org.postgresql.Driver"); Connection c = DriverManager .getConnection("jdbc:postgresql://localhost:5432/testdb", "postgres", "saurabh"); c.setAutoCommit(false); System.out.println("Opened database...

Squirrel Setup to connect to Phoenix - HBASE: Error java.util.concurrent.ExecutionException: java.lang.RuntimeException: java.lang.NoSuchMethodError:

jdbc,hbase,phoenix,squirrel
I am a newbie to Hbase & phoenix. I am trying to connect to HBASE via Phoenix JDBC Driver using Squirrel Client. Somehow I seem to get a strange error where the runtime complains of a NoSuchMethod Exception. I have included the relevant client jar phoenix-4.4.0-HBase-1.0-client in the lib folder...

erroneous with SQLite3 query in Java

java,hibernate,jdbc,sqlite3
I am parsing data out of a metrolink database. When I query the db from the command line I get the following out put : Stop Name Latitude Longitude ---------------------------------------- --------------- CLAYTON METROLINK STATION 38.645657 -90.339223 SUNNEN METROLINK STATION 38.607509 -90.330296 MAPLEWOOD METROLINK STATION 38.614023 -90.331314 BRENTWOOD METROLINK STATION 38.627851...

Insert date and get it in wrong format

java,sqlite,datetime,jdbc
I insert the current date in a table. I have a method to get the current datet: private static java.sql.Date getCurrentDate() { java.util.Date today = new java.util.Date(); return new java.sql.Date(today.getTime()); } Or in some cases I get the date from a from in a String format e.g. 2016-10-12 and then...

All I want is to access a H2 mem database in Websphere V8 using JPA 2.0

java,jpa,jdbc,websphere,persistence.xml
I've been struggling with this for days now and I searched dozens of articles in StackOverflow and other dev sites. I used the Deployment Manager interface to configure a Websphere Application Server 8.0.0.3 with a H2 JDBC provider and a Data Source for my application using a tutorial I've found...

JDBC API specification and implementation

java,jdbc
I was going through JDBC API's (mainly java.sql package) after writing some simple JDBC programs. For example, in java.sql, the below is the declaration: public interface Connection extends Wrapper, AutoCloseable So, as per my understanding, these specifications have to be implemented by database vendors, in the form of JDBC drivers....

MS SQL JDBC connection with MS SQL Server 2012

sql-server,jdbc
I use to use MYSQL for my database needs. I switched to MSSQL because somebody wanted me to develop an application on it. I used MS SQL Server 2008 earlier and then upgraded to MS SQL Server 2012. In JDBC, I used the following: String connectionUrl="jdbc:sqlserver://"+sname+";DatabaseName="+dbname; where sname is my...

Postgresql Update JDBC

java,postgresql,jdbc
I want to update table: id integer NOT NULL, "first" character varying(255), "last" character varying(255), age integer, CONSTRAINT registration_pkey PRIMARY KEY (id) using method: void updateTable(String tableName, String columnName, String value, String columnName2, String value2) { try { String sql = "UPDATE " + tableName + " SET " +...

Converting h2 database from h2.db to mv.db

java,database,jdbc,h2
I am converting old h2 databases (with the h2.db extension) to the newer mv database engine. In some tables of the database I have a problem with the stricter engine. just a SELECT * FROM does get an error, so with the latest h2-1.4.187.jar... i cannot even open the data...

How to solve JDBC - MySQL I occured? [duplicate]

java,android,mysql,jdbc,import
This question already has an answer here: What is a Null Pointer Exception, and how do I fix it? 12 answers When I run the emulator, it woks perfectly with no errors, but when I press the Login button, I get an error. This is my code: public class...

How to figure out the optimal fetch size for the select query

oracle,memory,jdbc,fetch
In JDBC the default fetch size is 10, but I guess that's not the best fetch size when I have a million rows. I understand that a fetch size too low reduces performance, but also if the fetch size is too high. How can I find the optimal size? And...

Cannot connect to MySQL Server using IP Address

java,mysql,jdbc
In JDBC, when I put localhost for the url to get a connection, it works perfectly fine; I can connect to the database. However, I want other programs to be able to connect. So I tried using my IP address but that doesn't work. I already granted access to other...

How to get remote access to a MySQL database on my computer?

java,mysql,jdbc
I've read around a lot and tried all the suggestions but nothing seems to be working. I want my java program to be able to remotely access a database on my computer. I tried using an IP address for the host name but that doesn't work. The only thing that...

Error in updating records using JDBC [duplicate]

java,mysql,jdbc
This question already has an answer here: Cannot issue data manipulation statements with executeQuery() 5 answers I am having a problem with an MySQL Update query. Here is the code: String s2="foo"; String s6="bar"; try{ Class.forName("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","root"); String query="update mydb set Status='"+s6+"' where IC_Number='"+s2+"'"; Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery(query);...

Escape single quotes in JDBC (getting error: You have an error in your SQL syntax …)

java,mysql,jdbc,syntax-error,quotes
I'm trying to insert data into mysql using jdbc. I have something like this: Connection conn = DriverManager.getConnection(urlDB, userDB, passwordDB); String postTitle = "Post title"; String postContent = "A Linux's distributions"; String sql = "INSERT INTO posts VALUES ( '"+postTitle+"', '"+postContent+"')"; PreparedStatement statement = conn.prepareStatement(sql); statement.executeUpdate(); conn.close(); But I'm getting...

Difference between RETURN_GENERATED_KEYS and specifying the generated column names

java,jdbc,auto-increment
What is the difference between the prepareStatement(String sql, int autoGeneratedKeys) and prepareStatement(String sql, String[] columnNames) methods of the JDBC Connection class? The Javadoc for both indicates that the returned PreparedStatement object is capable of returning auto-generated keys if the SQL statement is an INSERT statement. In the case of the...

connecting to a database through JDBC [duplicate]

java,mysql,jdbc,database-connection
This question already has an answer here: Connect Java to a MySQL database 8 answers I am trying to follow a tutorial in a book on connecting a program to a database with JDBC. I am confused on what the first block of code is doing in the class....

Get the value of the last inserted record

java,jdbc
I am trying to get the stop_name of the last inserted row in the table with preparedStatement. How can I get the last inserted one? I appreciate any help. behavoiur table: CREATE TABLE IF NOT EXISTS behaviour( behaviour_id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, mac VARCHAR(30) NOT NULL, stop_name VARCHAR(30)...

java.sql.SQLException: No suitable driver found for CONNECTION_URL

java,jdbc
i m getting error java.sql.SQLException: No suitable driver found for CONNECTION_URL This is a connection provider java file. package login; import java.sql.*; import java.sql.SQLException; public class ConnectionProvider { static Connection con = null; String database = "game"; String CONNECTION_URL = "jdbc:mysql://localhost:3306/" + database; String USERNAME = "root"; String PASSWORD =...

Do I need next() for a ResultSet with one row?

java,mysql,jdbc,resultset
I have the following code Statement stmt = SqlHelper.initializeDB(); String query = "SELECT status " + "FROM books " + "WHERE bookId = '" + bookId + "'"; ResultSet rs = stmt.executeQuery(query); result = rs.getString(1); rs.close(); SqlHelper.closeConnection(); Do I need to use rs.next()? I am sure there is only going...

How to get all data from row wise from a resultset in jdbc

java,mysql,jdbc
I have a table which is showing one row at a time, i.e in the first iteration it will give one row information and 2nd iteration and so on. Now I want to get all the row data in result set. How I can do that?? This is the structure...

How is the RowMapper Method working from Spring 1.2?

java,spring,jdbc,spring-data,spring-jdbc
I am doing a documentation of a Spring 1.2 implemented giant application for my company which wasn't documented while being coded around 8 years ago. Right now I am on one of the java classes and stuck on a particular method on how it is actually working, specially the part...

When to close connection in JDBC/SQL [duplicate]

java,mysql,jdbc
This question already has an answer here: When to close Connection, Statement, PreparedStatement and ResultSet in JDBC 1 answer I have a program that uses an SQL database and I had a question regarding when to close the connection of the program and the database. Should I connect at...

Append data to a DB2 blob

java,jdbc,db2
In my DB2 database, I have a table with a Blob: CREATE TABLE FILE_STORAGE ( FILE_STORAGE_ID integer, DATA blob(2147483647), CONSTRAINT PK_FILE_STORAGE PRIMARY KEY (FILE_STORAGE_ID)); Using the db2jcc JDBC driver (db2jcc4-9.7.jar), I can read and write data in this table without any problems. Now I need to be able to append...

Can't insert or update record to database jsp

java,jsp,jdbc
I am creating a form that is used to insert, update and delete data in a database, managed to do everything right but update and insert are not functioning. Delete works fine. Any help with solution will be highly appreciated FirstController package com.firstmohform.controller; import com.firstmohform.dao.FirstDAO; import java.io.IOException; import java.io.PrintWriter; import...

SQLException:java.sql.SQLException: Operation not allowed after ResultSet closed, While ResulSet never closed [duplicate]

java,jdbc,sqlexception
This question already has an answer here: Getting java.sql.SQLException: Operation not allowed after ResultSet closed 3 answers What I know-we cannot call ResultSet after this has been closed.and this is a good practice to close every ResultSet,StatementandConnection after using this. But in my code i never closed connection then...

Why does the following statement cause a SyntaxErrorException?

java,mysql,jdbc
I am trying to create a table using JDBC but i am getting syntax error at the query . Statement statement = con.createStatement(); String query = "CREATE TABLE accounts (user VARCHAR2(255) NOT NULL, password VARCHAR2(255) NOT NULL, dateRegistered date "+ "primary key (user));"; statement.executeUpdate(query); System.out.println("part 2:DONE !"); This is the...

Check if value exists in MySQL DB in Java?

java,mysql,database,jdbc
I'm creating a game right now that stores quest values into a DB when a player completes his or her quest. The issue I'm having right now is writing a method that searches the MySQL table for the player id and the quest id to check if he or she...

Exception in JDBC using MySQL

java,mysql,jdbc
I am trying to make an applicatio in java which has database in mysql. I have searched various sources on net and have included mysql-connector-java-5.0.8-bin.jar in properties->library->add JAR/Library. But it still shows me java.lang.ClassNotFound Exception when i run it. I am using netbeans IDE 8.0 and jdk 1.7.0_45 and mysql...

SQL Syntax Error with CREATE TABLE

java,mysql,sql,jdbc
I get a SQL Sytax Error when I try to execute this code: CREATE TABLE ? ( ID INT(255) UNSIGNED AUTO_INCREMENT PRIMARY KEY, `UUID` VARCHAR(36) NOT NULL ); I use a PreparedStatement to replace the ? with a String The Error Message: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an errorin your SQL syntax;...

PreparedStatement query to insert data into specific columns in a table

java,sql,jdbc,prepared-statement
I am trying to insert data into specific columns (5th and 6th) of a table. My PreparedStatement code is as follows: PreparedStatement pst1 = connection.prepareStatement("insert into CustomerPayment (End_Time,Paid) values (?,?) where PC_Used ='"+cmbpcname.getSelectedItem().toString()+"'"); pst1.setString(5,lblendtime.getText()); pst1.setString(6,lblamount.getText().substring(3,5)); pst1.execute(); Is this query right? I am getting error running that query. Any suggestion would...

sql BIT to Java [closed]

java,sql-server,jdbc,types,data-type-conversion
My sqlserver table has a column designed as a BIT datatype. It has values 1 and 0s Then in my Java code, I do result = new ArrayList result.add( (Boolean)(rs.getBoolean("columnName"))); Then when I read the value from the list - it shows as Long. According to everything I find, it...

Create a variable Date in format “yyyy-mm-dd”

java,sqlite,date,jdbc
I am trying to insert to my table, a date in format "yyyy-mm-dd". My table has a field date type DATETIME and I use SQLite DB SYSTEM. I need to be in this format, so later to have the option to select dates from - then. My table: CREATE TABLE...

ActiveMQ offline message transfer on database level

jdbc,activemq
we are running an in-house EAI system using ActiveMQ as the message broker using JDBC persistence. There we have a cold-standby failover solution each one having an own database schema (due to several reasons). Now if the primary goes down and we want to startup the backup we would like...

MySQL Fabric failover and Connection Pooling with Hibernate

mysql,hibernate,jdbc,connection-pooling,mysql-fabric
I'm attempting to implement automatic failover via a MySQL Fabric Server Group using a JNDI Resource, Hibernate, and Connection Pooling. Our DB farm is properly setup with MySQL Fabric and I'm attempting to implement the client/connector. I have a JNDI resource declared in my server.xml file which has a MySQL...

“ORA-00922: missing or invalid option” when trying to insert into table

sql,oracle,jdbc
When i run SQL query in oracle sql developer it is work, but in jdbc this query doesn't work and catch the java.sql.SQLSyntaxErrorException: ORA-00922: missing or invalid option. Could anyone help me ? There is my query below CREATE GLOBAL TEMPORARY TABLE MY_TABLE ( ID VARCHAR2(30 BYTE) PRIMARY KEY, NAME...

Does JDBC drivers talk directly to database? [closed]

java,jdbc,driver
I have some doubts regarding JDBC API's, JDBC drivers and the actual database. I understand that We need JDBC drivers in conjunction with JDBC API's in order to talk to a database. I have the following doubts: 1) Are JDBC API's fully implemented i.e. has Sun/Oracle themselves implemented JDBC API's?...

SQLite3 — Return Affected Rows

jdbc,sqlite3,transactions
Supposing I have a schema with a name field and an int field. I want to get one random entry where the int value is 1, set it to 0, and return the name of the entry that was changed in a transactional manner. What's the best way to do...

Why does my Tomcat only open 8 JDBC connections

java,jdbc,tomcat8
When setting up the database connections in Tomcat 8, for some reason Tomcat is not following what I configured in the context.xml, with as result that I run out of connections, leading to resource contentions at the application server side (BLOCKED/WAITING threads). I always have 8 connections (show processlist in...

Popular error - org.sqlite.JDBC

java,eclipse,sqlite,jdbc,fedora
package aplikacjajava; import java.sql.*; public class main { public main( String args[] ) { Connection c = null; try { Class.forName("org.sqlite.JDBC"); c = DriverManager.getConnection("jdbc:sqlite:projekt.db"); } catch ( Exception e ) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } System.out.println("Opened database successfully"); } } Error: java.lang.ClassNotFoundException: org.sqlite.JDBC I...

Get the id of the inserted row [duplicate]

java,jdbc
This question already has an answer here: sql jdbc getgeneratedkeys returns column “id” not found, column type unknown 2 answers I am trying to get the id of the inserted row. Currenly I am not getting the id back and I am getting the exception java.sql.SQLException: Column 'route_id' not...

What is pre-compiled SQL statement? [duplicate]

java,sql,jdbc,precompile
This question already has an answer here: What does it mean when I say Prepared statement is pre-compiled? 3 answers PreparedStatement is a precompiled statement so it will increase jdbc performance at runtime but still confused about What is precompiled SQL Statement? What it does? Why precompiled statement is...

PostgreSQL: skip erros in SQL clients using JDBC

postgresql,jdbc,squirrel-sql
I want to execute a SQL script in a client using JDBC (not the postgreSQL pslq client). In this script I would like to do something like that: skip errors on; alter table foo ...; skip errors off; Is there a way to do this with PostgreSQL >= 9.1?...

How do I get the variables in a column from java and sql?

java,mysql,jdbc,arraylist
So say a column is named Names I want to get a ArrayList of every variable inside of this column. Example: Names Test Test1 Test3 River World Etc I want to get all of that into an array list. Thanks for the help!...

Display attribute in JComboBox and register another attribute

java,swing,jdbc
I have a JComboBox and I must show the designation of the product, and each has a code designation, in my database I have to register the product code but in the Combo I must show the designation, how should I do to display the designation in the combo but...

ERROR jdbc.HiveConnection: Error opening session Hive

java,hadoop,jdbc,hive
i try to run JBDC code for Hive2 get error. i have hive 1.2.0 version hadoop 1.2.1 version. but in command line hive and beeline works fine without any problem.but with jdbc getting error. import java.sql.SQLException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.sql.DriverManager; public class HiveJdbcClient { private static...

Cannot initialise HikariCP pooled connection, Failure in loading native library db2jcct2

jdbc,db2,hikaricp
I'm trying to use HikariCP together with DB2 but get the following error: Failure in loading native library db2jcct2, java.lang.UnsatisfiedLinkError: db2jcct2 I have db2jcc4.jar file at my class path and only it. And the following hikari properties file: dataSourceClassName=com.ibm.db2.jcc.DB2SimpleDataSource dataSource.user=username dataSource.password=password dataSource.databaseName=database dataSource.serverName=server:50000 From what I understand Hikari tries to...

Select records from a table, which don't exist in another table

mysql,sqlite,jdbc
I have 2 tables TABLE1 and TABLE2 in sqlite DB. TABLE 2 has some of the records of the TABLE1. What I want is to select all the records from TABLE 1, which don't exist in TABLE2. So I coded: String sq = "SELECT TABLE1.name, TABLE1.surname, TABLE1.id FROM TABLE1" +...

Why does DriverManager.getConnection() lookup fail in GroovyConsole?

mysql,jdbc,groovy,groovy-console
The following Groovy script works correctly from the command line. (I successfully get a Connection.) // ---- jdbc_test.groovy import java.sql.* Class.forName("com.mysql.jdbc.Driver") def con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test", "root", "password") println con > groovy -cp lib\mysql-connector-java-5.1.25-bin.jar script\jdbc_test.groovy [email protected] But if the same script is loaded into GroovyConsole (2.4.3) and run - after...

Mysql Java Derby Netbeans: 'deleteRow' not allowed because the ResultSet is not an updatable ResultSet

java,mysql,netbeans,jdbc,derby
I'm trying delete a row but it does not allow me, it says "'deleteRow' not allowed because the ResultSet is not an updatable ResultSet". Here is my code: public void addUserName() throws SQLException { rs = st.executeQuery("select NAME, prize from usernames"); try { while (rs.next()) { String attribute2 = rs.getString("name");...

How to read timezone from 'timestamp with time zone' column?

java,postgresql,jdbc,timestamp-with-timezone
I am unable to find a way to read timezone value in PostgreSQL column of type timestamp with time zone. JDBC offers method java.sql.ResultSet#getTimestamp(int, java.util.Calendar) but I must provide my own calendar. I have see no way to obtain that calendar from timestamp field I am reading. I am working...

Uncategorized SQLException Jdbc Template

java,sql-server,spring,jdbc
I'm attempting to call a stored procedure to create an item in a SQL table. When the code is run, the stored procedure is run and the item is created, but throws this error. The values stored in the table are correct and the generate key generates the correct key....

Invalid operation for read only resultset when using select for update nowait in multithreaded environment

java,multithreading,jdbc,oracle11g
For an Oracle database, the following program will throw SQL exceptions only for some threads. Why downgrading resultSetConcurrency from CONCUR_UPDATABLE to CONCUR_READ_ONLY? In a single thread environment this is not happening. import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class Main extends Thread { public static final...

java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in date in query expression

jsp,ms-access,jdbc
Can Someone help me to solve the error. I am getting error when I pass the date String ex:"01-JAN-2015" as Parameter in setString ? javax.servlet.ServletException: java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error in date in query expression '(Event_Dairy) between #Pa_RaM000# and #Pa_RaM001#'. String url="jdbc:odbc:kaso"; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn=DriverManager.getConnection(url); PreparedStatement ppdsmt=conn.prepareStatement("select *...

Using a ResultSet after executing two different queries with statement.executeQuery() [duplicate]

java,jdbc,resultset
This question already has an answer here: Invalid state, the ResultSet object is closed 1 answer Given the code below: //connection stuff ResultSet rs = statement.executeQuery(query1); statement.executeQuery(query2); while(rs.next){ //code } Is the result set rs still valid even though a second statement has been executed? I know that when...

GET the id of the inserted record

java,jdbc
I am trying to get the id of the inserted record with the use of getGeneratedKeys. I dont know how to call setId(generatedKeys.getLong(1)); here to get the id? How can I get it to work. I appreciate any help. Code: ResultSet routesTables = dbm.getTables(null, null, "routes", null); int route_id; if...

apache camel route to split sql results

mysql,jdbc,apache-camel
I am trying to do is select all rows from DB, and for each row update some column for that row. Below is my camel route. from("direct:insert"). from("sql:select * from my_table"). split(body()). log("${body[id]}"). end(); I use the below code to start this route... context.createProducerTemplate().sendBody("direct:insert", null); Problem is it happens multiple...

Why paging query does not work

java,jsp,java-ee,servlets,jdbc
The main function of this program is to write a page displays the contents of the database and can achieve Pagination When you first visit the page can display the contents of the database,But when you click on the link below when the page is not able to properly display...