Trying to add a new record to a data table in MySQL fails with an error message:
can not add or update a child row
I can do the same command manually in xampp and it works fine, but not when it runs under my app.
here is the Code, starting with the table "users" and then "transactions"
public void CreateUsersTable(){
try {
String SQL = "CREATE TABLE IF NOT EXISTS Users ("
+ "Username varchar(80) NOT NULL,"
+ "Userpassword varchar(80) ,"
+ "User_GSM VARCHAR(30),"
+ "User_Tel_Home VARCHAR(30),"
+ "User_Address Varchar(100), "
+ "User_City Varchar(20), "
+ "User_Position Varchar(100), "
+ "PRIMARY KEY(Username))";
//con = DBModule.ConnectDataBase.ConnectDataBase_Method();
statement = con.prepareStatement(SQL);
statement.executeUpdate();
} catch (SQLException ex) {
CustomControls.CustomTools.CustomMsgBox(ex.getMessage());
}
}
and the second table
public void CreateTransactionsTable(){
try {
String SQL = "CREATE TABLE IF NOT EXISTS Transactions ("
+ "TransactionsNum INT(18) NOT NULL AUTO_INCREMENT,"
+ "TransactionsDate DATE,"
+ "TransactionsAmount float(8), "
+ "TransactionsUsername varchar(80) ,"
+ "PRIMARY KEY(TransactionsNum) , "
+ "FOREIGN KEY(TransactionsUsername) REFERENCES Users(Username) )"; // foregign key is the key in this table to accessed from main calling
//con = DBModule.ConnectDataBase.ConnectDataBase_Method();
statement = con.prepareStatement(SQL);
statement.executeUpdate();
} catch (SQLException ex) {
CustomControls.CustomTools.CustomMsgBox(ex.getMessage());
}
}
and finally, this the statement to update the DB
String addTRansSQL = "insert into transactions ( TransactionsDate , TransactionsAmount , TransactionsUsername ) "
+ " values( '" + sqlDate + "' , '" + tramount + "' , ' " + loggeduser + "' )";
Simply, you're trying to add a transaction row with a user that doesn't exists in the Users table, try these line "SET FOREIGN_KEY_CHECKS=0"
Related
I get from "SQLiteLog: (1) near "Name": syntax error" after the addPatient() method is called and the data given by addPatient() method is not stored in the database.
At first, I suspect that something might be wrong with my "CREATE TABLE" query but I have tried everything and I couldn't figure out what was wrong.
#Override
public void onCreate(SQLiteDatabase db)
{
//===============Create a table for Patient
String query = "CREATE TABLE TABLE_PATIENT (COLUMN_ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"COLUMN_USERNAME TEXT, " +
"COLUMN_PASSWORD TEXT, " +
"COLUMN_FIRSTNAME TEXT, " +
"COLUMN_LASTNAME TEXT, " +
"COLUMN_AGE TEXT, " +
"COLUMN_GENDER TEXT, " +
"COLUMN_PHONE TEXT, " +
"COLUMN_ADDRESS TEXT);";
db.execSQL(query);
}//End of onCreate()
//Add a new Patient Row to the database
public void addPatient(Patient patient)
{
Log.i(TAG, "addPatient("+patient.getUserName()+")");
ContentValues values = new ContentValues();
values.put(COLUMN_ID, patient.getU_Id());
values.put(COLUMN_USERNAME, patient.getUserName());
values.put(COLUMN_PASSWORD, patient.getPassword());
values.put(COLUMN_FIRSTNAME, patient.getFirstName());
values.put(COLUMN_LASTNAME,patient.getLastName());
values.put(COLUMN_AGE, patient.getAge());
values.put(COLUMN_GENDER,patient.getGender());
values.put(COLUMN_PHONE,patient.getPhoneNumber());
values.put(COLUMN_ADDRESS, patient.getAddress());
SQLiteDatabase db = getWritableDatabase();
try
{
db.insert(TABLE_PATIENT, null, values);
db.close();
}catch (Exception e)
{
Log.i(TAG, e.getMessage());
}
}//End of addPatient()
I guess you have defined these variables:
String COLUMN_ID = "id";
String COLUMN_USERNAME = "username";
....................................
or something like that.
If you have spaces in the names of the columns you must use square brackets or backticks around them, like:
String COLUMN_USERNAME = "[user name]";
In your CREATE TABLE statement you define the column names as:
"COLUMN_ID", "COLUMN_USERNAME", ....
because you use the variable names and not their values.
But in addPatient() method you are putting values to the ContentValues object by using their actual names.
To solve your problem, 1st uninstall the app from the device you are testing it, so the database is deleted.
Then change the CREATE TABLE statement like this:
String query = "CREATE TABLE " + TABLE_PATIENT +" (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_USERNAME + " TEXT, " +
COLUMN_PASSWORD + " TEXT, " +
COLUMN_FIRSTNAME + " TEXT, " +
COLUMN_LASTNAME + " TEXT, " +
COLUMN_AGE + " TEXT, " +
COLUMN_GENDER + " TEXT, " +
COLUMN_PHONE + " TEXT, " +
COLUMN_ADDRESS + " TEXT)";
and rerun to recreate the database with the correct column names.
I'm trying to delete a row in my SQLite db in my app. It keeps on crashing with
no such column: ID (code 1)
I've tried
db.delete(TABLE_NAME, "ID=?", new String[]{Integer.toString(numID)});
but I still end up with the same
DB Structure:
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME +
" (ITEM_ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"NAME TEXT, " +
"PRICE INTEGER, " +
"DATE TEXT);");
}
Deletion query:
SQLiteDatabase db = this.getWritableDatabase();
String query = "DELETE FROM " + TABLE_NAME + " WHERE " + ITEM_ID + " = '" + Integer.toString(numID ) + "'";
db.execSQL(query);
My other select queries work perfectly fine so any help would be appreciated
You are trying to delete by ID, but your table uses ITEM_ID
change
db.delete(TABLE_NAME, "ID=?", new String[]{Integer.toString(numID)});
to
db.delete(TABLE_NAME, "ITEM_ID=?", new String[]{Integer.toString(numID)});
Wouldn't ITEM_ID need to be within the "", rather than a variable??
String query = "DELETE FROM " + TABLE_NAME + " WHERE ITEM_ID='" + Integer.toString(numID) + "'";
contactid = 123;
SYNC_SUCCESS = 1;
db.updateSyncStatus(contactid, SYNC_SUCCESS);
I have tried the 3 possible ways to update the table in SQLite DB. But its not working. INSERT and DELETE process are working good. Only I am facing problem in the UPDATE. Did I missed anything?
public void updateSyncStatus(String contactid, int syncSuccess) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues CV = new ContentValues();
CV.put(CONTACTS_SYNC_STATUS, syncSuccess);
try {
// db.update(TABLE_CONTACTS, CV, CONTACTS_CONTACTID + "='" + contactid + "'", null); // Tried, Not working
// db.update(TABLE_CONTACTS, CV, CONTACTS_CONTACTID +" = ?", new String[] {contactid}); // Tried, Not Working
db.update(TABLE_CONTACTS, CV, CONTACTS_CONTACTID + " = ?", new String[]{contactid});
}
catch (Exception e){
String error = e.getMessage().toString();
Log.e(TAG, "UpdateError: " + error);
}
db.close();
}
Table Structure:
String CREATE_CONTACTS_TABLE = "CREATE TABLE IF NOT EXISTS " + TABLE_CONTACTS + "("
+ CONTACTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+ CONTACTS_NUMBER + " VARCHAR,"
+ CONTACTS_CONTACTID + " VARCHAR,"
+ CONTACTS_SYNC_STATUS + " TINYINT DEFAULT 0" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
Actually the problem is not with the update query. The problem is , before executing the updateSyncStatus method, next statement ran and I am getting the output before updating the rows. So I have used the Handler to wait for 10 seconds before showing the output.
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
when i create column family using the cql it gives me very unexpected output.
public static void createColumnfamily()
{
try
{
Class.forName("org.apache.cassandra.cql.jdbc.CassandraDriver");
Connection con = DriverManager.getConnection("jdbc:cassandra://192.168.1.32:9160/temp");
String qry = "CREATE TABLE users(user_name varchar," +
"password varchar," +
"gender varchar," +
"session_token varchar," +
"birth_year bigint," +
"PRIMARY KEY (user_name)" +
")";
Statement smt = con.createStatement();
smt.executeUpdate(qry);
System.out.println("TABLE(column family) is created");
con.close();
}
catch(Exception e)
{
System.out.println(" : " + e.getMessage());
}
}
Here what i got : line 1:132 extraneous input ')' expecting EOF
You're using CQL 2, which does not support that style of primary key declaration. If you want to declare it that way, you should be using CQL 3, which you can accomplish by requesting that version in the connection URL:
DriverManager.getConnection("jdbc:cassandra://192.168.1.32:9160/temp?version=3.0.0");
However, CQL 3 isn't necessary just for this. As Steve Van Opstal suggested, you can simply put the PRIMARY KEY marker with the column definition itself, since you don't have a multi-component primary key.
CREATE TABLE users(
user_name varchar PRIMARY KEY,
password varchar,
gender varchar,
session_token varchar,
birth_year bigint,
);
CQL 3 is to be generally preferred if your Cassandra supports it, as it is the way forward, but in case you don't want to switch right now, you can make that second change.
I only see two possible problems here.
The query doesn't accept your way of defining the primary key
Try this:
String qry = "CREATE TABLE users(user_name varchar PRIMARY KEY," +
"password varchar," +
"gender varchar," +
"session_token varchar," +
"birth_year bigint"
")";
The query doesn't accept varchar's as primary key
Try this:
String qry = "CREATE TABLE users(user_id int" +
"user_name varchar," +
"password varchar," +
"gender varchar," +
"session_token varchar," +
"birth_year bigint," +
"PRIMARY KEY (user_id)" +
")";