SQLiteException: near "null": syntax error (code 1): , while compiling: create table - java

Please help me, i get this errors when i run my app use Idea
here is screen of error
http://prntscr.com/en3lcu
here is part of code where create table
private String getTableDDL(final Class<? extends GlassContract.Table> table) {
return getTableDDL(table, GlassContract.getTableName(table));
}
private String getTableDDL(final Class<? extends GlassContract.Table> table, String tableName) {
final StringBuilder sql = new StringBuilder(128);
sql.append("create table ").append(tableName).append(" (");
for (final Field field : table.getFields()) {
if (field.getName().startsWith("_") || field.isAnnotationPresent(Deprecated.class))
continue;
try {
sql.append(field.get(null));
} catch (Exception ignore) {
}
try {
final Field type = table.getDeclaredField("_SQL_" + field.getName() + "_TYPE");
sql.append(' ').append(type.get(null));
} catch (Exception ignore) {
sql.append(" TEXT");
}
sql.append(',');
}
try {
final Field type = table.getDeclaredField("_PK_COMPOSITE");
sql.append("PRIMARY KEY(").append(type.get(null)).append(")");
sql.append(',');
} catch (Exception ignore) {
// ignore
}
try {
final Field type = table.getDeclaredField("_UNIQUE_COMPOSITE");
sql.append("UNIQUE(").append(type.get(null)).append(")");
sql.append(',');
} catch (Exception ignore) {
// ignore
}
sql.setLength(sql.length() - 1); // chop off last comma
sql.append(')');
Log.v(TAG, "DDL for " + table.getSimpleName() + ": " + sql);
return sql.toString();
}
I please help me, because I break my head))

Are you really trying to create text fields in your table that are named null?
Even if this works (and I am not sure it does), you are duplicating this and creating two identically named fields called null

The first field in that CREATE TABLE statement doesn't have a proper name (it is "null"). That's why it blows up.
There's more fields with illegal names as well.

Related

Get ID of the room from Json

I need to get the ID of room by its name from JSONObject.
I uploaded Json file here: https://gitlab.com/JaroslavVond/json/blob/master/Json
So I know the name of the room (Kitchen1) and I need to write some function in Java that will return me the ID of the room (in this case "1").
Any ideas how to do that?
So far I have something like this:
private static String GetIdRoom(String room) {
String id = "";
JSONObject myResponse = SendHTTP("/groups", "GET", "");
try {
// some code to get ID of room
} catch (Exception ex) {
System.out.println("error - " + ex);
}
return null ;
}
Iterator<?> ids = myResponse.keys();
while( ids.hasNext() ) {
id = (String) ids.next();
if(myResponse.getJSONObject(id).getString("name").equals(room)){
return id;
}
}

Set private field with reflection works on static OR final, but not static final (combined)

I've got two UnitTest projects for my Android project. One for the JUnit Test and one for the Android Unit Tests. In the JUnit Test Project I've made a class to access or set private fields, methods or constructors. (PS: For the ones that are curious of the complete code, let me know and I'll add it to the bottom of this post.)
I also have UnitTests to test these private-method accessing. Right now all of these UnitTests work, accept for one: Setting the value of a final static field.
This is the method I use for setting a private field:
// Test method to set a private Field from a class
public static void setPrivateField(Object ob, String fieldName, Object value) throws MyUnitTestException{
try {
Field field = ob.getClass().getDeclaredField(fieldName);
if(field != null){
field.setAccessible(true);
if(Modifier.isFinal(field.getModifiers())){
Field modifierField = Field.class.getDeclaredField("modifiers");
modifierField.setAccessible(true);
modifierField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
/*int modifiers = field.getModifiers();
Field modifierField = field.getClass().getDeclaredField("modifiers");
modifiers = modifiers & ~Modifier.FINAL;
modifierField.setAccessible(true);
modifierField.setInt(field, modifiers);*/
}
// ** IllegalAccessException at the following line with final static fields:
field.set(ob, value); // static fields ignore the given Object-parameter
}
}
catch (NoSuchFieldException ex){
throw new MyUnitTestException(ex);
}
catch (IllegalAccessException ex){
throw new MyUnitTestException(ex);
}
catch (IllegalArgumentException ex){
throw new MyUnitTestException(ex);
}
}
And this is the UnitTest:
#Test
public void testSetIntFields(){
MyClass myClassInstance = new MyClass();
final int value = 5;
for(int nr = 1; nr <= 4; nr++){
String nameOfField = "myInt" + nr;
try {
TestMethodsClass.setPrivateField(myClassInstance, nameOfField, value);
}
catch (MyUnitTestException ex) {
Assert.fail("setPrivateField caused an Exception: " + ex.getThrownException());
}
int x = myClassInstance.getMyInt(nr);
Assert.assertTrue("myInt " + nr + " should be above 0", x > 0);
Assert.assertEquals("myInt " + nr + " should equal the set value (" + value + ")", value, x);
}
}
With the following MyClass:
#SuppressWarnings("unused")
public class MyClass
{
private int myInt1 = 0;
private static int myInt2 = 0;
private final int myInt3 = 0;
private static final int myInt4 = 0;
public MyClass(){ }
public int getInt(int nr){
switch(nr){
case 1:
return myInt1;
case 2:
return myInt2;
case 3:
return myInt3;
case 4:
return myInt4;
}
return -1;
}
}
(And the following MyUnitTestException):
public class MyUnitTestException extends Exception
{
private static final long serialVersionUID = 1L;
private Throwable thrownException;
public MyUnitTestException(Throwable ex){
super(ex);
thrownException = ex;
}
public String getThrownException(){
if(thrownException != null)
return thrownException.getClass().getName();
else
return null;
}
}
Setting the value to the fields myInt1, myInt2 and myInt3 works, but at myInt4 I'm getting an IllegalAccessException.
Does anyone know how I should fix this in my setPrivateField method? So it can not only set private, private static and private final fields, but also private static final ones.
EDIT 1:
After reading this article Forbidden Java actions: updating final and static final fields about in-lining at RunTime, I modified my UnitTest to this:
#Test
public void testSetIntFields(){
MyClass myClassInstance = new MyClass();
final int value = 5;
for(int nr = 1; nr <= 4; nr++){
String nameOfField = "myInt" + nr;
try {
TestMethodsClass.setPrivateField(myClassInstance, nameOfField, value);
}
catch (MyUnitTestException ex) {
Assert.fail("setPrivateField caused an Exception: " + ex.getThrownException());
}
// Get the set value using reflection
// WARNING: Since at RunTime in-lining occurs, we never use a Getter to test the set value, but instead use reflection again
int x = -1;
try {
x = (Integer)TestMethodsClass.getPrivateField(myClassInstance, nameOfField);
}
catch (MyUnitTestException ex) {
Assert.fail("getPrivateField caused an Exception: " + ex.getThrownException());
}
Assert.assertTrue("myInt " + nr + " should be above 0", x > 0);
Assert.assertEquals("myInt " + nr + " should equal the set value (" + value + ")", value, x);
}
}
(And this is my getPrivateField method, which is already completely tested and works):
// Test method to access a private Field from a class
public static Object getPrivateField(Object ob, String fieldName) throws MyUnitTestException{
Object returnObject = null;
try {
Field field = ob.getClass().getDeclaredField(fieldName);
if(field != null){
field.setAccessible(true);
returnObject = field.get(ob); // static fields ignore the given Object-parameter
}
}
catch (NoSuchFieldException ex) {
throw new MyUnitTestException(ex);
}
catch (IllegalAccessException ex) {
throw new MyUnitTestException(ex);
}
catch (IllegalArgumentException ex) {
throw new MyUnitTestException(ex);
}
return returnObject;
}
But I still get the same error.
EDIT 2:
Because I was using a getPrivateField in a UnitTest above it and tested all my UnitTests at the same time, it didn't worked. When I tested the UnitTest above separately it did work.. So I removed the getPrivateField-UnitTests (since in the code above I use both the Set and Get in one test) and now it does work.
I know this is very bad practice for UnitTests, but changing a private static final field during RunTime is already bad practice anyway. I just made the class to get and set private fields, methods and constructors, because I needed it about 3-4 times in some of my UnitTests and then I was just curious how far you can go with reflection and created a TestCase for everything I could think of. (Personally I find it a bit too far though.)
WARNING: Do not use reflection in any other case than tests. I don't recommend using it in your normal project, unless you've tried every other possible way. (I can't even think of a situation where you'd want to use reflection in your project, apart from tests.)
A primitive static final field is treated specially.
It is inlined as a constant by the compiler. The final executable does not access the field at runtime anymore.
A static final field is special-cased in the compiler, as its allowed to be inlined into any method that calls it.
It may not even exist in the end code.
static final int TEN = 10; // removed at compile time
int twenty() {
return TEN * 2; // compiler will turn this into 10*2 (and then probably 20 directly)
}

This codes can't check NoResultException

This is the Code I was made. It shouldn't get and enter to NoResultException, but it doesn't as expected. There is an unused data. I try to print out, here is the output : "[ ]"
private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
try {
int row = tableDataRangka.getSelectedRow();
String idRangka = tableDataRangka.getValueAt(row, 0).toString();
System.out.println( relasiRumahkayuRangkaDAO.getRelasiByIdRangka(idRangka).toString() );
} catch (NoResultException nre) {
// Doing something..
} catch (Exception ex) {
Logger.getLogger(MasterDataProjectUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here is the code of method "getRelasiByIdRangka" :
public List<RelasiRumahKayuRangka> getRelasiByIdRangka(String idRangka) throws Exception{
initEntityManager();
List<RelasiRumahKayuRangka> rrDrs = new ArrayList<>();
Query q = em.createNamedQuery("RelasiRumahKayuRangka.findByIdRangka");
q.setParameter("idRangka", idRangka);
rrDrs.addAll(q.getResultList());
closeEntityManager();
return rrDrs;
}
And this one is the JPA query, findByIdRangka :
#NamedQuery(name = "RelasiRumahKayuRangka.findByIdRangka", query = "SELECT r FROM RelasiRumahKayuRangka r WHERE r.relasiRumahKayuRangkaPK.idRangka = :idRangka"),
Do you guys know the solution, so the code can be catched by NoResultException ?
In your code. if the result set is empty then list will also be empty.
Make use of that situation and throw a desired exception.
In your getRelasiByIdRangka(String idRangka) add following changes.
public List<RelasiRumahKayuRangka>
getRelasiByIdRangka( String idRangka ) throws Exception {
initEntityManager();
// rest of the code here
// ...
// check if some results are found or not
if( rrDrs.isEmpty() ) { // or ( rrDrs.size() == 0 )
throw new NoResultException( "No results found" );
} // if empty
// this should be a filled in list
return rrDrs;
} // end of method

Database search with lucene

I'm using Lucene for querying a website's database but i'm experiencing some problems. I don't actually know if the problems come from indexing or searching (more precisely the construction of queries). Well, as far as i'm aware, when searching in several SQL database tables its better to use more than one document for each table (i followed these tutorials:
http://kalanir.blogspot.pt/2008/06/indexing-database-using-apache-lucene.html
http://www.lucenetutorial.com/techniques/indexing-databases.html
http://www.youtube.com/watch?v=jTDTYdU6nTc
) which are close to what i want to do. In fact, in my case i have to search in 3 tables which are all related because each one specifies the above level (e.g.: product -> type -> color). Thus, my indexing was something like this:
String sql = "select c.idConteudo as ID, c.designacao as DESIGNACAO, cd.texto as DESCRICAO, ctf.webTag as TAG from Conteudo c, ConteudoDetalhe cd, ConteudoTipoFormato ctf where c.idConteudo = cd.idConteudo AND cd.idConteudoTipoFormato = ctf.idConteudoTipoFormato;";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);
Document document;
while (rs.next())
{
String S = new String();
S += IndexerCounter;
document = new Document();
document.add(new Field("ID_ID",S, Field.Store.YES, Field.Index.NO));
document.add(new Field("ID CONTEUDO", rs.getString("ID"), Field.Store.YES, Field.Index.NO));
document.add(new Field("DESIGNACAO", rs.getString("DESIGNACAO"), Field.Store.NO, Field.Index.TOKENIZED));
document.add(new Field("DESCRICAO", rs.getString("DESCRICAO"), Field.Store.NO, Field.Index.TOKENIZED));
document.add(new Field("TAG", rs.getString("TAG"), Field.Store.NO, Field.Index.TOKENIZED));
try{
writer.addDocument(document);
}catch(CorruptIndexException e){
}catch(IOException e){
}catch(Exception e){ } //just for knowing if something is wrong
IndexerCounter++;
}
If i output the results they are something like this:
ID: idConteudo: designacao: texto: webTag
1:1:Xor:xor 1 Descricao:x or
2:1:Xor:xor 2 Descricao:xis Or
3:1:Xor:xor 3 Descricao:exor
4:2:And:and 1 Descricao:and
5:2:And:and 2 Descricao:&
6:2:And:and 3 Descricao:ande
7:2:And:and 4 Descricao:a n d
8:2:And:and 5 Descricao:and,
9:3:Nor:nor 1 Descricao:nor
10:3:Nor:nor 2 Descricao:not or
What i really want is to make a query for (for example Xor) and search it in the created documents for it. Thus my searching method is something like this:
Constructor:
public Spider(String Query, String Pathh) {
String[] Q;
QueryFromUser = new String();
QueryFromUser = Query;
QueryToSearch1 = new String();
QueryToSearch2 = new String();
Path = Pathh;
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
return;
}
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "");
} catch (SQLException e) {
e.printStackTrace();
return;
}
Q = Query.split(" ");
//NOTE: the AND word enables the search engine to search by the various words in a query
for (int i = 0; i < Q.length; i++) {
if ((Q.length - i) > 1) //prevents the last one to take a AND
{
QueryToSearch1 += Q[i] + " AND ";
} else {
QueryToSearch1 += Q[i];
}
}
for (int i = 0; i < Q.length; i++) {
QueryToSearch2 += "+" + Q[i];
}
try {
SEARCHING_CONTENT();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Spider.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(Spider.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Spider.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Spider.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParseException ex) {
Logger.getLogger(Spider.class.getName()).log(Level.SEVERE, null, ex);
}
SEARCHING_WEB(); //not for using now
} catch (CorruptIndexException ex) {
Logger.getLogger(Spider.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Spider.class.getName()).log(Level.SEVERE, null, ex);
}
The idea is that QueryToSearch1 and QueryToSearch2 has the commands (i saw it on an online tutorial, don't quite remember where) AND and +. Thus, to a query "not or" from the user, what will be searched it will be "not AND or" for searching for the two words simultaneously and "+not+or" for searching the two words separetly. This is one of my doubts, i don't really know if the construction of lucene queries are like this. The fact is that, in the method Querying:
private void SEARCHING_CONTENT() throws CorruptIndexException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException, ParseException {
Querying(QueryToSearch1); // search for the whole phrase
Querying(QueryToSearch2); //search by individual words
//Querying(QueryFromUser); //search by individual words
}
private void Querying(String QueryS) throws CorruptIndexException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException, ParseException {
searcher = new IndexSearcher(IndexReader.open(Path + "/INDEX_CONTENTS"));
query = new QueryParser("TAG", new StopWords()).parse(QueryS);
query.toString();
hits = searcher.search(query);
pstmt = connection.prepareStatement(sql);
for (int i = 0; i < hits.length(); i++) {
id = hits.doc(i).get("TAG");
pstmt.setString(1, id);
displayResults(pstmt);
}
}
there are no hits on the documents for the query. It is important to say that in the following line:
query = new QueryParser("TAG", new StopWords()).parse(QueryS);
the StopWords is a class i made that extents StandardAnalyser but its a new class with words i specified (for NOT removing important on my search words like or or and - in this case those words may be important).
The problem is, as i told. There are no hits when the search is performed. I'm not sure if this is because of the indexing or because of the construction of the queries to search (if the queries are bad constructed, thence, there are no hits).
I would apreciatte any help from anyone. I would gladly provide more information if needed.
Thanks a lot.
Easy first move for you - use Luke (https://code.google.com/p/luke/) to look on your index. You could run your queries from Luke to check, do they find something, or not.
Luke is pretty easy to understand, since it have very usefull UI (https://code.google.com/p/luke/source/browse/wiki/img/overview.png)

SQL Error when tried to enter data using netbeans

First, I'll give the codes I'm dealing with.
Action code for the "Save" Button.
private void saveBtActionPerformed(java.awt.event.ActionEvent evt) {
try {
Production production=new Production(batchNoValueLabel.getText(), productIDCombo.getSelectedItem(), rawMaterialUsedCombo.getSelectedItem(), dateValueLabel.getText(), rawMaterialBatchCombo.getSelectedItem(), weightInitialSpinner.getValue(), beforeWeightSpinner.getValue(), afterWeightSpinner.getValue(), finalWeightSpinner.getValue(), packingWeightSpinner.getValue(), noOfUnitSpinner.getValue(), wastageSpinner.getValue());
int res=ProductionController.addBatch(production);
if(res==1){
JOptionPane.showMessageDialog(this, "New Batch Added!");
String nextid = IDGeneration.getNextid("B", "production", "productionBatchID");
batchNoValueLabel.setText(nextid);
productIDCombo.removeAllItems();
ArrayList<String> getProductsDetails = ProductsController.getProductID();
for (String detail : getProductsDetails) {
productIDCombo.addItem(detail);
}
}else{
JOptionPane.showMessageDialog(this, "New Product Adding Failed!");
}
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(ProductsForm.class.getName()).log(Level.SEVERE, null, ex);
}
}
Then, the Model Class. (Getters and Setters are there, not pasted here)
public Production(String productionBatchID, Object finishedMaterialID, Object rawMaterialID, String productionDate, Object rawMatBatchID, Object initialWeight, Object beforeWeight, Object afterWeight, Object finalWeight, Object packingWeight, Object noOfUnits, Object wastage) {
this.productionBatchID = productionBatchID;
this.finishedMaterialID = (String) finishedMaterialID;
this.rawMaterialID = (String) rawMaterialID;
this.productionDate = productionDate;
this.rawMatBatchID = (String) rawMatBatchID;
this.initialWeight = (int) initialWeight;
this.beforeWeight = (int) beforeWeight;
this.afterWeight = (int) afterWeight;
this.finalWeight = (int) finalWeight;
this.packingWeight = (int) packingWeight;
this.noOfUnits = (int) noOfUnits;
this.wastage = (int) wastage;
}
And, finally the controller class.
public class ProductionController {
public static int addBatch(Production production) throws ClassNotFoundException, SQLException {
Connection conn=DBConnection.getConnection();
Statement stm=conn.createStatement();
String sql="insert into production (productionBatchID, finishedMaterialID, rawMaterialID, productionDate, rawMatBatchID, initialWeight, beforeWeight, finalWeight, packingWeight, noOfUnits, wastage) values ('"+production.getProductionBatchID()+"','"+production.getFinishedMaterialID()+"','"+production.getRawMaterialID()+"','"+production.getProductionDate()+"','"+production.getRawMatBatchID()+"','"+production.getInitialWeight()+"','"+production.getBeforeWeight()+"','"+production.getAfterWeight()+"','"+production.getFinalWeight()+"','"+production.getPackingWeight()+"','"+production.getNoOfUnits()+"','"+production.getWastage()+"');";
int rowCount=stm.executeUpdate(sql);
return rowCount;
}
}
And still, when I enter data in the GUI and try to send the data to the database, it gives out "java.sql.SQLException: Column count doesn't match value count at row 1" error. How to solve this? Oh, and here's the MySQL Table:
create table production(productionBatchID VARCHAR(4) NOT NULL,finishedMaterialID VARCHAR(4) NOT NULL,rawMaterialID VARCHAR(4) NOT NULL,productionDate VARCHAR(15),rawMatBatchID VARCHAR(4),initialWeight INT(5),beforeWeight INT(5),afterWeight INT(5),finalWeight INT(5),packingWeight INT(5),noOfUnits INT(5),wastage INT(5),CONSTRAINT PRIMARY KEY (productionBatchID))ENGINE=INNODB;
How to solve this?
Your VALUES clause has
'"+production.getAfterWeight()+"','"+production.getFinalWeight()+
But you only have finalWeight in the column list.
The error tells you this
insert into production (
productionBatchID, finishedMaterialID,
rawMaterialID, productionDate,
rawMatBatchID, initialWeight,
beforeWeight, finalWeight,
packingWeight, noOfUnits,
wastage)
values (
'"+production.getProductionBatchID()+"','"+production.getFinishedMaterialID()+"','"+
production.getRawMaterialID()+"','"+production.getProductionDate()+"','"+
production.getRawMatBatchID()+"','"+production.getInitialWeight()+"','"+
production.getBeforeWeight()+"','"+
production.getAfterWeight()+"','"+
production.getFinalWeight()+"','"+ there are 3 here
production.getPackingWeight()+"','"+production.getNoOfUnits()+"','"+
production.getWastage()+"');";
Also, parameterise your queries to mitigate SQL Injection risks please
There is mismatch in number of columns you are using in INSERT query, 'beforeWeight' is the column, whose values is missing, below is the corrected query:
String sql="insert into production (productionBatchID, finishedMaterialID, rawMaterialID, productionDate, rawMatBatchID, initialWeight, **beforeWeight**, finalWeight, packingWeight, noOfUnits, wastage) values ('"+production.getProductionBatchID()+"','"+production.getFinishedMaterialID()+"','"+production.getRawMaterialID()+"','"+production.getProductionDate()+"','"+production.getRawMatBatchID()+"','"+production.getInitialWeight()+"','"+production.getBeforeWeight()+"','"+production.getAfterWeight()+"','"+production.getBeforeWeight()+"','"+production.getFinalWeight()+"','"+production.getPackingWeight()+"','"+production.getNoOfUnits()+"','"+production.getWastage()+"');";

Categories

Resources