How to create a database dynamically a from a variable? - java

I have a string called str_train_no and i want to create a database with the same name and so far i have tried
String name=str_Train_no+".db";
SQLiteDatabase traindb = openOrCreateDatabase(name,SQLiteDatabase.CREATE_IF_NECESSARY , null);
sql="CREATE TABLE IF NOT EXISTS "+str_Train_no+" ("
+"Stops VARCHAR);";
traindb.execSQL(sql);
Heres the Source code for the database declaration and insertion part
SQLiteDatabase db = openOrCreateDatabase( "Train_list.db", SQLiteDatabase.CREATE_IF_NECESSARY , null);
try {
final String CREATE_TABLE_TRAIN_LIST = "CREATE TABLE IF NOT EXISTS Train_list ("
+ "Train_name VARCHAR,"
+ "Train_no VARCHAR,"
+ "Train_start VARCHAR,"
+ "Train_end VARCHAR,"
+ "Seats_Available VARCHAR);";
db.execSQL(CREATE_TABLE_TRAIN_LIST);
Toast.makeText(admin_manipulation.this, "Table created", Toast.LENGTH_LONG).show();
String sql = "INSERT or replace INTO Train_list (Train_name, Train_no, Train_start, Train_end, Seats_Available) VALUES('"+str_Train_name + "',' " +str_Train_no + "', '" +str_Train_start+"','" +str_Train_end+"',' " +str_Train_seats +"');";
db.execSQL(sql);
Toast.makeText(admin_manipulation.this, "Inserted Sucessfully", Toast.LENGTH_SHORT).show();
String name=str_Train_no+".db";
SQLiteDatabase traindb = openOrCreateDatabase(name, SQLiteDatabase.CREATE_IF_NECESSARY , null);
sql="CREATE TABLE IF NOT EXISTS "+str_Train_no+" ("
+"Stops VARCHAR);";
traindb.execSQL(sql);
Toast.makeText(admin_manipulation.this, "Table "+str_Train_no+" verified", Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(admin_manipulation.this, "An Error has occured", Toast.LENGTH_SHORT).show();
}
and this keeps throwing an exception.
Any ideas why?
Thanks in advance!

With str_train_no beeing a numerical string you have the problem that you try to create a table with a name which is no valid SQL identifier.
In this particular case you can solve it by prefixing it with a text string like:
sql = "CREATE TABLE IF NOT EXISTS train"+str_Train_no+ ...
In your case you can also use a static table name, since you create one database per train (which might not be the best thing to do).

use text instead of varchar. as I know there is not varchar in SQLite.

Related

show "No Title" if a column in SQLite is empty

I made a note app and I give users an option to leave the title of their note empty. But in RecyclerView and Toolbar title is shown and in this case it's empty. I tried to give value to that column while creating the table but it doesn't work.
Here's the code to create table:
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + DATABASE_TABLE + "(" +
ID + " INTEGER PRIMARY KEY," +
TITLE + " TEXT DEFAULT 'No Title'," +
CONTENT + " TEXT," +
DATE + " TEXT," +
TIME + " TEXT" + ")";
db.execSQL(query);
}
UPDATE:
Save method in adding note:
private void saveNote() {
if (TextUtils.isEmpty(title.getText()) && TextUtils.isEmpty(content.getText())) {
Toast.makeText(this, "Please write Something in your note", Toast.LENGTH_SHORT).show();
} else {
NotePad notePad = new NotePad(title.getText().toString(), content.getText().toString(), currentDate, currentTime);
Database database = new Database(this);
database.addNote(notePad);
Toast.makeText(this, "Note Saved!", Toast.LENGTH_LONG).show();
moveToList();
}
}
add note method in database:
void addNote(NotePad notePad) {
SQLiteDatabase database = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TITLE, notePad.getTitle());
cv.put(CONTENT, notePad.getContent());
cv.put(DATE, notePad.getDate());
cv.put(TIME, notePad.getTime());
database.insert(DATABASE_TABLE, null, cv);
}
In the method addNote() you should not set a value in the ContentValues object for TITLE if it is empty, so SQLite will set the column's value to the default value:
void addNote(NotePad notePad) {
SQLiteDatabase database = this.getWritableDatabase();
cv = new ContentValues();
if (!TextUtils.isEmpty(notePad.getTitle())) cv.put(TITLE, notePad.getTitle());
cv.put(CONTENT, notePad.getContent());
cv.put(DATE, notePad.getDate());
cv.put(TIME, notePad.getTime());
database.insert(DATABASE_TABLE, null, cv);
}
Use IFNULL while fetching data . For example
Select IFNULL(“TITLE”,”NO TITLE”) from table...

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

Android: Retrieve data from sqlite Database

I currently I have my database set up like the following:
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_LOCKERNUMBER
+ " TEXT NOT NULL, " + KEY_STATUS + " INTEGER, " + KEY_PIN
+ " INTEGER);");
And I am trying to write a method to get the pin code from the column for a specific locker number. Any ideas? I am very new I would like think I would need to use the query function and a cursor. I just one to get the integer value and store it into an int variable so I can compare the pin codes from what the user types in to the one in the database.
Queries to database returns in a Cursor object. You should use the db.query() method to get a row(s). Pass the table name, an array of columns you want to get (or null if you want all of them), pass a selection string that should be like "id = ?" or "key > ?", etc, then pass a String array containing the value for those ? inside the previous string,
and finally pass null for having, groupBy and orderBy unless you want to use them.
Cursor cursor = db.query(TABLE_NAME, new String[] { KEY_ROWID }, "id = ?", new String[] { Integer.toString(id) }, null, null, null);
After you get the Cursor, do cursor.moveToFirst() or cursor.moveToPosition(0) (can't remember the exact method, but the point is to move the cursor to the first retrieved row)
then you're going to iterate through the cursor with
while(cursor.moveToNext()) {
int keyRowIdColumnIndex = cursor.getColumnIndex(KEY_ROWID);
int yourValue = cursor.getInt(keyRowIdColumnIndex);
int keyLockNumberColumnIndex = cursor.getColumnIndex(KEY_LOCKNUMBER);
int pin = cursor.getInt(keyLockNumberColumnIndex);
}
This is a pretty straight forward task and there is a bunch of tutorials, examples, similar questions on SO:
How to perform an SQLite query within an Android application?
In general - you need to query the database passing your search arguments. See the documentation.
It will return you a Cursor with the matching results, which you can then iterate over and manipulate as you wish.
Fyi - storing password in a database table is a bad idea. On Android databases can be accessed and easily read. You either need to encrypt your data or think of another way to store it if it's important.
//Try This code
public String getLabeId(String LockNo)
{
ArrayList<String> Key_Pin_array = new ArrayList<String>();
Cursor cur = db.rawQuery("SELECT * FROM DATABASE_TABLE where KEY_LOCKERNUMBER = '" + LockNo + "'", null);
try {
while (cur.moveToNext())
{
System.out.println("Key_Pin" + cur.getString(3));
Key_Pin_array.add(cur.getString(3));
}
}
catch (Exception e)
{
System.out.println("error in getLabelID in DB() :" + e);
}
finally
{
cur.close();
}
return id;
}

How so I use variables in an execSQL()?

I'm trying to take some values stored from EditText fields and store them into my SQLLite DB.
I have the following String variables:
site_name
_address
_user
_pass
Here is the Sql command I'm trying to use:
SQLiteDatabase db = openOrCreateDatabase("SiteManager", MODE_PRIVATE,
null);
db.execSQL("CREATE TABLE IF NOT EXISTS SiteTable (Name VARCHAR, Address VARCHAR, Usernname VARCHAR, Password VARCHAR, PORT INT(4), Passive BIT);");
db.execSQL("INSERT INTO SiteTable VALUES ('" + site_name + "','"
+ _address + "','" + _user + "','" + _pass + "'," + _port + ","
+ _passive + ");");
I'm checking the value like this in another Activity:
SQLiteDatabase db = openOrCreateDatabase("SiteManager",
MODE_PRIVATE, null);
Cursor c = db.rawQuery("SELECT * FROM SiteTable", null);
c.moveToFirst();
Toast.makeText(this, c.getString(c.getColumnIndex("Name")),
Toast.LENGTH_LONG).show();
db.close();
In the debugger it's showing c as not having any values but the column names are there. So this makes me think there's something wrong with the way I'm trying to use variables in my SQL statement. What am I doing wrong?
If you're using the standard Android binding, whose Javadoc is here, then you can find the right code to call by looking at the Javadoc for an overload of execSQL. See SQLiteDatabase.html#execSQL(String, Object[]).
Now, the Javadoc says that execSQL is not to be used for SELECT/INSERT/UPDATE/DELETE. Instead, there are three insertXXX methods, each of which takes additional data in a ContentValues object. So, you construct that object, which looks like a Map, with the new row's data.
This is the answer you are searching
sqLiteDatabase.execSQL("insert into userTable (username,name,password,email)
values('"+username+"','"+name+"','"+password+"','"+email+"') ");

Android SQLite ordering table columns differently

I'm setting up an SQLite Database and I've got most things set up how I think they're supposed to be. The main error has to with a column not being where it should be. I initialized the database column names in strings like so:
public static final String KEY_ROWID = "_id";
public static final String KEY_SPORT = "given_sport";
public static final String KEY_NAME = "given_name";
public static final String KEY_DATE = "given_date";
public static final String KEY_TIME = "given_time";
public static final String KEY_PERIOD = "given_period";
public static final String KEY_LOCATION = "given_location";
When it was time to create a table with the column names:
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_SPORT + " TEXT NOT NULL, " +
KEY_NAME + " TEXT NOT NULL, " +
KEY_DATE + " TEXT NOT NULL, " +
KEY_TIME + " TEXT NOT NULL, " +
KEY_PERIOD + " TEXT NOT NULL, " +
KEY_LOCATION + "TEXT NOT NULL);"
);
The problem now is that I'm getting the following error:
05-27 04:13:01.448: E/Database(273): android.database.sqlite.SQLiteException: table groupTable has no column named given_location: , while compiling: INSERT INTO groupTable(given_location, given_time, given_date, given_period, given_sport, given_name) VALUES(?, ?, ?, ?, ?, ?);
It seems like the table names are being reordered and that's what is causing the error in insertion. I'm clueless though and I'd really appreciate some help with this.
EDIT: here's the INSERT command
ContentValues cv = new ContentValues();
cv.put(KEY_SPORT, sportInput);
cv.put(KEY_NAME, nameInput);
cv.put(KEY_DATE, dateInput);
cv.put(KEY_TIME, timeInput);
cv.put(KEY_PERIOD, periodInput);
cv.put(KEY_LOCATION, locationInput);
return dbSQL.insert(DATABASE_TABLE, null, cv);
The problem is probably that you've changed the database structure but not the database version. It's a weird issue that I had to spend a lot of time figuring out the first time.
In your DatabaseHelper class there should be a version number, just increment it by one anytime you change any table schema etc.
EDIT
You're missing a space before the "TEXT" in your SQL table creation.
It should be:
...
+ KEY_LOCATION+ " TEXT" ...
once you fix that, increment the version number again.
The order of the table columns will not create "no column" error. If you have added the column to your table after running your app at least once but haven't incremented the database version, this is one way to cause this error.
The order of these columns:
INSERT INTO groupTable(given_location, given_time, given_date, given_period, given_sport, given_name) ...
depends on the order of the columns when you write your INSERT statement, it is not a fixed order based off of the CREATE command.

Categories