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+"') ");
Related
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.
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
I have an xml file as shown in the picture. I want two things, first, I want to insert pre-defined values in my sqlite database on onCreate method using an arraylist (or any method). Then secondly, I want to use those values from the arraylist, now in my database, to populate the two spinners(Producer and Product).
I have a database file that handles the db connections and methods and this is what I have done so far. This code is inside my onCreate method
db.execSQL("CREATE TABLE " + TABLE_PRODUCT + "("
+ PRODUCT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + PRODUCT_NAME + " TEXT,"
+ PRODUCER_FK + " INTEGER" + " FOREIGN KEY(PRODUCER_FK) REFERENCES TABLE_PRODUCER(PRODUCER_ID))");
ContentValues contentv=new ContentValues();
contentv.put("name", "Soya Seed");
getWritableDatabase().insert("TABLE_PRODUCT", null, contentv);
db.execSQL("CREATE TABLE " + TABLE_PRODUCER + "("
+ PRODUCER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + PRODUCER_NAME + " TEXT,"
+ PRODUCER_ADDRESS + " TEXT,"
+ PRODUCER_PHONE + " TEXT UNIQUE," + PRODUCER_EMAIL + " TEXT,"
+ CONTACT_PERSON + " TEXT" + ")");
ContentValues cv=new ContentValues();
cv.put("name", "ZamSEED");
cv.put("address", "Luanda");
cv.put("phone", "+244977654321");
cv.put("email", "demo#zamseed.com");
cv.put("contact_name", "Mr. Tembo");
getWritableDatabase().insert("TABLE_PRODUCER", null, cv);
Then I have an inventory file that reads from the database to get values from the product and producers tables to populate the spinners.
My challenge is how can I tell if my db.execSQL is actually successful?
And how would I use an arraylist to insert values in the database?
NOTE: the app runs fine when I ran it but I am not sure if the tables are created and values inserted. Am a newbie to Android programming, thanks.
After some time of research into this, I found this article here that led me to see the actual tables of my db.execSQL command and the data contained. In Ubuntu:
cd /path/to/my/sdk/platform-tools
./adb shell
run-as <app package name>
cd /data/data/<app package name>/databases
ls
chmod 666 <database file name>
sqlite3 <database file name>
> (semi-colon terminated commands can be run here to query the data)
> .exit
(copy full database path)
exit
Then use sqlite3 commands to work on database > (semi-colon terminated commands can be run here to query the data)
DatabaseHelper.java
public ArrayList<String>getProductList(){
ArrayList<String>products = new ArrayList<String>();
SQLiteDatabase qDB = getReadableDatabase();
String columns[]=new String[]{PRODUCT_NAME};
Cursor cursor = qDB.query(TABLE_PRODUCT,columns,null,null,null,null,null);
while (cursor.moveToNext()){
String produectName = cursor.getString(1);
products.add(productName);
Log.e("e",products);
}
return products;
}
SomeActivity.java
spinnerProducts = (Spinner) findViewById(R.id.spinnerProducts);
ArrayList<String>productsList = new DatabaseHelper(context).getProductsList();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context,android.R.layout.simple_list_item_1,productsList);
spinnerProducts.setAdapter(arrayAdapter);
...
//same logic for Producers list
My challenge is how can I tell if my db.execSQL is actually successful?
It was successful if it did not throw an exception.
However calling getWritableDatabase() in onCreate() is an error since that results in recursion: getWritableDatabase() triggers a call to onCreate() in the first place. You should use the SQLiteDatabase passed to you as a param instead.
If you did not see an exception about the recursive call then you already had a database file with the correct version. You can uninstall your app to clean up its data and then install and run it again to make onCreate() run again.
And how would I use an arraylist to insert values in the database?
Use a loop to iterate the list and insert values one by one.
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;
}
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.