ERROR ON QUERYING ORACLE DB - java

I am using oracle 10g and I wrote a create table query like this -
String UserTable="CREATE TABLE UserDetail ( \n" +
" idNo INT(64) NOT NULL , \n" +
" name VARCHAR(50),\n" +
" email VARCHAR(50), \n" +
" state VARCHAR(50),\n"+
" country VARCHAR(50),\n" +
" CONSTRAINT person_pk PRIMARY KEY ('idNo')"
+ ");";
// Connection con2=DriverManager.getConnection(DbAddress,"vivek","123456");
PreparedStatement st2=conn.prepareStatement(UserTable);
st2.executeUpdate();
conn.close();
but it gives following exception-
java.sql.SQLSyntaxErrorException: ORA-00907: missing right parenthesis
on syssout it the query becomes this -
CREATE TABLE UserDetail (
idNo INT(64) NOT NULL ,
name VARCHAR(50),
email VARCHAR(50),
state VARCHAR(50),
country VARCHAR(50),
CONSTRAINT person_pk PRIMARY KEY (idNo)
);
please help.

Remove the below line
CONSTRAINT person_pk PRIMARY KEY ('idNo')
Use the below line in your code instead
CONSTRAINT person_pk PRIMARY KEY (idNo)

oh I got the solution- I was using Int instead of Number and it was not supported. the query should be-
"CREATE TABLE UserDetail ( \n" +
" idNo NUMBER NOT NULL , \n" +
" name VARCHAR(50),\n" +
" email VARCHAR(50), \n" +
" state VARCHAR(50),\n"+
" country VARCHAR(50),\n" +
" CONSTRAINT person_pk PRIMARY KEY ('idNo')"
+ ");";

Related

INSERT OR REPLACE only works with 1 row in database

INSERT OR REPLACE works when there is only one row in the table and it happens to be the one that is replaced. However, when there are multiple rows in the table, INSERT OR REPLACE just inserts and creates a duplicate!
For example, if I create an entry with eventId = '123'. And then try to write another entry with eventId = '123' and roomnumber equal to something different than the first entry, INSERT OR REPLACE will work. However, if there are more than one rows in the table it will create a duplicate. Here is my code:
String createSql = "CREATE TABLE IF NOT EXISTS events (\n"
+ " eventId VARCHAR(20) PRIMARY KEY ON CONFLICT REPLACE,\n"
+ " roomNumber VARCHAR(20) NOT NULL,\n"
+ " startTime TIMESTAMP NOT NULL,\n"
+ " endTime TIMESTAMP NOT NULL,\n"
+ " name VARCHAR(250),\n"
+ " isVIP BOOLEAN NOT NULL,\n"
+ " capacity INTEGER(20) NOT NULL, \n"
+ " UNIQUE (eventId) \n"
+ ");";
String sql = "INSERT OR REPLACE INTO events (eventId, roomNumber, startTime, endTime, capacity, name, isVIP)" + " Values('"+event.getID()+"', '"+event.getRoomNumber()+"', '"+event.getStartTime()+"', '"+event.getEndTime()+"', '"+event.getCapacity()+"', '"+event.getName()+"', '"+event.getVIPStatus()+"')";
I would read this thread for more information about how REPLACE works.
https://stackoverflow.com/questions/29539838/replace-versus-insert-in-sql#:~:text=According%20to%20the%20documentation%2C%20the,the%20new%20row%20is%20inserted.
Also I would suggest trying just "REPLACE," as it functions as INSERT but will replace on conflicts.

SQLite Delete Cascade not working: FOREIGN KEY constraint failed

I have two table:
Child Table
public static final String SQL_CREATE_TAB_COMMENT = "CREATE TABLE " +TABLE_COMMENT+ "( " + KEY_COMMENT + " INTEGER PRIMARY KEY AUTOINCREMENT , " + COLUMN_EMMET + " TEXT NOT NULL , " +COMMENT+ " TEXT , "+IMAGCOM+" TEXT , "+FORMAT+" TEXT NOT NULL , "+DATECMTCREATION+" TEXT , "+TAGSTATUTCMT+" TEXT , "+ COLUMN_COMMENT_KEY_POST +" INT NOT NULL , "+EMETPOST_PHONE+ " TEXT, " +DEST_PHONE+ " TEXT, " + IDCMTEMET + " TEXT,"+VISITEDCMT+" TEXT, "+TAB_IMAGES + " TEXT, "+IS_DOWNLOADED + " TEXT,"+FILEDOC+" TEXT, FOREIGN KEY(" + COLUMN_COMMENT_KEY_POST + ") REFERENCES " + TABLE_POST_NEW + "(_id) ON DELETE CASCADE )";
Parent Table
public static final String SQL_CREATE_TAB_POST_NEW = "CREATE TABLE " +TABLE_POST_NEW+ "( " +KEY_POST+ " INTEGER PRIMARY KEY AUTOINCREMENT ," +EMMET+ " TEXT NOT NULL , " +TEXT+ " TEXT NOT NULL , "+ IMAG +" TEXT ,"+TYPE+ " TEXT ," +DEST+ " TEXT ," +IDPOSTEMET+ " TEXT NOT NULL, " +CMT_NON_LU+ " TEXT, " +DATELASTEVENT+" TEXT, " +DATECREATION+ " TEXT, " +TAGSTATUT+ " TEXT,"+COUNTER_DEST+" TEXT,"+VISITED+" TEXT,"+ NAME_GROUP+ " TEXT,"+ IDGROUP + " TEXT, "+TAB_IMAGES + " TEXT, "+IS_DOWNLOADED +" TEXT, "+COLUMN_POST_KEY_CONTACT+ " INT NOT NULL DEFAULT 0, "+LABEL_IMAGES+" TEXT,"+TAB_FILE+" TEXT)";
Now If I am deleting parent row I have this error:
FOREIGN KEY constraint failed Error Code : 787 (SQLITE_CONSTRAINT_FOEIGNKEY)
Caused By : Abort due to constraint violatio
public PosteManager openForWrite(){
db = dbHelper.getWritableDatabase();
//db.execSQL("PRAGMA foreign_keys=ON");
db.setForeignKeyConstraintsEnabled(true);
return this;
}
public int deletePoste(int posteId){
openForWrite();
int delete = db.delete(DbHelper.TABLE_POST_NEW, DbHelper.KEY_POST + "=" + posteId, null);
close();
return delete;
}
KEY_POST = _id; and I test COLUMN_COMMENT_KEY_POST = _id and COLUMN_COMMENT_KEY_POST = post_id
I have the same error
I test your code and I have this in Log.d("TABLESQL","The creation SQL for table " :
D/TABLESQL: The creation SQL for table comment_tbl_new is
CREATE TABLE comment_tbl_new( _commentid INTEGER PRIMARY KEY AUTOINCREMENT , Emetteur TEXT NOT NULL , comment TEXT , imageCom TEXT , format TEXT NOT NULL , Datecmtcreation TEXT , Tagstatutcmt TEXT , post_id INT NOT NULL , emetPost_phone TEXT, Dest_phone TEXT, idcmtemet TEXT,visited TEXT, tab_image TEXT, idownloaded TEXT,filedoc TEXT, FOREIGN KEY(post_id) REFERENCES post_tbl_new(_id) )
06-14 00:11:06.845 18468-18468/com. D/TABLESQL: The creation SQL for table comment_tbl is
CREATE TABLE comment_tbl( _commentid INTEGER PRIMARY KEY AUTOINCREMENT , Emetteur TEXT NOT NULL , comment TEXT , imageCom TEXT , format TEXT NOT NULL , Datecmtcreation TEXT , Tagstatutcmt TEXT , _id INT NOT NULL , emetPost_phone TEXT, Dest_phone TEXT, idcmtemet TEXT,visited TEXT, tab_image TEXT, idownloaded TEXT,filedoc TEXT, FOREIGN KEY(_id) REFERENCES post_tbl_new(_id) ON DELETE CASCADE )
From API 16+, you should enable foreign key constraint like this in SQLITEOpenHelper class:
#Override
public void onConfigure(SQLiteDatabase db){
db.setForeignKeyConstraintsEnabled(true);
}
As the foreign key constraint is enabled, You can check if another table is not referring child table and it's foreign key is not cascade. Also ") REFERENCES " + TABLE_POST_NEW + "(_id) have you defined _id column in your TABLE_POST_NEW ?

How to Dynamically Assign Table Name in mysql Server

I am trying To Create Tables in mysql dynamically And Assign them Name Using The Email Address User Provided. But Whenever I try to Assign Table Name dynamically it shows me error and i don,t know anyother way to fulfil my requirement.
Here is The Code I Wrote
String TableName = Email.getText();
try {
String myTableName = "CREATE TABLE '" + TableName + "' "
+ "(id INTEGER not NULL, "
+ " first VARCHAR(255), "
+ " last VARCHAR(255), "
+ " age INTEGER, "
+ " PRIMARY KEY ( id ))";;
Class.forName(m.RegisterationString);
java.sql.Connection con;
con = DriverManager.getConnection(m.URL, m.UserName, m.Password);
Statement State = con.createStatement();
//This line has the issue
State.executeUpdate(myTableName);
System.out.println("Table Created");
}
In MySQL the name of table should not be between '' it can be between :
String myTableName ="CREATE TABLE `" + tableName + "`"
//--------------------------------^-----------------^
Note for good pratice don't start the name of variable with upper letter like State or TableName, Email

creating a new mysql table using JAVA

I'm trying to create a table similar to a ready table I created before (a template, if you will) where the only variable should be the table name.
This is what I've tried so far:
I exported the template table to mysql code and copied the code to a preparedStatement object as such:
createNewLineTableStatement = constantLink.prepareStatement("CREATE TABLE IF NOT EXISTS ? (" +
" `index` int(5) NOT NULL," +
" `station` int(5) NOT NULL," +
" PRIMARY KEY (`index`)," +
" UNIQUE KEY `station` (`station`)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;\");");
Than I try to execute the code by calling the following function:
private static boolean createNewLineTable(String tableName) throws SQLException{
createNewLineTableStatement.setString(1, tableName);
if (createNewLineTableStatement.executeUpdate() == Statement.EXECUTE_FAILED)
return false;
return true;
}
But I'm getting a syntax error exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 ''line_37_var_1' ( `index` int(5) NOT NULL, `station` int(5) NOT NULL, PRIMARY' at line 1
How can I fix the code? OR is there a cleaner, better way to do the same thing? Maybe creating a script with a user variable? I thought of that but I've never used .sql script before.
Problem 1: You can't use a prepared statement parameter as the table name.
Problem 2: You have an unmatched paren and extra characters ");at the end of your statement.
Your query string should look something like:
String query = "CREATE TABLE IF NOT EXISTS `" + tableName + "` (" +
" `index` int(5) NOT NULL," +
" `station` int(5) NOT NULL," +
" PRIMARY KEY (`index`)," +
" UNIQUE KEY `station` (`station`)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
by design, TableName and ColumnNames cannot be parameterized.
If you are scared about SQL Injection, create a custom function to check for malicious tableName. It is safe if the value comes inside of your application.
Then concatenate it in the string, add backtick for first level of defense :D
String tableName = "Your tableName";
String query = "CREATE TABLE IF NOT EXISTS `" + tableName + "` (" +
" `index` int(5) NOT NULL," +
" `station` int(5) NOT NULL," +
" PRIMARY KEY (`index`)," +
" UNIQUE KEY `station` (`station`)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci";
You are missing Table name and i think that "?" shouldn't be there.
I will be something like
"CREATE TABLE IF NOT EXISTS YOURTABLE" + the following code

creating column family in cql?

when i create column family using the cql it gives me very unexpected output.
public static void createColumnfamily()
{
try
{
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
Connection con = DriverManager.getConnection("jdbc:cassandra://192.168.1.32:9160/temp");
String qry = "CREATE TABLE users(user_name varchar," +
"password varchar," +
"gender varchar," +
"session_token varchar," +
"birth_year bigint," +
"PRIMARY KEY (user_name)" +
")";
Statement smt = con.createStatement();
smt.executeUpdate(qry);
System.out.println("TABLE(column family) is created");
con.close();
}
catch(Exception e)
{
System.out.println(" : " + e.getMessage());
}
}
Here what i got : line 1:132 extraneous input ')' expecting EOF
You're using CQL 2, which does not support that style of primary key declaration. If you want to declare it that way, you should be using CQL 3, which you can accomplish by requesting that version in the connection URL:
DriverManager.getConnection("jdbc:cassandra://192.168.1.32:9160/temp?version=3.0.0");
However, CQL 3 isn't necessary just for this. As Steve Van Opstal suggested, you can simply put the PRIMARY KEY marker with the column definition itself, since you don't have a multi-component primary key.
CREATE TABLE users(
user_name varchar PRIMARY KEY,
password varchar,
gender varchar,
session_token varchar,
birth_year bigint,
);
CQL 3 is to be generally preferred if your Cassandra supports it, as it is the way forward, but in case you don't want to switch right now, you can make that second change.
I only see two possible problems here.
The query doesn't accept your way of defining the primary key
Try this:
String qry = "CREATE TABLE users(user_name varchar PRIMARY KEY," +
"password varchar," +
"gender varchar," +
"session_token varchar," +
"birth_year bigint"
")";
The query doesn't accept varchar's as primary key
Try this:
String qry = "CREATE TABLE users(user_id int" +
"user_name varchar," +
"password varchar," +
"gender varchar," +
"session_token varchar," +
"birth_year bigint," +
"PRIMARY KEY (user_id)" +
")";

Categories