i am trying to make a simple application using h2 Database. Program is working perfectly just for one time. when i am tying to insert more data, following error occurred.
org.h2.jdbc.JdbcSQLException: Database may be already in use: "C:/Users/ali/bookDB.mv.db". Possible solutions: close all other connection(s); use the server mode [90020-186]
java.lang.IllegalStateException: The file is locked: nio:C:/Users/ali/bookDB.mv.db [1.4.186/7]
Code is
package h2_basic;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class H2_Basic {
public static void main(String[] args) {
try{
Class.forName("org.h2.Driver");
Connection con = DriverManager.getConnection("jdbc:h2:~/bookDB","test","test");
Statement sta = con.createStatement();
String CREATE_TABLE = "CREATE TABLE BOOKS "
+ "(bookid bigint auto_increment NOT NULL PRIMARY KEY, "
+ " booktitle VARCHAR(255), "
+ " bookauthor VARCHAR(255), "
+ " editiondate VARCHAR(255))";
sta.execute(CREATE_TABLE);
String sql = "INSERT INTO BOOKS (booktitle, bookauthor, editiondate) VALUES ('ali','ali','12')";
sta.execute(sql);
}catch(Exception ex)
{
ex.printStackTrace();
}
}
}
Change your JDBC URL to jdbc:h2:~/bookDB;AUTO_SERVER=TRUE, as in
DriverManager.getConnection("jdbc:h2:~/bookDB;AUTO_SERVER=TRUE","test","test");
to start H2 in Automatic Mixed Mode.
Related
I am creating a database that keeps track of Spiderman comic books. I am getting a SQLExecption at line 28:
stmt.executeUpdate(createstring);"
So I assume there is something wrong with the syntax of my SQL that is in the createstring but nothing jumps out at me.
Below is code
import java.sql.*;
import javax.swing.*;
public class SpidermanDatabase {
public static void main(String[] args)
{
String url = "jdbc:ucanaccess://c:/users/jeff/comics.accdb";
Connection con;
String createstring;
createstring = "CREATE TABLE Spider-Man (" +
"ComicName varchar(40), " +
"IssueDate varchar(40), " +
"IssueName varchar(40), " +
"MintCond varchar(40), " +
"IssueValue double(2,2), " +
"IssueNum int)";
Statement stmt;
try
{
con = DriverManager.getConnection(url, "", "");
stmt = con.createStatement();
stmt.executeUpdate(createstring);
JOptionPane.showMessageDialog(null, "Spider-Man table created", "SQL Statement Confirmation",
JOptionPane.INFORMATION_MESSAGE);
stmt.close();
con.close();
System.exit(0);
}
catch(SQLException ex)
{
System.out.println("SQLException");
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
}
Image attached is full error message
It appears to me that you are using Microsoft Access database. It also appears that you are using ucanaccess JDBC driver to connect to that database.
Your problem is that you are using an illegal character in the name of the table that you are trying to create. According to Microsoft documentation, identifiers, such as database table names, cannot contain a dash (-) (also known as a hyphen) – unless you enclose the identifier in either square brackets, i.e. [], or quotation marks.
Hence you should change the SQL create table string to the following:
createstring = "CREATE TABLE [Spider-Man] (" +
"ComicName varchar(40), " +
"IssueDate varchar(40), " +
"IssueName varchar(40), " +
"MintCond varchar(40), " +
"IssueValue double, " +
"IssueNum int)";
Also note that the double data type cannot have scale and precision qualifiers. Hence I also removed the (2,2) part from the data type for column IssueValue.
Remember that after this you must always write [Spider-Man] (or "Spider-Man") as the table name in all SQL statements. Alternatively, you could replace the dash with and underscore (_) which is a legal character in an identifier and thus do away with the need for square brackets (or quotation marks), i.e. name the table Spider_Man.
EDIT
Although the above CREATE TABLE statement is valid SQL, it appears that ucanaccess JDBC driver cannot handle it. The only way I got it to work was to replace the dash with an underscore.
Here is my java code for creating the database table Spider_Man.
(Note that the below code uses try-with-resources.)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class JdbcTst0 {
public static void main(String[] args) {
String url = "jdbc:ucanaccess://C:/users/jeff/comics.accdb";
String createstring = "CREATE TABLE Spider_Man (" +
"ComicName varchar(40), " +
"IssueDate varchar(40), " +
"IssueName varchar(40), " +
"MintCond varchar(40), " +
"IssueValue double, " +
"IssueNum int)";
try (Connection con = DriverManager.getConnection(url, "", "");
Statement stmt = con.createStatement()) {
stmt.executeUpdate(createstring);
System.out.println("Spider_Man table created");
}
catch (SQLException xSql) {
xSql.printStackTrace();
}
}
}
I'm in a Java class and the assignment is to create a table that will show the first ten values of pre-selected columns. However, when I run my code, with the sql running the way it is it says that my table is already created. I was wondering if there was a way for it to stop erroring out when that happens and to still show my code? Also when I set up a new table, the values that I need, (Income, ID, Pep) won't show up, just the headers I established before the syntax will. How would I make these fixes so it stops erroring out and I see my values in the console log?
This is running in eclipse, extended with prior project files from the class i'm taking. I've tried adding prepared statements, attempted to parse for strings to other variables and attempted syntax to achieve the values I need.
LoanProccessing.java file (Main file):
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class LoanProcessing extends BankRecords {
public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub
BankRecords br = new BankRecords();
br.readData();
Dao dao = new Dao();
dao.createTable();
dao.insertRecords(torbs); // perform inserts
ResultSet rs = dao.retrieveRecords();
System.out.println("ID\t\tINCOME\t\tPEP");
try {
while (rs.next()) {
String ID= rs.getString(2);
double income=rs.getDouble(3);
String pep=rs.getString(4);
System.out.println(ID + "\t" + income + "\t" + pep);
}
}
catch (SQLException e ) {
e.printStackTrace();
}
String s = "";
s=String.format("%10s\t %10s \t%10s \t%10s \t%10s \t%10s ", rs.getString(2), rs.getDouble(3), rs.getString(4));
System.out.println(s);
String timeStamp = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(Calendar.getInstance().getTime());
System.out.println("Cur dt=" + timeStamp);
Dao.java file:
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Dao {
//Declare DB objects
DBConnect conn = null;
Statement stmt = null;
// constructor
public Dao() { //create db object instance
conn = new DBConnect();
}
public void createTable() {
try {
// Open a connection
System.out.println("Connecting to a selected database to create Table...");
System.out.println("Connected database successfully...");
// Execute create query
System.out.println("Creating table in given database...");
stmt = conn.connect().createStatement();
String sql = "CREATE TABLE A_BILL__tab " + "(pid INTEGER not NULL AUTO_INCREMENT, " + " id VARCHAR(10), " + " income numeric(8,2), " + " pep VARCHAR(4), " + " PRIMARY KEY ( pid ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
conn.connect().close(); //close db connection
} catch (SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
}
}
public void insertRecords(BankRecords[] torbs) {
try {
// Execute a query
System.out.println("Inserting records into the table...");
stmt = conn.connect().createStatement();
String sql = null;
// Include all object data to the database table
for (int i = 0; i < torbs.length; ++i) {
// finish string assignment to insert all object data
// (id, income, pep) into your database table
String ID = torbs[i].getID();
double income=torbs[i].getIncome();
String pep=torbs[i].getPep();
sql = "INSERT INTO A_BILL__tab(ID,INCOME, PEP) " + "VALUES (' "+ID+" ', ' "+income+" ', ' "+pep+" ' )";
stmt.executeUpdate(sql);
}
conn.connect().close();
} catch (SQLException se) { se.printStackTrace(); }
}
public ResultSet retrieveRecords() {
ResultSet rs = null;
try {
stmt = conn.connect().createStatement();
System.out.println("Retrieving records from table...");
String sql = "SELECT ID,income,pep from A_BILL__tab order by pep desc";
rs = stmt.executeQuery(sql);
conn.connect().close();
} catch (SQLException se) { se.printStackTrace();
}
return rs;
}
}
Expected results would be printlns for the table functions (inserting records and so on), the headings, the data values for the first 10 files, and the date and time of when the program was run. Actual results were some of the table functions, headings and then the time when the program ran not including when it errors me out with table already created. I'm not exactly sure where or how to fix these issues.
you're getting this exception because every time you run your code, your main method calls dao.createTable();, and if the table is already created, it will throw an exception. So for this part, use a verification to check if the table is already created.
I'm not really sure where you created the variable torbs, but also make sure its properties are not null before inserting them to the database.
I am Trying to write a stored procedure in derby Database.
I wrote a Java file which executes as expected.
This is my java File
package javaapplication8;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class JavaApplication8 {
public static void procedure(int uid, String Domain) {
Connection con;
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
con = DriverManager.getConnection("jdbc:derby://localhost:1527/Love_To_Learn", "Mohammed_Numan", "mohammed");
String sql = "Update Intrests set Points = Points + 10 where User_Id = " + uid + " and Intrest = '" + Domain + "'";
PreparedStatement pst = con.prepareStatement(sql);
int x = pst.executeUpdate();
if (x == 1) {
System.out.println("Finally");
}
} catch (Exception e) {
System.out.println(e);
}
}
}
I installed the jar file in the database by using.
CALL sqlj.install_jar( 'C:\Users\flipkart\My Documents\NetBeansProjects\JavaApplication8\dist\JavaApplication8.jar', 'Mohammed_Numan.JavaApplication8',0);
And
CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.database.classpath','Mohammed_Numan.JavaApplication8');
Created a Procedure Using
CREATE PROCEDURE Final(IN ID INTEGER,
IN Dom VARCHAR(40))
LANGUAGE JAVA
PARAMETER STYLE JAVA
EXTERNAL NAME 'javaapplication8.JavaApplication8.procedure';
This gives me no error.
Now i called the Procedure Using
call Final(10006,'Java');
Even this executes.But the table is not Updated.
Any reason For This?
I even Called this using callable Statement.
The code is
CallableStatement cst = con.prepareCall("Call Final (?,?)");
cst.setInt(1,Integer.parseInt(u.getString(1)));
cst.setString(2,v.getString(1));
boolean done = cst.execute();
if(done){
System.out.println("Done")
}
else{
System.out.println("Sorry");
}
And i always get Sorry..!Where Am i Going Wrong?Please Check out.
I am attempting to execute multiple SQL statements at once using JDBC. I am aware that the addBatch() and executeBatch() functions can be used to accomplish this. I have incorporated them into my code and even "SET NOCOUNT OFF" but my CREATE and INSERT statements were not reflected in my SQL Server database. Here is what I have attempted below:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import com.microsoft.sqlserver.jdbc.SQLServerException;
public class Excel_Java_POI_Exp_V2
{
#BeforeClass
public void setUp() throws Exception
{
//Do Nothing
}
#Test
public void testUsingExcel() throws Exception, SQLException
{
String url = "jdbc:sqlserver://localhost:1433;" + "databaseName=AdventureWorks2012;" + "integratedSecurity=true;";
try
{
//Loading the required JDBC Driver class
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
//Creating a connection to the database
Connection conn = DriverManager.getConnection(url);
//Print Connection Verification
System.out.println("Connection Established ln");
Statement query = conn.createStatement();
//Executing SQL query and fetching the result
String SQL = "SET NOCOUNT OFF;";
//CREATE A NEW SQL TABLE AFTER ESTABLISHING CONNECTION
String SQL_Create = "CREATE TABLE SELCREATEDB"
+ "(PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255));";
//INSERT 10 RECORDS WITHIN DATABASE TABLE
String SQL1 = "INSERT INTO dbo.SELCREATEDB VALUES "
+ "(\"1000\", \"Davis\", \"John\", \"3444 Mulberry Lane\", \"Oakland CA\")";
String SQL2 = "INSERT INTO dbo.SELCREATEDB VALUES "
+ "(\"1001\", \"Robinson\", \"Larry\", \"5633 Skyline Drive\", \"Annandale VA\")";
String SQL3 = "INSERT INTO dbo.SELCREATEDB VALUES "
+ "(\"1002\", \"Arafat\", \"Yasser\", \"5633 Quidbury Lane\", \"Hezburg Israel\")";
String SQL4 = "INSERT INTO dbo.SELCREATEDB VALUES "
+ "(\"1003\", \"Castro\", \"Fidel\", \"5234 Honey Tree Avenue\", \"Port Lunciana Cuba\")";
String SQL5 = "INSERT INTO dbo.SELCREATEDB VALUES "
+ "(\"1004\", \"Carter\", \"Jimmy\", \"9234 Mackel Court\", \"Lynchburg VA\")";
String SQL6 = "INSERT INTO dbo.SELCREATEDB VALUES "
+ "(\"1005\", \"Boro\", \"Kerebede\", \"2342 Memory Lane\", \"Jamestowne VA\")";
String SQL7 = "INSERT INTO dbo.SELCREATEDB VALUES "
+ "(\"1006\", \"Attenborough\", \"David\", \"3330 Peach Lane\", \"Atlanta GA\")";
String SQL8 = "INSERT INTO dbo.SELCREATEDB VALUES "
+ "(\"1007\", \"Ahmed\", \"David\", \"30499 Tressleburry Lane\", \"Tampa FL\")";
String SQL9 = "INSERT INTO dbo.SELCREATEDB VALUES "
+ "(\"1008\", \"Tramper\", \"Jamie\", \"30499 Dickens Avenue\", \"Dallas TX\")";
String SQL10 = "INSERT INTO dbo.SELCREATEDB VALUES "
+ "(\"1009\", \"Valentine\", \"Rudy\", \"8900 Spicetree Lane\", \"San Diego CA\")";
//SET PROPERTIES
query.addBatch(SQL);
//CREATE TABLE
query.addBatch(SQL_Create);
//INSERT RECORDS
query.addBatch(SQL1);
query.addBatch(SQL2);
query.addBatch(SQL3);
query.addBatch(SQL4);
query.addBatch(SQL5);
query.addBatch(SQL6);
query.addBatch(SQL7);
query.addBatch(SQL8);
query.addBatch(SQL9);
query.addBatch(SQL10);
//EXECUTE ALL COMMANDS
query.executeBatch();
//CLOSE CONNECTION
conn.close();
}
catch (SQLServerException sqe)
{
System.out.println("A result set was generated for update.");
}
catch (java.sql.BatchUpdateException bae)
{
System.out.println("Executed Queries! Terminating Connection...");
}
}
#AfterClass
public void tearDown() throws Exception
{
//Do Nothing
}
}
I am using SQL Server 2012 Standard Edition with an Established JDBC Connection to the AdventureWorks2012 database. Any help would be much appreciated. Thank You!
The code that you have is absolutely fine but the SQL statements that you've written for your INSERT's are not one of the finest. The issue was the INSERT queries in itself!
I've corrected the INSERT queries and executed the program with one change, of SQL AUTHENTICATION and the program worked with no issues.
Updated code:
public class DDLDMLStatementsinJDBC
{
public static final String URL = "jdbc:sqlserver://localhost:1433;" + "databaseName=Dummy;sendStringParametersAsUnicode=false";
public static final String DBUSER = "sa";
public static final String DBPASS = "Welcome12!";
public static void main(String[] args) throws Exception, SQLException
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(URL, DBUSER, DBPASS);
System.out.println("Connection Established ln");
Statement query = conn.createStatement();
String SQL = "SET NOCOUNT OFF;";
String SQL_Create = "CREATE TABLE SELCREATEDB" + "(PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255));";
String SQL1 = "INSERT INTO dbo.SELCREATEDB VALUES " + "(1000, 'Davis', 'John', '3444 Mulberry Lane', 'Oakland CA')";
String SQL2 = "INSERT INTO dbo.SELCREATEDB VALUES " + "(1001, 'Robinson', 'Larry', '5633 Skyline Drive', 'Annandale VA')";
String SQL3 = "INSERT INTO dbo.SELCREATEDB VALUES " + "(1002, 'Arafat', 'Yasser', '5633 Quidbury Lane', 'Hezburg Israel')";
String SQL4 = "INSERT INTO dbo.SELCREATEDB VALUES " + "(1003, 'Castro', 'Fidel', '5234 Honey Tree Avenue', 'Port Lunciana Cuba')";
String SQL5 = "INSERT INTO dbo.SELCREATEDB VALUES " + "(1004, 'Carter', 'Jimmy', '9234 Mackel Court', 'Lynchburg VA')";
query.addBatch(SQL);
query.addBatch(SQL_Create);
query.addBatch(SQL1);
query.addBatch(SQL2);
query.addBatch(SQL3);
query.addBatch(SQL4);
query.addBatch(SQL5);
query.executeBatch();
conn.close();
}
catch (SQLServerException sqe)
{
System.out.println("A result set was generated for update.");
sqe.printStackTrace();
}
catch (java.sql.BatchUpdateException bae)
{
System.out.println("Executed Queries! Terminating Connection...");
bae.printStackTrace();
}
}
}
Hope you are able to get the change!
I'm trying to use HyperSQL in my Java application in the following way:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Main {
static Connection conn;
static Statement stat;
public static void main(String[] args) {
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver" );
} catch (Exception ex) {
System.out.println("An error occurred while loading HSQLDB JDBC driver: " + ex.getMessage());
return;
}
try {
conn = DriverManager.getConnection(
"jdbc:hsqldb:file:helper_db;sql.syntax_mys=true");
stat = conn.createStatement();
stat.executeUpdate(
"CREATE TABLE IF NOT EXISTS some_table " +
"(" +
"foo TEXT PRIMARY KEY, " +
"bar TEXT" +
");"
);
stat.executeUpdate(
"INSERT INTO some_table VALUES" +
"('foo', 'bar') " +
"ON DUPLICATE KEY UPDATE some_table = VALUES" +
"('foo', 'bar');"
);
} catch (Exception ex) {
System.out.println("An error occurred: " + ex.getMessage());
return;
}
}
}
This code gives me the following output:
An error occurred: unexpected token: ON
What am I doing wrong? How to resolve this issue?
HSQLDB does not support the ON DUPLICATE syntax (which is clearly documente in the manual).
You need to use MERGE instead assuming that there is at least one column in your values clause that is a unique key:
MERGE INTO some_table ut
USING (
VALUES
('foo', 'bar')
) AS md (foo_column, bar_column) ON (ut.foo_column = md.foo_column)
WHEN MATCHED THEN UPDATE
SET ut.bar_column = md.bar_column
WHEN NOT MATCHED THEN
INSERT (foo_column, bar_column)
VALUES (md.foo_column, md.bar_column);
Please check the manual for more details: http://hsqldb.org/doc/2.0/guide/dataaccess-chapt.html#dac_merge_statement
The updated version of HSQL now supports ON DUPLICATE KEY UPDATE feature of MySQL.
Refer: http://hsqldb.org/doc/guide/guide.html#coc_compatibility_mysql