Table/View 'ACCOUNTS' already exists in Schema 'APP' - java

I'm not an experienced database developer.
Running a JDBC program with org.apache.derby.jdbc.EmbeddedDriver. When I try to create an ACCOUNTS table, I use the following code:
final String DRIVER =
"org.apache.derby.jdbc.EmbeddedDriver";
final String CONNECTION =
"jdbc:derby:AccountDatabase;create=true";
try {
Class.forName(DRIVER).newInstance();
} catch ( ... etc.
}
try (Connection connection =
DriverManager.getConnection(CONNECTION);
Statement statement =
connection.createStatement()) {
statement.executeUpdate(
"create table ACCOUNTS "
+ " (NAME VARCHAR(32) NOT NULL PRIMARY KEY, "
+ " ADDRESS VARCHAR(32), "
+ " BALANCE FLOAT) ");
But I get the following error message:
Table/View 'ACCOUNTS' already exists in Schema 'APP'.
Then, when I try to update or query the ACCOUNTS table with the following code:
final String DRIVER =
"org.apache.derby.jdbc.EmbeddedDriver";
final String CONNECTION =
"jdbc:derby:AccountDatabase";
try {
Class.forName(DRIVER).newInstance();
} catch ( .. etc.
}
try (Connection connection =
DriverManager.getConnection(CONNECTION);
Statement statement =
connection.createStatement();
ResultSet resultset =
statement.executeQuery(
"select * from ACCOUNTS")) {
I get the following error messages:
java.sql.SQLException: Database 'AccountDatabase' not found.
Also, when I check for the existence of any tables with the following code, I get no tables at all:
DatabaseMetaData meta = connection.getMetaData();
ResultSet res = meta.getTables(null, null, null,
new String[] { "TABLE" });
System.out.println("List of tables: ");
while (res.next()) {
System.out.println(" " + res.getString("TABLE_CAT") + ", "
+ res.getString("TABLE_SCHEM") + ", "
+ res.getString("TABLE_NAME") + ", "
+ res.getString("TABLE_TYPE") + ", "
+ res.getString("REMARKS"));
}
Any suggestions?

Related

Error: No suitable driver found for jdbc:omar\mssqlserver01:sqlserver://localhost:1433;DatabaseName=DB1FR;

I am trying to connect java code to SQL server, I am using engine mssqlserver01, database called DB1FR.
I tried opening the server SQL configuration -> TCP/UDP -> IP address and unified al ports to 1433 and dynamic ones to 0. I also tried another engine, restarted the database.
public static void addCustomer(int id, String fullName, String email, int creditCardNum, int nationalID) throws SQLException {
Connection con = DriverManager.getConnection( "jdbc:sqlserver://mssqlserver01:1433;DatabaseName=DB1FR;user=omar;");
java.sql.Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("INSERT INTO dbo.Customer(CustomerID, full_name, email, creditcardnum, nationalid) VALUES "
+ id + ", "
+ fullName + ", "
+ email + ", "
+ creditCardNum + ", "
+ nationalID);
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}
}
It should insert into the CUSTOMER table those values. But an exception is thrown and the table is not updated.

ORA-00923: FROM keyword not found where expected in SeleniumWebDriver

I created a class (ValidarStatusOsPage) in java that makes a connection to the DB and returns to a test class (ValidateStatusOsTest) the result of the query and prints to the screen.
When I run the test class, the Eclipse console displays the message:
ORA-00923: FROM keyword not found where expecte
I have reviewed the code several times but I can not verify where the error is.
Below is the Java class for connecting to the DB and the test class.
public class ValidarStatusOsTest {
static String query;
#Test
public void validarOs() {
ValidarStatusOsPage os = new ValidarStatusOsPage();
query = os.returnDb("179195454");
}}
public class ValidarStatusOsPage {
String resultado;
public String returnDb(String NuOs) {
// Connection URL Syntax: "jdbc:mysql://ipaddress:portnumber/db_name"
String dbUrl = "jdbc:oracle:thin:#10.5.12.116:1521:desenv01";
// Database Username
String username = "bkofficeadm";
// Database Password
String password = "bkofficeadmdesenv01";
// Query to Execute
String query = "SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURA" +
"FROM tb_bkoffice_os"+
"WHERE NU_OS ="+ NuOs +"";
try {
// Load mysql jdbc driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// Create Connection to DB
Connection con = DriverManager.getConnection(dbUrl, username, password);
// Create Statement Object
Statement stmt = con.createStatement();
// Execute the SQL Query. Store results in ResultSet
ResultSet rs = stmt.executeQuery(query);
// While Loop to iterate through all data and print results
while (rs.next()) {
String NU_OS = rs.getString(1);
String CD_ESTRATEGIA = rs.getString(2);
String CD_STATUS = rs.getString(3);
String NU_MATR = rs.getString(4);
String DT_ABERTURA = rs.getString(5);
resultado = NU_OS + " " + CD_ESTRATEGIA + " " + CD_STATUS + " " + NU_MATR + " " + DT_ABERTURA + "\n";
System.out.println(NU_OS + " - " + CD_ESTRATEGIA + " - " + CD_STATUS + " - " + NU_MATR + " - "+ DT_ABERTURA);
}
// closing DB Connection
con.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return resultado;
}}
3 points are there in your query:
SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURA" +
"FROM tb_bkoffice_os"+
"WHERE NU_OS ="+ NuOs +""
space before FROM missed first part of query is: SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURAFROM
space missed before WHERE: SELECT NU_OS, CD_ESTRATEGIA, CD_STATUS, NU_MATR, DT_ABERTURAFROM tb_bkoffice_osWHERE NU_OS =
concatenate parameter into SQL string is exact hack point for SQL Injection attack. Never do it in real program even if it is pure standalone. Always use parameters for queries.
and a little last one: + NuOs +"" - last "" has no sense at all...
good luck.
UPD: #YCF_L absolutely right use Prepared statement.
you need to do this:
in Sql String: WHERE NU_OS = ?
in code:
PreparedStatement stmt = con.prepareStatement(query);
stmt.setString(1, NuOs);
//also works: stmt.setObject(1,NuOs);
things to remember with JDBC:
all parameters in SQL are just ? marks
parameter indexes start with 1 (not 0)
and in order they appear in SQL from strat to end
(e.g. Select * FROM tbl WHERE col1=? and col2=?
has parameter 1 for col1 and parameter 2 for col2
PS. your initial SQL has one more error but I'm not going to tell you what is it :-) use parameter and all be fine.

Resultset.next returns true but doesn't return the value

I am trying to read from a mysql table and I am doing the following:
protected void pushRegisteredStudentsData() {
try {
conn = (Connection) DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String userID = "SELECT * FROM STUDENT";
rs = stmt.executeQuery(userID);
while (rs.next()) {
int id = rs.getInt("ID");
this.studentID = id;
String insertSql = "INSERT INTO REGISTEREDSTUDENTS(StudentID, ModuleCode) VALUES ('" + studentID + "', + '"
+ this.moduleCode + "')";
System.out.println("Inserting into REGISTEREDSTUDENTS.. [" + id + "]" + "[" + this.moduleCode + "]");
stmt.executeUpdate(insertSql);
}
} catch (SQLException e) {
}
}
..but for some reason,
while (rs.next()) {
int id = rs.getInt("ID");
always returns the same ID, even though the table has different ID's on every line!
Does anyone have an idea why that might be?
Thank you in advance! :(
EDIT:
I was using a single statement to execute 2 updates, which was causing the problem!
It is a bit weird that it returns always the same value because it should only return the first value ONCE.
If you print the stacktrace instead of just catching the exception and doing nothing, you will see that it will print something like:
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:794)
You are using THE SAME statement for a Select and then for an Insert. This causes the resultSet that is "attached" to the Statement to close because it is not supposed to be used again.
It can be easily fixed by creating another statement:
String insertSql = "INSERT INTO REGISTEREDSTUDENTS(StudentID, ModuleCode) VALUES ('" + studentID + "', + '"
+ this.moduleCode + "')";
System.out.println("Inserting into REGISTEREDSTUDENTS.. [" + id + "]" + "[" + this.moduleCode + "]");
Statement stmt2 = conn.createStatement();
stmt2.executeUpdate(insertSql);

Java JDBC SQLite update entry not working

I have created a database and a set of table using JDBC and SQLite in Eclipse.
I am trying to update the table using the following code:
public static void update()
{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:WalkerTechCars.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
String sql = "UPDATE CUSTOMERS2 set ADDRESS = Byron WHERE PHONE=2;";
stmt.executeUpdate(sql);
c.commit();
ResultSet rs = stmt.executeQuery( "SELECT * FROM CUSTOMERS;" );
while ( rs.next() ) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
String address = rs.getString("address");
float salary = rs.getFloat("salary");
System.out.println( "ID = " + id );
System.out.println( "NAME = " + name );
System.out.println( "AGE = " + age );
System.out.println( "ADDRESS = " + address );
System.out.println( "SALARY = " + salary );
System.out.println();
}
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
System.out.println("Update Completed successfully");
}
As far as I can understand the SQL syntax I m using says:
update the table customers2 and set the address as Byron where phone =2
But am getting the following error:
java.sql.SQLException: no such column: Byron
Which tells me it is interpreting my request as asking to alter the column named Byron, which is not what I believe the code to be saying?
As per SQL syntax, varchar values should be used with single quotes so update this:
String sql = "UPDATE CUSTOMERS2 set ADDRESS = Byron WHERE PHONE=2;";
to
String sql = "UPDATE CUSTOMERS2 set ADDRESS = 'Byron' WHERE PHONE=2;";
If you don't use the single quotes, SQL assumes that you are trying to set the value using a different column and hence it throws the error:
java.sql.SQLException: no such column: Byron
ADVICE: Use PreparedStatment for dynamic parameter queries
PreparedStatement stmt;
String sql = "UPDATE CUSTOMERS2 set ADDRESS=? WHERE PHONE=?";
stmt = c.prepareStatement(sql);
stmt.setString(1, "Byron");
stmt.setInt(2, 2);
stmt.executeUpdate();

Wrong data type returned for date in jtds.jar

I have a table on MS SQL Server with a column having data type as date. I am using jtds.jar for JDBC connection with DB. I am taking DatabaseMetaData from Connection. While checking columns from DatabaseMetaData, I observed that
int iType = rsMeta.getInt("DATA_TYPE");
returns Column type as java.sql.Types.VARCHAR which is a string and not date. but it also returns
String tmp = rsMeta.getString("TYPE_NAME");
type name as date.
But for Oracle, It returns the date datatype as java.sql.Types.DATE.
Why is such a difference?
This is a known JTDS bug, see http://sourceforge.net/p/jtds/bugs/679/.
The returned datatype for a SQLServer Date type is returned as a
varchar with a length of 10. This is wrong, it should return as
Sql.Date. int iType = rsMeta.getInt("DATA_TYPE"); String tmp =
rsMeta.getString("TYPE_NAME");
This still appears to be an open issue with jTDS 1.3.1. I was able to work around it by querying the SQL Server table catalog directly for the tables I'm working with, and getting a list of date columns for the table:
private HashMap<String,Boolean> getDateColumns (String tableName, String schemaName, Connection conn) throws Exception {
String sql = "SELECT table_name + ',' + column_name"
+ " FROM INFORMATION_SCHEMA.COLUMNS "
+ " WHERE TABLE_SCHEMA = N'" + schemaName + "' "
+ " AND table_name = N'" + tableName + "' "
+ " AND data_type IN ('date', 'datetime', 'datetime2')";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
HashMap<String,Boolean> dateCols = new HashMap<String,Boolean>();
while (rs.next()) {
String tableColKey = rs.getString(1);
dateCols.put(tableColKey.toUpperCase(), true );
}
rs.close();
return dateCols;
}
Once you have this list, you can explicitly check and see if the column is a date type:
private ResultSetMetaData getTableMetaData (String tableName, Connection conn) throws Exception {
String sql = "SELECT * FROM dbo." + tableName + " where 1 = 2 ";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
rs.close();
HashMap<String,Boolean> dateColumns = getDateColumns (tableName, conn);
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String key = tableName + "," + rsmd.getColumnName(i);
int type = -1;
if (dateColumns.containsKey(key)) {
type = Types.DATE;
}
else {
type = rsmd.getColumnType(i);
}
System.out.println ("... col: " + rsmd.getColumnName(i) + ", driver type name: " + rsmd.getColumnTypeName(i) + ", driver type: " + rsmd.getColumnType(i) + ", final data type: " + type);
}
return rsmd;
}
So, say I have a sample table with three columns:
SAMPLE
------------------
SITE_ID numeric
START_DATE date
END_DATE date
This code will print the following values when run with jTDS:
... col: SITE_ID, driver type name: numeric, driver type: 2, final data type: 2
... col: START_DATE, driver type name: nvarchar, driver type: 12, final data type: 91
... col: END_DATE, driver type name: nvarchar, driver type: 12, final data type: 91
It's not ideal, but it should work for others with a similar problem.

Categories