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();
}
}
}
Related
I'm coding some database transactions by using java. I'm sending a query using java. I think it has no problem with it. And if I send the query at prompt, it is working.
This method is updating book quantity.
private static void updateBquantity(int bqt, String bname) {
Connection con = makeConnection();
try {
Statement stmt = con.createStatement();
System.out.println(bqt + " " +bname);
//this part is making problem
stmt.executeUpdate("update books set bookquantity = bookquantity -" + bqt + "where bookname = '" + bname + "';");
System.out.println("<book quantity updated>");
} catch (SQLException e) {
System.out.println(e.getMessage());
System.exit(0);
}
stmt.executeUpdate("update books set bookquantity = bookquantity -" + bqt + "where 도서이름 = '" + bname + "';");
This part is making problem.
Other queries using this form is working.
The compiler says :
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'bookname = 'Davinci Code'' at line 1
Help me.
I'm confused with bookname = 'Davinci Code, where is bookname in your query? No matter what, in this query, you missed a blank before where, try this:
stmt.executeUpdate("update books set bookquantity = bookquantity -" + bqt + " where 도서이름 = '" + bname + "';");
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.
I'm trying to create an Apache Derby-Table and to insert data in it by the JDBC-interface.
Here is a short excerpt of my implementation:
public class SQLDatabase {
private Connection connection = null;
public final static String HOME_DIRECTORY = System.getProperty("user.home");
public final static String TABLE_NAME = "PORPHYRIE";
public SQLDatabase() {
setConnection();
if (!(isTableExisting(TABLE_NAME))) {
createTable();
}
}
// OTHER
public void createTable() {
String statement = "CREATE TABLE PORPHYRIE("
+ "ID int NOT NULL GENERATED ALWAYS AS IDENTITY"
+ "(START WITH 1,INCREMENT BY 1)," + "ENTRYDATE DATE NOT NULL,"
+ "DRUGTYPE varchar(255) NOT NULL,"
+ "UPPERLIMIT DOUBLE NOT NULL," + "NORMOSANG BOOLEAN NOT NULL,"
+ "MENSTRUATION BOOLEAN NOT NULL,"
+ "DRUGAMOUNT_MG DOUBLE NOT NULL,"
+ "DRUGAMOUNT_ML DOUBLE NOT NULL,"
+ "AMPOULE_NUMBERS DOUBLE NOT NULL,"
+ "RECORDDATE DATE NOT NULL," + "PRIMARY KEY(ID)" + ")";
updateStatement(statement);
}
public void dropTable() {
String statement = "DROP TABLE PORPHYRIE";
updateStatement(statement);
}
public void addData(EntryPoint entry) {
DrugAmount drugAmount = entry.getDrugAmountObject();
SimpleDateFormat form = new SimpleDateFormat("dd.MM.yyyy");
String statement = "INSERT INTO PORPHYRIE (ENTRYDATE,DRUGTYPE,UPPERLIMIT,NORMOSANG,MENSTRUATION,DRUGAMOUNT_MG,DRUGAMOUNT_ML,AMPOULE_NUMBERS,RECORDDATE)"
+ " values('"
+ form.format(entry.getEntryDate().getTime())
+ "','"
+ entry.DRUG_TYPE_DOLANTIN
+ "',"
+ entry.DRUG_UPPER_LIMIT
+ ","
+ entry.getNormoSang()
+ ","
+ entry.getMenstruation()
+ ","
+ drugAmount.getAmpoulesInMG()
+ ","
+ drugAmount.getAmpoulesInML()
+ ","
+ drugAmount.getNumberOfAmpoules() + ",CURRENT_DATE)";
System.out.println("Add data!");
updateStatement(statement);
}
private void setConnection() {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
connection = DriverManager.getConnection("jdbc:derby:"
+ HOME_DIRECTORY + "\\MyDB;create=true");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
private void updateStatement(String statementString) {
try {
PreparedStatement preparedStatement = getConnection()
.prepareStatement(statementString);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
This is what I get:
What is here the problem with the ID column?
The first time when a SQL-Database object is created, is should create the table, which works fine.
Then you should able to insert some data by the addData()-method, which also looks fine.
But if you create an new SQL-Database Object and use the addData-method() within, then it adds the data (row five in the picture above) but do not auto-increment correctly. What is wrong here?
Gaps in the generated sequence numbers are a correct and documented behavior of Derby.
See, for example, https://db.apache.org/derby/docs/10.9/ref/rrefproperpreallocator.html
And: https://issues.apache.org/jira/browse/DERBY-5151
the problem is we have to shut down the derby db whenever we are sign out or closing our application,then only the values will be inserted properly otherwise the cache values prevents the exact insertion value in database table.
follow below steps:
con = DriverManager.getConnection("jdbc:derby:" + "db" + ";create=true");->this is for loading derby db by mentioning 'db' name.this code we have to place in your application login action.
DriverManager.getConnection("jdbc:derby:"+"db"+";shutdown=true");->this is for closing the database 'db'.we have to place this code in your application logout action or closing place.
note : This is for Embedded DB
As Described by Bryan, this error is well known. But good thing is you can solve it by using:
DriverManager.getConnection("jdbc:derby:;shutdown=true");
This will shutdown all the databases that you have in derby, you can always specify the database you want to shutdown.
DriverManager.getConnection("jdbc:derby:" + HOME_DIRECTORY + "\\MyDB;shutdown=true")
I am using java to execute postgresql statements. In one step, I need to create a table in which one column will store blocks of text (that may contain punctuation marks, such as comma, semi-colon, etc).
What data type do I use to populate this column?
For example, in the given example, I am creating a table called "MYTHOUGHTS", and that has a column called "THOUGHTS". I am trying the following code:
try {
con = DriverManager.getConnection(url, user, password);
System.out.println("Opened Database Successfully");
st = con.createStatement();
String sql = "CREATE TABLE MYTHOUGHTS " + "(ID INT PRIMARY KEY NOT NULL," + " THOUGHTS TEXT NOT NULL," + " Number INT NOT NULL," + " ADDRESS CHAR(50), " + " SALARY REAL)";
st.executeUpdate(sql);
sql = "INSERT INTO COMPANY (ID,THOUGHTS,AGE,ADDRESS,SALARY) " + "VALUES (1," + "This is life, as I see it. Do you think otherwise?" + ", 32, 'California', 20000.00 );";
st.executeUpdate(sql);
st.close();
con.close();
}
catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
I get the following error:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "life"
Position: 68
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2161)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1890)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:560)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:403)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:331)
at com.vivek.PostgreSQLExample.main(PostgreSQLExample.java:39)
org.postgresql.util.PSQLException: ERROR: syntax error at or near "life"
Position: 68
It is possible that TEXT data type is not appropriate. Please, let me know how I may add multiple lines of text that may have commas and periods into a column.
Thank you for your time and assistance. Highly appreciate it.
Use the text data type. The contents do not matter, the only thing you can't put in text is the null byte \0.
If you're having problems with the contents then you're running dangerous code that's doing direct string interpolation, instead of using parameterized statements. See: http://bobby-tables.com/ , http://en.wikipedia.org/wiki/SQL_injection, http://docs.oracle.com/javase/tutorial/jdbc/basics/
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