I have written a query to insert values into a database in Android:
db.execSQL("CREATE TABLE " + TABLE_NAME + "( " + KEY_SITUATION_NAME
+ " TEXT NOT NULL, " + KEY_CATEGORY_NAME + " TEXT NOT NULL,"
+ KEY_LATTIUDE +" NOT NULL," + KEY_LONGITUDE + " NOT NULL," + " );");
However, when I execute it, an error is thrown. Can anyone point out the error in it?
db.execSQL("CREATE TABLE " + TABLE_NAME + "( " + KEY_SITUATION_NAME
+ " TEXT NOT NULL, " + KEY_CATEGORY_NAME + " TEXT NOT NULL,"
+ KEY_LATTIUDE +" INTEGER NOT NULL," + KEY_LONGITUDE + " INTEGER NOT NULL" + " );");
Provide a Datatype to KEY_LATITUDE and to KEY_LONGITUDE.
And also you have kept a (,) at last which was not needed...
the correct code is:
db.execSQL("CREATE TABLE " + TABLE_NAME + "( " + KEY_SITUATION_NAME
+ " TEXT NOT NULL, " + KEY_CATEGORY_NAME + " TEXT NOT NULL," + KEY_LATTIUDE +" NOT NULL," + KEY_LONGITUDE + " NOT NULL," + " )");
db.execSQL("CREATE TABLE " + TABLE_NAME + "( " + KEY_SITUATION_NAME
+ " TEXT NOT NULL, " + KEY_CATEGORY_NAME + " TEXT NOT NULL,"
+ KEY_LATTIUDE +" NOT NULL," + KEY_LONGITUDE + " NOT NULL);");
Related
as i am working on a minecraft server some plugin does not make a certain table itself.
For who is interested: https://www.spigotmc.org/resources/craftconomy.2395/
But in the github files i found the java script where it does generate the needed table.
public final String createTableMySQL = "CREATE TABLE IF NOT EXISTS " + getPrefix() + TABLE_NAME + " (" +
" `" + BALANCE_FIELD + "` double DEFAULT NULL," +
" `" + WORLD_NAME_FIELD + "` varchar(255)," +
" `username_id` int(11)," +
" `" + CURRENCY_FIELD + "` varchar(50)," +
" PRIMARY KEY (" + WORLD_NAME_FIELD + ", username_id, currency_id)," +
" CONSTRAINT `"+getPrefix()+"fk_balance_account`" +
" FOREIGN KEY (username_id)" +
" REFERENCES " + getPrefix() + AccountTable.TABLE_NAME + "(id) ON UPDATE CASCADE ON DELETE CASCADE," +
" CONSTRAINT `"+getPrefix()+"fk_balance_currency`" +
" FOREIGN KEY (" + CURRENCY_FIELD + ")" +
" REFERENCES " + getPrefix() + CurrencyTable.TABLE_NAME +"(name) ON UPDATE CASCADE ON DELETE CASCADE" +
") ENGINE=InnoDB CHARSET=utf8;";
Could someone help me to make a SQL query out of this, which just can be dropped into PHPMyadmin?
Thanks already for reading.
I already solved it myself, no reason for reaction anymore.
Im attempting to create 2 tables, but I dont fully understand where Im going wrong. It's obviously a syntax error, and Im new to SQL in general, can someone explain to me what Im doing wrong here?
String query = "CREATE TABLE IF NOT EXISTS " + tableName + " (" +
"uuid CHAR(36) NOT NULL," +
" team_name VARCHAR(255) NOT NULL," +
" BOOLEAN manager NOT NULL," +
" BOOLEAN team_chat NOT NULL," +
" PRIMARY KEY (uuid))";
String query2 = "CREATE TABLE IF NOT EXISTS " + secondTableName + " (" +
"team_name VARCHAR(255) NOT NULL," +
" team_password VARCHAR(255) NOT NULL" +
" BOOLEAN friendly_fire NOT NULL," +
" VARCHAR(255) hq," +
" VARCHAR(255) rally," +
" PRIMARY KEY (team_name))";
This is my stacktrace:
WARN 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 'manager NOT NULL, BOOLEAN team_chat NOT NULL, PRIMARY KEY (uuid))' at line 1
Code used to execute:
private void createTables(String tableName, String secondTableName) throws SQLException {
try {
checkConnection();
} catch (Exception e) {
e.printStackTrace();
}
try {
String query = "CREATE TABLE IF NOT EXISTS " + tableName + " (" +
"uuid CHAR(36) NOT NULL," +
" team_name VARCHAR(255) NOT NULL," +
" BOOLEAN manager NOT NULL," +
" BOOLEAN team_chat NOT NULL," +
" PRIMARY KEY (uuid))";
String query2 = "CREATE TABLE IF NOT EXISTS " + secondTableName + " (" +
"team_name VARCHAR(255) NOT NULL," +
" team_password VARCHAR(255) NOT NULL" +
" BOOLEAN friendly_fire NOT NULL," +
" VARCHAR(255) hq," +
" VARCHAR(255) rally," +
" PRIMARY KEY (team_name))";
PreparedStatement preparedStatement = connection.prepareStatement(query);
PreparedStatement preparedStatement2 = connection.prepareStatement(query2);
preparedStatement.execute();
preparedStatement2.execute();
main.getLogger().log(Level.INFO, "Tables " + tableName + " and " + secondTableName + " were successfully created.");
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
}
The problem is presence of MAX in the table definition. VARCHAR expects a number as an argument so you either need to define MAX as variable and pass it (from Java) or just replace MAX with a number, e.g.:
String query = "CREATE TABLE IF NOT EXISTS " + tableName + " (" +
"uuid CHAR(36) NOT NULL," +
" team_name VARCHAR( + " + MAX + ") NOT NULL," +
" BOOLEAN manager NOT NULL," +
" BOOLEAN team_chat NOT NULL," +
" PRIMARY KEY (uuid))";
OR
String query = "CREATE TABLE IF NOT EXISTS " + tableName + " (" +
"uuid CHAR(36) NOT NULL," +
" team_name VARCHAR(255) NOT NULL," +
" BOOLEAN manager NOT NULL," +
" BOOLEAN team_chat NOT NULL," +
" PRIMARY KEY (uuid))";
If you do not know the max length then you can use LONGTEXT as type.
Also, we need to fix the ordering of type and column names, it needs to be manager BOOLEAN and not BOOLEAN manager, e.g.:
String query = "CREATE TABLE IF NOT EXISTS " + tableName + " (" +
"uuid CHAR(36) NOT NULL," +
" team_name VARCHAR(255) NOT NULL," +
" manager BOOLEAN NOT NULL," +
" team_chat BOOLEAN NOT NULL," +
" PRIMARY KEY (uuid))";
String query2 = "CREATE TABLE IF NOT EXISTS " + secondTableName + " (" +
"team_name VARCHAR(255) NOT NULL," +
" team_password VARCHAR(255) NOT NULL" +
" friendly_fire BOOLEAN NOT NULL," +
" hq VARCHAR(255)," +
" rally VARCHAR(255)," +
" PRIMARY KEY (team_name))";
The column name has to come before the data type. So
BOOLEAN manager NOT NULL,
BOOLEAN team_chat NOT NULL,
should be
manager BOOLEAN NOT NULL,
team_chat BOOLEAN NOT NULL,
I have this onCreate method in my SQLiteOpenHelper
class, and I would like to add a unique constraint on these two columns (composite unique columns):
SongContract.SongEntry.COLUMN_TITLE
SongContract.SongEntry.COLUMN_RELEASEDATE
But I am getting an error:
Cannot resolve method UNIQUE
Here is my code:
public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_SONG_TABLE = "CREATE TABLE " + SongContract.SongEntry.TABLE_SONG + " (" +
SongContract.SongEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
SongContract.SongEntry.COLUMN_TITLE + " TEXT NOT NULL, " +
SongContract.SongEntry.COLUMN_RELEASEDATE + " INTEGER, " +
UNIQUE(SongContract.SongEntry.COLUMN_TITLE, SongContract.SongEntry.COLUMN_RELEASEDATE) +
SongContract.SongEntry.COLUMN_RATING + " TEXT);";
db.execSQL(SQL_CREATE_SONG_TABLE);
}
What is the correct syntax to achieve my goal?
I found the corrrect syntax after playing around sqllite:
final String SQL_CREATE_SONG_TABLE = "CREATE TABLE " + SongContract.SongEntry.TABLE_SONG + " (" +
SongContract.SongEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
SongContract.SongEntry.COLUMN_TITLE + " TEXT NOT NULL, " +
SongContract.SongEntry.COLUMN_RELEASEDATE + " INTEGER NOT NULL, " +
SongContract.SongEntry.COLUMN_RATING + " TEXT, " + "UNIQUE" + "(" +
SongContract.SongEntry.COLUMN_TITLE + "," + SongContract.SongEntry.COLUMN_RELEASEDATE + ") " + ");";
I am trying to get all the values in a table that have column _parentbook set to a certain value. When I try to retrieve the entries I get the error shown below.
E/SQLiteLog: (1) table recipes has no column named _parentbook
E/SQLiteDatabase: Error inserting _parentbook=Test _recipemethod=Stir in pot for 20 mins _recipeingredients=No bugs, freedom _recipedescription=Test recipe _recipename=Recipe 1 in Test _recipenotes=Do on Android Studio
The error refers to the method below that I use to add a recipe to the database
public void addRecipe(Recipe recipe) {
ContentValues values = new ContentValues();
values.put(COLUMN_RECIPE_NAME, recipe.getRecipeTitle());
values.put(COLUMN_RECIPE_DESCRIPTION, recipe.getRecipeDescription());
values.put(COLUMN_RECIPE_INGREDIENTS, recipe.getIngredients());
values.put(COLUMN_RECIPE_METHOD, recipe.getMethod());
values.put(COLUMN_RECIPE_NOTES, recipe.getNotes());
//values.put(COLUMN_IMAGE_ID, recipe.getImageId());
values.put(COLUMN_PARENT_BOOK, recipe.getParentBook());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_RECIPES, null, values);
db.close();
}
Code used to initialise TABLE_RECIPES:
String CREATE_TABLE_RECIPES = "CREATE TABLE IF NOT EXISTS " + TABLE_RECIPES + " (" +
COLUMN_ID_2 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_RECIPE_NAME + " TEXT, " +
COLUMN_RECIPE_DESCRIPTION + " TEXT, " +
COLUMN_RECIPE_INGREDIENTS + " TEXT, " +
COLUMN_RECIPE_METHOD + " TEXT, " +
COLUMN_RECIPE_NOTES + " TEXT, " +
COLUMN_IMAGE_ID + " INTEGER " +
COLUMN_PARENT_BOOK + " TEXT" +
");";
#Override
public void onCreate(SQLiteDatabase db) {
Log.e(TAG, "OnCreate() called");
db.execSQL(CREATE_TABLE_RECIPES);
}
Method for getting the recipes from the table:
List<Recipe> recipes;
public List<Recipe> getRecipes(String bookName) {
recipes = new ArrayList<>();
SQLiteDatabase db = getWritableDatabase();
//String query = "SELECT "+ COLUMN_PARENT_BOOK +" FROM " + TABLE_RECIPES + " WHERE " + COLUMN_PARENT_BOOK + "=" + bookName;
String query = "SELECT * FROM " + TABLE_RECIPES;// + " WHERE 1";
// Cursor going to point to a location in the results
Cursor c = db.rawQuery(query, null);
// Move it to the first row of your results
c.moveToFirst();
if (c.moveToFirst()) {
do {
if (c.getString(c.getColumnIndex(COLUMN_RECIPE_NAME)) != null) {
recipes.add(new Recipe(
c.getString(c.getColumnIndex(COLUMN_RECIPE_NAME)),
c.getString(c.getColumnIndex(COLUMN_RECIPE_DESCRIPTION)),
c.getString(c.getColumnIndex(COLUMN_RECIPE_INGREDIENTS)),
c.getString(c.getColumnIndex(COLUMN_RECIPE_METHOD)),
c.getString(c.getColumnIndex(COLUMN_RECIPE_NOTES)),
// Add image here if required
c.getString(c.getColumnIndex(COLUMN_PARENT_BOOK))
));
}
} while (c.moveToNext());
}
db.close();
//c.close();
return recipes;
}
I have tried upgrading the database version and looking at other similar questions on StackOverflow, neither helped.
Thanks.
You forgot to put comma(,) in create table statement.
Instead of
String CREATE_TABLE_RECIPES = "CREATE TABLE IF NOT EXISTS " + TABLE_RECIPES + " (" +
COLUMN_ID_2 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_RECIPE_NAME + " TEXT, " +
COLUMN_RECIPE_DESCRIPTION + " TEXT, " +
COLUMN_RECIPE_INGREDIENTS + " TEXT, " +
COLUMN_RECIPE_METHOD + " TEXT, " +
COLUMN_RECIPE_NOTES + " TEXT, " +
COLUMN_IMAGE_ID + " INTEGER " +
COLUMN_PARENT_BOOK + " TEXT" +
");";
It should be
String CREATE_TABLE_RECIPES = "CREATE TABLE IF NOT EXISTS " + TABLE_RECIPES + " (" +
COLUMN_ID_2 + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_RECIPE_NAME + " TEXT, " +
COLUMN_RECIPE_DESCRIPTION + " TEXT, " +
COLUMN_RECIPE_INGREDIENTS + " TEXT, " +
COLUMN_RECIPE_METHOD + " TEXT, " +
COLUMN_RECIPE_NOTES + " TEXT, " +
COLUMN_IMAGE_ID + " INTEGER, " + // Here you forgot to put comma(,) in this line
COLUMN_PARENT_BOOK + " TEXT" +
");";
I'm trying to update a row in my database. Here is the code I am trying to use to update:
public void addFBComments(int id){
SQLiteDatabase db = this.getWritableDatabase();
String query = "UPDATE " + TABLE_FB_FEED + " SET " + COL_FB_COMMENTS+"="+"HELLO" + " WHERE " + COL_FB_ID+"="+id;
db.execSQL(query);
}
When I run the command, it throws this error:
08-18 15:42:10.145: E/AndroidRuntime(10493): FATAL EXCEPTION: Thread-922
08-18 15:42:10.145: E/AndroidRuntime(10493): android.database.sqlite.SQLiteException: no such column: HELLO (code 1): , while compiling: UPDATE fb_feed SET fb_comments= HELLO WHERE _id=3
Here is the TABLE_FB_FEED:
private static final String TABLE_FB_FEED_CREATE = "create table " + TABLE_FB_FEED +
" ("
+ COL_FB_ID + " integer primary key autoincrement not null,"
+ COL_FB_MESSAGE + " text,"
+ COL_FB_CAPTION + " text,"
+ COL_FB_POSTER_ID + " text,"
+ COL_FB_POST_ID + " text,"
+ COL_FB_LIKES + " text,"
+ COL_FB_POSTER_NAME + " text,"
+ COL_FB_COMMENTS + " text," // this is the column i want to update
+ COL_FB_LIKES_NUM + " text,"
+ COL_FB_TIMESTAMP + " text,"
+ COL_FB_PROFILE_PICTURE_URI + " text,"
+ COL_FB_PICTURE_URI + " text,"
+ COL_FB_NAME + " text,"
+ COL_FB_PREVIOUS_PAGE_URI + " text,"
+ COL_FB_NEXT_PAGE_URI + " text,"
+ COL_FB_POST_TYPE + " text,"
+ COL_FB_LINK_NAME + " text,"
+ COL_FB_COMMENTS_NUM + " text,"
+ COL_FB_STORY + " text,"
+ COL_FB_DESCRIPTION + " text,"
+ COL_FB_COMMENTS_BEFORE + " text,"
+ COL_FB_COMMENTS_AFTER + " text,"
+ COL_FB_LIKES_PROFILE_PIC + " text,"
+ COL_FB_COMMENTS_PROFILE_PIC + " text);";
Why is it throwing the query? I thought I was doing everything correctly.
in your code you need to add single quotes:
String query = "UPDATE " + TABLE_FB_FEED + " SET " + COL_FB_COMMENTS
+"="+"'HELLO'" + " WHERE " + COL_FB_ID+"="+id
or
String query = "UPDATE " + TABLE_FB_FEED + " SET " + COL_FB_COMMENTS
+"='HELLO' WHERE " + COL_FB_ID+"="+id
this is another example
"UPDATE DB_TABLE SET YOUR_COLUMN='newValue' WHERE id=myidValue");
In SQL, string values must be quoted:
String query = "..." + COL_FB_COMMENTS+"= 'HELLO' WHERE ...";
Anyway, formatting problems such as this (which get worse when the string itself contains quotes) can be avoided by using parameters:
String query = "... SET " + COL_FB_COMMENTS+"= ? WHERE " + COL_FB_ID+"="+id;
db.execSQL(query, new Object[] { "HELLO" });
You need to escape your String literal,
String query = "UPDATE " + TABLE_FB_FEED + " SET " + COL_FB_COMMENTS
+"="+"HELLO" + " WHERE " + COL_FB_ID+"="+id
Could be
String query = "UPDATE " + TABLE_FB_FEED + " SET " + COL_FB_COMMENTS
+"="+"'HELLO'" + " WHERE " + COL_FB_ID+"="+id
Or, you could use a bind parameter.
something like
String query = "UPDATE " + TABLE_FB_FEED + " SET " + COL_FB_COMMENTS+"="+"'HELLO'" + " WHERE " + COL_FB_ID+"="+id;
would work