diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..39f27a6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,287 @@ +# Created by https://www.toptal.com/developers/gitignore/api/java,gradle,intellij,intellij+all,macos,windows +# Edit at https://www.toptal.com/developers/gitignore?templates=java,gradle,intellij,intellij+all,macos,windows + +### Intellij ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +# .idea/artifacts +# .idea/compiler.xml +# .idea/jarRepositories.xml +# .idea/modules.xml +# .idea/*.iml +# .idea/modules +# *.iml +# *.ipr + +# CMake +cmake-build-*/ + +# Mongo Explorer plugin +.idea/**/mongoSettings.xml + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Cursive Clojure plugin +.idea/replstate.xml + +# SonarLint plugin +.idea/sonarlint/ + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +# Editor-based Rest Client +.idea/httpRequests + +# Android studio 3.1+ serialized cache file +.idea/caches/build_file_checksums.ser + +### Intellij Patch ### +# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 + +*.iml +modules.xml +.idea/misc.xml +*.ipr + +# Sonarlint plugin +# https://plugins.jetbrains.com/plugin/7973-sonarlint +.idea/**/sonarlint/ + +# SonarQube Plugin +# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin +.idea/**/sonarIssues.xml + +# Markdown Navigator plugin +# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced +.idea/**/markdown-navigator.xml +.idea/**/markdown-navigator-enh.xml +.idea/**/markdown-navigator/ + +# Cache file creation bug +# See https://youtrack.jetbrains.com/issue/JBR-2257 +.idea/$CACHE_FILE$ + +# CodeStream plugin +# https://plugins.jetbrains.com/plugin/12206-codestream +.idea/codestream.xml + +# Azure Toolkit for IntelliJ plugin +# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij +.idea/**/azureSettings.xml + +### Intellij+all ### +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider +# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 + +# User-specific stuff + +# AWS User-specific + +# Generated files + +# Sensitive or high-churn files + +# Gradle + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +.idea/artifacts +.idea/compiler.xml +.idea/jarRepositories.xml +.idea/modules.xml +.idea/*.iml +.idea/modules +*.iml +*.ipr + +# CMake + +# Mongo Explorer plugin + +# File-based project format + +# IntelliJ + +# mpeltonen/sbt-idea plugin + +# JIRA plugin + +# Cursive Clojure plugin + +# SonarLint plugin + +# Crashlytics plugin (for Android Studio and IntelliJ) + +# Editor-based Rest Client + +# Android studio 3.1+ serialized cache file + +### Intellij+all Patch ### +# Ignore everything but code style settings and run configurations +# that are supposed to be shared within teams. + +.idea/* + +!.idea/codeStyles +!.idea/runConfigurations + +### Java ### +# Compiled class file +*.class + +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* +replay_pid* + +### macOS ### +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +### macOS Patch ### +# iCloud generated files +*.icloud + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +### Gradle ### +.gradle +**/build/ +!src/**/build/ + +# Ignore Gradle GUI config +gradle-app.setting + +# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) +!gradle-wrapper.jar + +# Avoid ignore Gradle wrappper properties +!gradle-wrapper.properties + +# Cache of project +.gradletasknamecache + +# Eclipse Gradle plugin generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath + +### Gradle Patch ### +# Java heap dump +*.hprof + +# End of https://www.toptal.com/developers/gitignore/api/java,gradle,intellij,intellij+all,macos,windows \ No newline at end of file diff --git a/bin/com/holub/database/jdbc/JDBCConnection$1.class b/bin/com/holub/database/jdbc/JDBCConnection$1.class index d9ab462..6c4f981 100644 Binary files a/bin/com/holub/database/jdbc/JDBCConnection$1.class and b/bin/com/holub/database/jdbc/JDBCConnection$1.class differ diff --git a/bin/com/holub/database/jdbc/JDBCConnection$2.class b/bin/com/holub/database/jdbc/JDBCConnection$2.class index 9ef4842..c611ae2 100644 Binary files a/bin/com/holub/database/jdbc/JDBCConnection$2.class and b/bin/com/holub/database/jdbc/JDBCConnection$2.class differ diff --git a/bin/com/holub/database/jdbc/JDBCConnection.class b/bin/com/holub/database/jdbc/JDBCConnection.class index baeb217..7a642ae 100644 Binary files a/bin/com/holub/database/jdbc/JDBCConnection.class and b/bin/com/holub/database/jdbc/JDBCConnection.class differ diff --git a/bin/com/holub/database/jdbc/JDBCPreparedStatement.class b/bin/com/holub/database/jdbc/JDBCPreparedStatement.class new file mode 100644 index 0000000..ffb6aa0 Binary files /dev/null and b/bin/com/holub/database/jdbc/JDBCPreparedStatement.class differ diff --git a/bin/com/holub/database/jdbc/JDBCStatement.class b/bin/com/holub/database/jdbc/JDBCStatement.class index 50dad9a..a648c0b 100644 Binary files a/bin/com/holub/database/jdbc/JDBCStatement.class and b/bin/com/holub/database/jdbc/JDBCStatement.class differ diff --git a/bin/com/holub/database/jdbc/JDBCTest.class b/bin/com/holub/database/jdbc/JDBCTest.class index a11df70..050cd40 100644 Binary files a/bin/com/holub/database/jdbc/JDBCTest.class and b/bin/com/holub/database/jdbc/JDBCTest.class differ diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..38df794 --- /dev/null +++ b/build.gradle @@ -0,0 +1,44 @@ +plugins { + id 'java' + id 'maven-publish' +} + +group 'com.holub' +version '1.0-SNAPSHOT' + +repositories { + mavenCentral() +} + +dependencies { + testImplementation 'junit:junit:4.12' + implementation 'junit:junit:4.12' +} + +sourceSets { + main { + java { + srcDirs = ['src'] + } + } +} + +jar { + manifest { + attributes 'Main-Class': 'com.holub.jdbc.Console' + } +} + +publishing { + publications { + mavenJava(MavenPublication) { + from components.java + } + } + + repositories { + maven { + url 'https://jitpack.io' + } + } +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..7f93135 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..ac72c34 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..0adc8e1 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..6689b85 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/com/holub/database/jdbc/JDBCConnection.java b/src/com/holub/database/jdbc/JDBCConnection.java index f4eea8a..a8cf8b4 100644 --- a/src/com/holub/database/jdbc/JDBCConnection.java +++ b/src/com/holub/database/jdbc/JDBCConnection.java @@ -93,6 +93,12 @@ public Statement createStatement() throws SQLException { return new JDBCStatement(database); } + public PreparedStatement prepareStatement(String sql) throws SQLException + { return new JDBCPreparedStatement(sql, database); + // cannot be casted without implements PreparedStatement + // need to write overriding methods for PreparedStatement + } + /** Terminate the current transactions and start a new * one. Does nothing if auto-commit mode is on. * @see #setAutoCommit diff --git a/src/com/holub/database/jdbc/JDBCPreparedStatement.java b/src/com/holub/database/jdbc/JDBCPreparedStatement.java new file mode 100644 index 0000000..50aaad4 --- /dev/null +++ b/src/com/holub/database/jdbc/JDBCPreparedStatement.java @@ -0,0 +1,28 @@ +package com.holub.database.jdbc; + +import com.holub.database.Database; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +public class JDBCPreparedStatement extends JDBCStatement{ + private Database database; + private String sqlQuery; + private JDBCConnection connection; + + public JDBCPreparedStatement(String sql, Database database) + { + super(database); + this.database = database; + this.sqlQuery = sql; + } + public JDBCPreparedStatement(JDBCConnection c, String sql, Database database){ + super(c, database); + this.connection = c; + this.database = database; + this.sqlQuery = sql; + } + + protected static PreparedStatement getInstance(JDBCConnection conn, String sql, Database db) throws SQLException { + return new JDBCPreparedStatement(conn, sql, db); + } +} diff --git a/src/com/holub/database/jdbc/JDBCStatement.java b/src/com/holub/database/jdbc/JDBCStatement.java index 013e507..93dd6ef 100644 --- a/src/com/holub/database/jdbc/JDBCStatement.java +++ b/src/com/holub/database/jdbc/JDBCStatement.java @@ -28,21 +28,30 @@ import java.sql.*; import java.io.*; +import java.util.ArrayList; +import java.util.List; import com.holub.database.*; import com.holub.database.jdbc.adapters.*; - + /*** * @include /etc/license.txt */ - public class JDBCStatement extends StatementAdapter -{ private Database database; +{ + private Database database; + private static List sql_batch = new ArrayList<>(); + protected volatile JDBCConnection connection = null; public JDBCStatement(Database database) { this.database = database; } - + + public JDBCStatement(JDBCConnection c, Database database) { + this.connection = c; + this.database =database; + } + public int executeUpdate(String sqlString) throws SQLException { try { database.execute( sqlString ); @@ -52,7 +61,7 @@ public int executeUpdate(String sqlString) throws SQLException { throw new SQLException( e.getMessage() ); } } - + public ResultSet executeQuery(String sqlQuery) throws SQLException { try { Table result = database.execute( sqlQuery ); @@ -62,8 +71,56 @@ public ResultSet executeQuery(String sqlQuery) throws SQLException { throw new SQLException( e.getMessage() ); } } - public void close() throws SQLException { // does nothing. } + + public void addBatch(String sql) throws SQLException { + //synchronized (checkClosed().getConnectionMutex()){ + if (sql != null){ + sql_batch.add(sql); + } + //} + } + + public int[] executeBatch() throws SQLException { + int updateCounts[] = new int[sql_batch.size()]; + try { + if (sql_batch != null) { + int nbrCommands = sql_batch.size(); + for (int i = 0; i < nbrCommands; i++) { + updateCounts[i] = EXECUTE_FAILED; // set error value(-3) + } + int commandIndex = 0; + for (commandIndex = 0; commandIndex < nbrCommands; commandIndex++) { + try { + String sql = sql_batch.get(commandIndex); + updateCounts[commandIndex] = executeUpdate(sql); + } catch (SQLException ex) { + updateCounts[commandIndex] = EXECUTE_FAILED; + } + } + } + return updateCounts != null ? updateCounts : new int[0]; + }catch (Exception e) { + System.out.println("error!"); + throw new SQLException(e.getMessage()); + }finally { + clearBatch(); + } + } + + public void clearBatch() throws SQLException { + sql_batch.clear(); + } + + protected JDBCConnection checkClosed() throws SQLException { + JDBCConnection c = this.connection; + + if (c == null){ + throw new SQLException("Statement.AlreadyClosed"); + } + return c; + } + } diff --git a/src/com/holub/database/jdbc/JDBCTest.java b/src/com/holub/database/jdbc/JDBCTest.java index 3837def..aa1335d 100644 --- a/src/com/holub/database/jdbc/JDBCTest.java +++ b/src/com/holub/database/jdbc/JDBCTest.java @@ -35,38 +35,38 @@ public class JDBCTest { static String[] data = - { "(1, 'John', 'Mon', 1, 'JustJoe')", - "(2, 'JS', 'Mon', 1, 'Cappuccino')", - "(3, 'Marie', 'Mon', 2, 'CaffeMocha')", - }; + { "(1, 'John', 'Mon', 1, 'JustJoe')", + "(2, 'JS', 'Mon', 1, 'Cappuccino')", + "(3, 'Marie', 'Mon', 2, 'CaffeMocha')", + }; public static void main(String[] args) throws Exception { Class.forName( "com.holub.database.jdbc.JDBCDriver" ) //{=JDBCTest.forName} - .newInstance(); + .newInstance(); Connection connection = null; Statement statement = null; try { connection = DriverManager.getConnection( //{=JDBCTest.getConnection} - "file:/c:/src/com/holub/database/jdbc/Dbase", - "harpo", "swordfish" ); + "file:/c:/src/com/holub/database/jdbc/Dbase", + "harpo", "swordfish" ); statement = connection.createStatement(); - + statement.executeUpdate( - "create table test (" + - " Entry INTEGER NOT NULL" + - ", Customer VARCHAR (20) NOT NULL" + - ", DOW VARCHAR (3) NOT NULL" + - ", Cups INTEGER NOT NULL" + - ", Type VARCHAR (10) NOT NULL" + - ", PRIMARY KEY( Entry )" + - ")" + "create table test (" + + " Entry INTEGER NOT NULL" + + ", Customer VARCHAR (20) NOT NULL" + + ", DOW VARCHAR (3) NOT NULL" + + ", Cups INTEGER NOT NULL" + + ", Type VARCHAR (10) NOT NULL" + + ", PRIMARY KEY( Entry )" + + ")" ); for( int i = 0; i < data.length; ++i ) - statement.executeUpdate( + statement.executeUpdate( "insert into test VALUES "+ data[i] ); // Test Autocommit stuff. If everything's working @@ -74,13 +74,13 @@ public static void main(String[] args) throws Exception // but Fred should not. connection.setAutoCommit( false ); - statement.executeUpdate( - "insert into test VALUES "+ - "(4, 'James', 'Thu', 1, 'Cappuccino')" ); + statement.addBatch( + "insert into test VALUES "+ + "(4, 'James', 'Thu', 1, 'Cappuccino')" ); + statement.addBatch( + "insert into test (Customer) VALUES('Fred')"); + int[] batch_result = statement.executeBatch(); connection.commit(); - - statement.executeUpdate( - "insert into test (Customer) VALUES('Fred')"); connection.rollback(); connection.setAutoCommit( true ); @@ -89,18 +89,18 @@ public static void main(String[] args) throws Exception ResultSet result = statement.executeQuery( "select * from test" ); while( result.next() ) { System.out.println - ( result.getInt("Entry") + ", " - + result.getString("Customer") + ", " - + result.getString("DOW") + ", " - + result.getInt("Cups") + ", " - + result.getString("Type") - ); + ( result.getInt("Entry") + ", " + + result.getString("Customer") + ", " + + result.getString("DOW") + ", " + + result.getInt("Cups") + ", " + + result.getString("Type") + ); } } finally { - try{ if(statement != null) statement.close(); }catch(Exception e){} - try{ if(connection!= null) connection.close();}catch(Exception e){} + try{ if(statement != null) statement.close(); }catch(Exception e){} + try{ if(connection!= null) connection.close();}catch(Exception e){} } } -} +} \ No newline at end of file diff --git a/src/com/holub/database/jdbc/adapters/StatementAdapter.java b/src/com/holub/database/jdbc/adapters/StatementAdapter.java index 96af5fe..d7dd9e3 100644 --- a/src/com/holub/database/jdbc/adapters/StatementAdapter.java +++ b/src/com/holub/database/jdbc/adapters/StatementAdapter.java @@ -25,11 +25,19 @@ * in any of this code. */ package com.holub.database.jdbc.adapters; +import com.holub.database.jdbc.JDBCConnection; + +import java.io.InputStream; +import java.io.Reader; +import java.math.BigDecimal; +import java.net.URL; import java.sql.*; +import java.util.Calendar; + /*** * @include /etc/license.txt */ -public class StatementAdapter implements java.sql.Statement +public class StatementAdapter implements java.sql.Statement, java.sql.PreparedStatement { public StatementAdapter() {} @@ -70,47 +78,68 @@ public StatementAdapter() {} public void setCursorName(String name) throws SQLException {throw new SQLException("Statement.setCursorName(String name) not supported");} public void setEscapeProcessing(boolean enable) throws SQLException {throw new SQLException("Statement.setEscapeProcessing(boolean enable) not supported");} public void setMaxFieldSize(int max) throws SQLException {throw new SQLException("Statement.setMaxFieldSize(int max) not supported");} -public void checkClosed() throws SQLException {throw new SQLException("Statement.checkClosed() not supported");} - -@Override -public T unwrap(Class iface) throws SQLException { - // TODO Auto-generated method stub - return null; -} - -@Override -public boolean isWrapperFor(Class iface) throws SQLException { - // TODO Auto-generated method stub - return false; -} - -@Override -public boolean isClosed() throws SQLException { - // TODO Auto-generated method stub - return false; -} - -@Override -public void setPoolable(boolean poolable) throws SQLException { - // TODO Auto-generated method stub - -} - -@Override -public boolean isPoolable() throws SQLException { - // TODO Auto-generated method stub - return false; -} - -@Override -public void closeOnCompletion() throws SQLException { - // TODO Auto-generated method stub - -} - -@Override -public boolean isCloseOnCompletion() throws SQLException { - // TODO Auto-generated method stub - return false; -} -} +// checkClosed(): public -> protected, void -> JDBCConnection +protected JDBCConnection checkClosed() throws SQLException {throw new SQLException("Statement.checkClosed() not supported");} +// adding PreparedStatement +public T unwrap(Class iface) throws SQLException {throw new SQLException("PreparedStatement.unwrap() not supported");} +public boolean isWrapperFor(Class iface) throws SQLException {throw new SQLException("PreparedStatement.isWrapperFor() not supported");} +public boolean isClosed() throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setPoolable(boolean poolable) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public boolean isPoolable() throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void closeOnCompletion() throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public boolean isCloseOnCompletion() throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public ResultSet executeQuery() throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public int executeUpdate() throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setNull(int parameterIndex, int sqlType) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setBoolean(int parameterIndex, boolean x) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setByte(int parameterIndex, byte x) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setShort(int parameterIndex, short x) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setInt(int parameterIndex, int x) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setLong(int parameterIndex, long x) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setFloat(int parameterIndex, float x) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setDouble(int parameterIndex, double x) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setBigDecimal(int parameterIndex, BigDecimal x) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setString(int parameterIndex, String x) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setBytes(int parameterIndex, byte[] x) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setDate(int parameterIndex, Date x) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setTime(int parameterIndex, Time x) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setTimestamp(int parameterIndex, Timestamp x) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setAsciiStream(int parameterIndex, InputStream x, int length) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setUnicodeStream(int parameterIndex, InputStream x, int length) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void clearParameters() throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setObject(int parameterIndex, Object x) throws SQLException {throw new SQLException("PreparedStatement.setObject() not supported");} +public boolean execute() throws SQLException {throw new SQLException("PreparedStatement.execute() not supported");} +public void addBatch() throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setRef(int parameterIndex, Ref x) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setBlob(int parameterIndex, Blob x) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setClob(int parameterIndex, Clob x) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setArray(int parameterIndex, Array x) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public ResultSetMetaData getMetaData() throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setTime(int parameterIndex, Time x, Calendar cal) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setTimestamp(int parameterIndex, Timestamp x, Calendar cal) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setURL(int parameterIndex, URL x) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public ParameterMetaData getParameterMetaData() throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setRowId(int parameterIndex, RowId x) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setNString(int parameterIndex, String value) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setNCharacterStream(int parameterIndex, Reader value, long length) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setNClob(int parameterIndex, NClob value) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setClob(int parameterIndex, Reader reader, long length) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setBlob(int parameterIndex, InputStream inputStream, long length) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setNClob(int parameterIndex, Reader reader, long length) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setSQLXML(int parameterIndex, SQLXML xmlObject) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setObject(int parameterIndex, Object x, int targetSqlType, int scaleOrLength) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setAsciiStream(int parameterIndex, InputStream x, long length) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setBinaryStream(int parameterIndex, InputStream x, long length) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setAsciiStream(int parameterIndex, InputStream x) throws SQLException {throw new SQLException("PreparedStatement.isClosed() not supported");} +public void setBinaryStream(int parameterIndex, InputStream x) throws SQLException {throw new SQLException("PreparedStatement.setBinaryStream() not supported");} +public void setCharacterStream(int parameterIndex, Reader reader) throws SQLException {throw new SQLException("PreparedStatement.setCharacterStream() not supported");} +public void setNCharacterStream(int parameterIndex, Reader value) throws SQLException {throw new SQLException("PreparedStatement.setNCharacterStream() not supported");} +public void setClob(int parameterIndex, Reader reader) throws SQLException {throw new SQLException("PreparedStatement.setClob() not supported");} +public void setBlob(int parameterIndex, InputStream inputStream) throws SQLException {throw new SQLException("PreparedStatement.setBlob() not supported");} +public void setNClob(int parameterIndex, Reader reader) throws SQLException {throw new SQLException("PreparedStatement.setNClob() not supported");}}