I'm using JDBC in eclipse IDE , i want to put two foreign keys in my table 3 , one is referencing to the primary key in table 1 and one is referencing to the primary key in table 2. When i only put one foreign key constrains for any referencing table1 or table 2 , it works fine but when i include two it gives me sql exception as stated below:
java.sql.SQLSyntaxErrorException: 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 'foreign key(T2) references
Table2(T2) )' at line 1
String createString =
// TABLE 1
"CREATE TABLE " + this.tableName + " ( " +
"T1 varchar(50) NOT NULL PRIMARY KEY )";
// TABLE 2
"CREATE TABLE " + this.tableName + " ( " +`enter code here`
"T2 varchar(50) NOT NULL PRIMARY KEY )";
// TABLE 3
"CREATE TABLE " + this.tableName + " ( " +
"T1 varchar(50) " +
"T2 varchar(50) " +
"foreign key(T1) references Table1 (T1)" +
"foreign key(T2) references Table2(T2) )";
First, this is actually a MySQL question, unrelated to Java/JDBC. Secondly, and more importantly, you don't appear to be using the correct syntax, which would be...
CREATE TABLE TableName (
T1 varchar(50),
T2 varchar(50),
foreign key(T1) references Table1(T1),
foreign key(T2) references Table2(T2)
);
Formatted for your code, it would look like this:
String createString = "CREATE TABLE " + this.tableName + " ( " +
" T1 varchar(50)," +
" T2 varchar(50)," +
" foreign key(T1) references Table1(T1)," +
" foreign key(T2) references Table2(T2));";
You were missing commas after each item in the items list for your CREATE TABLE statement.
In my app, i'm using subquerys of sqlite, the subquery returns 3 values, its ok, but in the main query, returns empty and i need help in this.
*some parts of variables is in portuguese because i'm brazilian.
public List<Table_Anuncio_Empregador> getAllUser_Empregador() {
SQLiteDatabase db = this.getReadableDatabase();
List<Table_Anuncio_Empregador> anuncios = new ArrayList<Table_Anuncio_Empregador>();
SharedPreferences preferences = context.getSharedPreferences("user_preferences", MODE_PRIVATE);
int user_id = preferences.getInt("user_id_conectado",0);
String selectQuery = "SELECT "+KEY_ID+", "+KEY_IMAGEM_ANUNCIO+", "+KEY_TITULO+", "+KEY_DESCRICAO+", "+KEY_CIDADE
+ " FROM " + TABLE_ANUNCIO_EMPREGADOR
+ " WHERE "+ KEY_ID +" IN (SELECT "+KEY_ANUNCIO_EMPREGADOR_ID+" FROM "+ TABLE_ANUNCIO
+" WHERE "+ KEY_ANUNCIO_PERFIL+" = 'empregador' AND "+ KEY_USER_ID+" = "+user_id+")";
Log.e(LOG, selectQuery);
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
Table_Anuncio_Empregador anuncio = new Table_Anuncio_Empregador();
anuncio.setAnuncio_empregador_id(c.getInt(c.getColumnIndex(KEY_ID)));
anuncio.setImagem_do_anuncio(c.getBlob(c.getColumnIndex(KEY_IMAGEM_ANUNCIO)));
anuncio.setTitulo(c.getString(c.getColumnIndex(KEY_TITULO)));
anuncio.setDescricao(c.getString(c.getColumnIndex(KEY_DESCRICAO)));
anuncio.setCidade(c.getString(c.getColumnIndex(KEY_CIDADE)));
anuncios.add(anuncio);
} while (c.moveToNext());
}
return anuncios;
}
The LOG shows the query as :-
E/Banco_Helper: SELECT ID, Imagem_anuncio, Titulo, Descricao, Cidade FROM Anuncio_empregador WHERE ID IN (SELECT Anuncio_empregado_info_ID FROM Anuncio WHERE Anuncio_perfil = 'empregador' AND User_ID = 2)
The tables are created using :-
private static final String CREATE_TABLE_ANUNCIO =
"CREATE TABLE IF NOT EXISTS " + TABLE_ANUNCIO + "(" + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
KEY_USER_ID + " INTEGER NOT NULL," +
KEY_ANUNCIO_PERFIL + " TEXT NOT NULL," +
KEY_ANUNCIO_EMPREGADOR_ID + " INTEGER," +
KEY_ANUNCIO_PRESTADOR_ID + " INTEGER," +
KEY_CREATED_AT + " DATETIME NOT NULL" + ")";
and :-
private static final String CREATE_TABLE_ANUNCIO_EMPREGADOR =
"CREATE TABLE IF NOT EXISTS " + TABLE_ANUNCIO_EMPREGADOR + "(" + KEY_ID + " INTEGER PRIMARY KEY," +
KEY_TITULO + " TEXT NOT NULL," +
KEY_DESCRICAO + " TEXT NOT NULL," +
KEY_BAIRRO + " TEXT NOT NULL," +
KEY_CIDADE + " TEXT NOT NULL," +
KEY_ESTADO + " TEXT NOT NULL," +
KEY_LOCAL_SERVICO + " TEXT NOT NULL," +
KEY_EXIGENCIAS + " TEXT," +
KEY_IMAGEM_ANUNCIO + " BLOB NOT NULL" + ")";
Equating to :-
CREATE TABLE IF NOT EXISTS Anuncio(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
USER_ID INTEGER NOT NULL,
Anuncio_perfil TEXT NOT NULL,
Anuncio_empregado_info_ID INTEGER,
ANUNCIO_PRESTADOR_ID INTEGER,
CREATED_AT DATETIME NOT NULL
);
And :-
CREATE TABLE IF NOT EXISTS Anuncio_empregador (
ID INTEGER PRIMARY KEY,
Titulo TEXT NOT NULL,
Descricao TEXT NOT NULL,
Bairro TEXT NOT NULL,
Cidade TEXT NOT NULL,
Estado TEXT NOT NULL,
Local_Servico TEXT NOT NULL,
Exigencias TEXT,
Imagem_anuncio BLOB NOT NULL
);
I believe that your issue is with the actual data rather then the query.
That is, the following was used to create and populate the two tables and to also run the query (plus some intermediate queries). The result was that the three expected rows were included and that the three rows that should have been excluded were. That is the query in question ran with the expected results.
The following SQL was used :-
DROP TABLE IF EXISTS Anuncio;
CREATE TABLE IF NOT EXISTS Anuncio(
ID INTEGER PRIMARY KEY AUTOINCREMENT,
USER_ID INTEGER NOT NULL,
Anuncio_perfil TEXT NOT NULL,
Anuncio_empregado_info_ID INTEGER,
ANUNCIO_PRESTADOR_ID INTEGER,
CREATED_AT DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);
DROP TABLE IF EXISTS Anuncio_empregador;
CREATE TABLE IF NOT EXISTS Anuncio_empregador (
ID INTEGER PRIMARY KEY,
Titulo TEXT NOT NULL,
Descricao TEXT NOT NULL,
Bairro TEXT NOT NULL,
Cidade TEXT NOT NULL,
Estado TEXT NOT NULL,
Local_Servico TEXT NOT NULL,
Exigencias TEXT,
Imagem_anuncio BLOB NOT NULL DEFAULT X'00010203040506070809'
)
;
INSERT INTO Anuncio_empregador
(Titulo,Descricao,Bairro,Cidade,Estado,Local_Servico,Exigencias)
VALUES
('Mr','Albert','Bloggs','something','something else','xxx','xxxx'),
('Mr','Bert','Bloggs','something','something else','xxx','xxxx'),
('Mr','Charlie','Bloggs','something','something else','xxx','xxxx'),
('Mr','Dave','Bloggs','something','something else','xxx','xxxx'),
('Mr','Eddie','Bloggs','something','something else','xxx','xxxx'),
('Mr','Fred','Bloggs','something','something else','xxx','xxxx'),
('Mr','George','Bloggs','something','something else','xxx','xxxx')
;
SELECT * FROM Anuncio_empregador;
INSERT INTO Anuncio
(USER_ID, Anuncio_perfil,Anuncio_empregado_info_ID,ANUNCIO_PRESTADOR_ID)
VALUES
(1,'empregador',1,100),
(2,'empregador',2,100),
(3,'empregador',3,100),
(4,'not an empregador',1,100),
(5,'not an empregador',2,100),
(6,'not an empregador',3,100)
;
SELECT * FROM Anuncio;
SELECT * FROM Anuncio WHERE Anuncio_perfil = 'empregador';
SELECT ID,Imagem_anuncio,Titulo,Descricao,Cidade
FROM Anuncio_empregador
WHERE ID IN
(
SELECT Anuncio_empregado_info_ID
FROM ANUNCIO
WHERE ANUNCIO_PERFIL = 'empregador' AND USER_ID = user_id
)
;
Note that some liberties were taken, like
using the CURRENT_TIMESTAMP and
using X'00010203040506070809'
saving having to repeat these values which would have no impact upon workings of the SQL.
The resultant Anuncio_empregador table being :-
The resultant Anuncio table being :-
i.e. last 3 rows have been set to be excluded according to the clause WHERE ANUNCIO_PERFIL = 'empregador'
The result of the query in Question
SELECT ID,Imagem_anuncio,Titulo,Descricao,Cidade
FROM Anuncio_empregador
WHERE ID IN
(
SELECT Anuncio_empregado_info_ID
FROM ANUNCIO
WHERE ANUNCIO_PERFIL = 'empregador' AND USER_ID = user_id
)
;
being :-
Note changing AND USER_ID = user_id to AND USER_ID = 2 shows just the 1 row for Bert, as expected.
I am creating a bus table with an event to maintain th data. Is it possible to drop the table and the autoDelete event by DropBusEvent event if no records exist in the bus table?
stt.execute("CREATE TABLE IF NOT EXISTS bus"
+ "(id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY,"
+ "mac VARCHAR(30) NOT NULL UNIQUE,"
+ "route int(11) NOT NULL,"
+ "latitude FLOAT(10,6) NOT NULL,"
+ "longitude FLOAT(10,6) NOT NULL,"
+ "created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
stt.execute("CREATE EVENT IF NOT EXISTS AutoDelete "
+ "ON SCHEDULE EVERY 3 MINUTE "
+ "DO "
+ "DELETE FROM bus WHERE created_at < (NOW() - INTERVAL 3 MINUTE)");
// I tried this statement here but it does not work.
stt.execute("CREATE EVENT IF NOT EXITS DropBusTable "
+ "Do "
+ "DROP TABLES IF EXISTS bus");
I am getting 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 'EXITS DropBusTableDROP TABLES IF EXISTS bus' at line 1
You have a mistake in your syntax:
EXITS instead of EXISTS
in the line
stt.execute("CREATE EVENT IF NOT EXITS DropBusTable "
I am trying to make a variable Table name through Java.
My code is :
public void createTable(String tableName){
try {
Statement stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE '"+tableName+"'" +
"(id INTEGER not NULL, " +
" username VARCHAR(255), " +
" pass VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))");
}
catch (SQLException e){
e.printStackTrace();
}
}
It gives me a syntax error saying:
Incorrect syntax near 'VariableTableNameIChose'.
Does anyone have any ideas?
It could be one of 2 things or the combination of both.
Maybe the single quotes around the table name are not valid in your database. So do like this:
stmt.executeUpdate("CREATE TABLE "+tableName+" " +
"(id INTEGER not NULL, " +
" username VARCHAR(255), " +
" pass VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))");
Or maybe you need a spaces between the table name and the ( following after:
Statement stmt = con.createStatement();
// v this one was missing
stmt.executeUpdate("CREATE TABLE '"+tableName+"' " +
"(id INTEGER not NULL, " +
" username VARCHAR(255), " +
" pass VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))");
The table name is an identifier. Identifiers do not use single quotes (in standard SQL).
"CREATE TABLE '"+tableName+"' "
Will result in
CREATE TABLE 'foobar'
which is invalid SQL. You need to remove the single quotes:
"CREATE TABLE "+tableName+" " + ...
As the table name is apparently a user input, you might actually want to use quoted identifiers (although this is in general a bad idea). Identifiers are quoted using double quotes in the SQL standard:
"CREATE TABLE \""+tableName+"\" " + ...
The first 2 go through without a hitch, but when I try to do the last one, I get this error message:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (corejava., CONSTRAINT #sql-8b8_50_ibfk_2 FOREIGN KEY (call_Number) REFERENCES book (call_Number))
There has got to be a way around this right?
Please see corrected code below: For any other newbies out there, my transaction call_Number INSERT field had incorrect values (tiny, minor, incorrect values!!!!)
s.executeUpdate (
"CREATE TABLE transaction ("
+ "patron_ID CHAR(10) NOT NULL,"
+ "call_Number CHAR(10) NOT NULL, check_Out_Date DATE NOT NULL, check_In_Date DATE NOT NULL,"
+ "PRIMARY KEY (patron_ID, call_Number),"
+ "overdue CHAR(15), total_Charge FLOAT)");
count3 = s.executeUpdate (
"INSERT INTO transaction"
+ " VALUES"
+ "('P222200000','MY.111.000','2011-06-06','2011-06-12','yes',5.00),"
+ "('P222200001','MY.111.001','2011-07-06','2011-07-12','no',5.00),"
+ "('P222200002','SF.111.002','2011-08-06','2011-08-12','yes',5.00),"
+ "('P222200003','SF.111.003','2011-09-06','2011-09-12','no',5.00),"
+ "('P222200004','AV.111.004','2011-10-06','2011-10-12','yes',5.00),"
+ "('P222200005','AV.111.005','2011-11-06','2011-11-12','no',5.00),"
+ "('P222200006','CO.111.006','2011-12-06','2011-12-12','yes',5.00),"
+ "('P222200007','CO.111.007','2011-01-06','2011-01-12','no',5.00),"
+ "('P222200008','IN.111.008','2011-02-06','2011-02-12','yes',5.00),"
s.executeUpdate(
"ALTER TABLE transaction ADD FOREIGN KEY (patron_ID) references " + dbName + ".patron (patron_ID)");
s.executeUpdate (
"ALTER TABLE patron ADD FOREIGN KEY (call_Number) references " + dbName + ".book (call_Number)");
s.executeUpdate (
"ALTER TABLE transaction ADD FOREIGN KEY (call_Number) references " + dbName + ".book (call_Number)");