MySQL INSERT with duplicate support - java

I'm trying to use a MySQL database to save player information, but whenever there is a duplicate it will load (or save?) every player from the same player column.
Here's what I'm working with:
public boolean saveGame(String playerName, String playerPass) {
String player = "'" + playerName + "', '" + playerPass + "'";
String player2 = "`password` = '" + playerPass + "'";
String playerData = "'" + playerName + "', 'testtttt'";
String playerData2 = "`test` = 'testtttt'";
Server.getConnectionPool().executeUpdate("INSERT INTO player (username, password) VALUES (" + player + ") ON duplicate KEY UPDATE " + player2);
Server.getConnectionPool().executeUpdate("INSERT INTO playerdata (username, test) VALUES (" + playerData + ") ON duplicate KEY UPDATE " + playerData2);
return true;
}
public int loadGame(String name, String pass) {
ResultSet res = Server.getConnectionPool().executeQuery("SELECT * FROM player, playerdata WHERE player.username = '" + name + "'");
try {
name = res.getString("username");
if (!pass.equalsIgnoreCase(res.getString("password"))) {
return 3;
}
} catch (Exception e) {
e.printStackTrace();
}
return 1;
}
Here are the schemas (I removed the data from the example as it's not really needed, it doesn't load/save properly regardless):
Player:
image http://puu.sh/Alit.png
Playerdata:
image http://puu.sh/Aljr.png
I'm aware they'll be the same because I'm using the same string for the test field, but even if I do random ones or custom edit it in PHPMyAdmin it'll still save and then load from the same column. I think that it's saving because it seems to load the player properly, it's just not updating the proper column, which I don't know how to do. Inside the playerdata table all of the data for every single person is the same, and I don't know what's causing it, any ideas?

I have fixed this issue by changing the loading query to SELECT * FROM player as p, playerdata as pd WHERE p.username = '" + name + "' AND pd.username = '" + name + "'

If you want to insert duplicate record in your database, please remove primary key(username) from both tables.so you don't want to insert duplicate records, please use JDBC transactions.The following is sample usage;
Server.getConnectionPool().setAutoCommit(false);
Server.getConnectionPool().executeUpdate("INSERT INTO player (username, password) VALUES (" + player + ") ON duplicate KEY UPDATE " + player2);
Server.getConnectionPool().executeUpdate("INSERT INTO playerdata (username, test) VALUES (" + playerData + ") ON duplicate KEY UPDATE " + playerData2);
Server.getConnectionPool().commit();
Details usage can learn here.

Related

Checking before insert

I would like to check my first field and the second (CodeA, TitreA) and stop duplicates.
I don't know what to do.
public boolean insertAlbum (Album alb)
{
boolean ok = ConnexionMySQL.getInstance().actionQuery(
"Insert into album (CodeA, TitreA, SortieA, IdentC) values ('" +
alb.getCodeA() + "','" +
alb.getTitreA() + "'," +
alb.getSortieASQL() + "," +
alb.getChanteurAlb().getIdentC() + ")");
return ok;
}
Your database table should enforce uniqueness of that column combination. Add this to your database:
alter table album add constraint unique_code_titre unique (codea, titrea);
Then, if you try inserting the same combination, it will show you an error, and won't insert the new row.

Inserting Content Values in multiple tables in Sqlite Android Application

I am brand new to multiple tables in an SQLite database and am trying to find out what the best practices are for inserting values into multiple tables. My main question is do I need to Create another ContentValues object for inserting the values into a second table? I am really stumped on how to perform the insert(). Here is what I am trying so far.
Here are the two tables and schema
/* Creating a common attributes table here. */
private static final String CREATE_COMMON_ATTRIBUTES_TABLE = "create table "
+ COMMON_ATTRIBUTES_TABLE + "(" + DBColCons.UID_COMMON_ATTRIBUTES + " integer" +
" primary key autoincrement, " + DBColCons.GPS_POINT+ " integer not null, "
+ DBColCons.EXISTING_GRADE_GPS_POINT+ " integer not null, "
+ DBColCons.COVER+ " real not null, "+ DBColCons.NOTES+ " text, "
+ DBColCons.DATE+ " text)";
/* Creating a weld table here */
private static final String CREATE_WELD_TABLE = " create table " +WELD_TABLE+ "("
+ DBColCons.UID_WELD + " integer primary key, " + DBColCons.WELD_TYPE +
" text, " + DBColCons.WELD_ID + " text, " + DBColCons.DOWNSTREAM_JOINT +
" text, " + DBColCons.UPSTREAM_JOINT + " text, " + DBColCons.HEAT_AHEAD +
" text, " + DBColCons.LENGTH_AHEAD + " real, " + DBColCons.WALL_CHANGE +
" text, " + DBColCons.WELD_WALL_THICKNESS + " text, "
+ DBColCons.WELDER_INITIALS + " text, foreign key("+DBColCons.WELD_ID+") references" +
"("+DBColCons.GPS_POINT+"))";
Here is the method I am wanting to use for the insert() with some class getters() for the Weld class, which I am passing in as a parameter.
public boolean insertWeld(Weld weld) {
/* Get a writable copy of the database */
SQLiteDatabase db = this.getWritableDatabase();
/* Content values to insert with Weld class setters */
ContentValues contentValuesWeld = new ContentValues();
try {
contentValuesWeld.put(DBColCons.GPS_POINT, weld.getGpsPoint());
contentValuesWeld.put(DBColCons.WELD_TYPE, weld.getWeldType());
contentValuesWeld.put(DBColCons.WELD_ID, weld.getWeldId());
contentValuesWeld.put(DBColCons.DOWNSTREAM_JOINT, weld.getDownstreamJoint());
contentValuesWeld.put(DBColCons.UPSTREAM_JOINT, weld.getUpstreamJoint());
contentValuesWeld.put(DBColCons.HEAT_AHEAD, weld.getHeatAhead());
contentValuesWeld.put(DBColCons.LENGTH_AHEAD, weld.getLengthAhead());
contentValuesWeld.put(DBColCons.EXISTING_GRADE_GPS_POINT, weld.getExistingGradePoint());
contentValuesWeld.put(DBColCons.COVER, weld.getCover());
contentValuesWeld.put(DBColCons.WALL_CHANGE, weld.getWallChange());
contentValuesWeld.put(DBColCons.WELD_WALL_THICKNESS, weld.getWeldWallThickness());
contentValuesWeld.put(DBColCons.WELDER_INITIALS, weld.getWelderInitials());
contentValuesWeld.put(DBColCons.NOTES, weld.getNotes());
/* adding the date in here to the row. */
contentValuesWeld.put(DBColCons.DATE, String.valueOf(mStrDate));
/* Inserting into the weld table */
db.insertWithOnConflict(WELD_TABLE, DBColCons.WELDER_INITIALS, contentValuesWeld,
SQLiteDatabase.CONFLICT_NONE);
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
The values for DBColCons.GPS_POINT,DBColCons.EXISTING_GRADE_GPS_POINT,DBColCons.GPS_COVER and DBColCons.NOTES are what I want to insert into the Common_Attributes_Table. This is where I am really confused. Do I need to create a separate ContentValues object for those specific values and insert them into the desired table with a separate db.insert() method along with the one I am already using with the insert on the WELD_TABLE?
Help I am lost in this train wreck. Ha.
Thank you all.
You need to call insert() (or insertWithConflict()) for each table you are inserting values into. Unless the values are the same, this implies you will need another ContentValues per table.
If you intend for these inserts to be committed as a single atomic operation, consider using a transaction.
SQLiteDatabase db = ...;
db.beginTransaction();
try {
// do your inserts/etc. here
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}

Modifying the class level hashmap changes reflecting in local reference

I am trying to save insurance details to database based on insuranceid or updating if the insuranceid is already exists in the database. The problem is that when I am trying to save multiple insurance details it is giving ConcurrentModificationException. While debugging I found that 1st cycle it is ok that is 1st insurance details is successfully saving to database. But when next insurance details is storing it is giving the Exception. Another thing is that here I am modifying main HashMap(patientId,HashMap(insuranceId,InsuranceInfo)), and the changes are reflecting in local reference that is the id is adding to insuranceMap variable in the current method(). Please try to help me
this is my storing method...
public void storeInsuranceInformationToDataBase(int patientId) throws SQLException
{
//It gives arrayList of isuranceIds which are already in the data base.
ArrayList<Integer> insuranceIdsListInDatabase = getInsuranceIdsListInDatabase();
//It returns HashMap of insurance ids for given patient id.
HashMap<Integer, InsuranceInfo> insuranceMap = getInsuranceDetails(patientId);
Set<Integer> insuranceIdsInHashMap = insuranceMap.keySet();
//Here I am getting ConcurrentModificationException
for (int insuranceIdInHashMap : insuranceIdsInHashMap)
{
//Here I am comparing the both ids..
if (insuranceIdsListInDatabase.contains(insuranceIdInHashMap))
{
String updateInsuranceQuery = "UPDATE jp_InsuranceInfo SET typeOfPolicy='" + insuranceMap.get(insuranceIdInHashMap).getTypeOfPolicy() + "', amount=" + insuranceMap.get(insuranceIdInHashMap).getAmount() + ", duration=" + insuranceMap.get(insuranceIdInHashMap).getDuration()
+ ", companyName='" + insuranceMap.get(insuranceIdInHashMap).getCompanyName() + "' WHERE insuranceId=" + insuranceIdInHashMap + ";";
getDataBase().getStatement().executeUpdate(updateInsuranceQuery);
}
else
{
String insertInsuranceQuery = "INSERT INTO jp_InsuranceInfo VALUES(" + insuranceMap.get(insuranceIdInHashMap).getPatientId() + ",'" + insuranceMap.get(insuranceIdInHashMap).getTypeOfPolicy() + "'," + insuranceMap.get(insuranceIdInHashMap).getAmount() + ","
+ insuranceMap.get(insuranceIdInHashMap).getDuration() + ",'" + insuranceMap.get(insuranceIdInHashMap).getCompanyName() + "')";
getDataBase().getStatement().executeUpdate(insertInsuranceQuery);
ResultSet generatedInsuranceId = getDataBase().getStatement().executeQuery("SELECT SCOPE_IDENTITY()");
int newInsuranceId = 0;
if (generatedInsuranceId.next())
{
newInsuranceId = generatedInsuranceId.getInt(1);
}
//Here it returns an insurance object which contains insurance details
InsuranceInfo insuranceObject = insuranceMap.get(insuranceIdInHashMap);
insuranceObject.setInsuranceId(newInsuranceId);
//Here I am trying to store the newly inserted insurance object into main hashmap
storeInsuranceInfoToHashMap(patientId, insuranceObject);
//I am removing previous insurance object with temporary insurance id
getInsuranceMap().get(patientId).remove(insuranceIdInHashMap);
// Adding newly generated insurance id to array list
getInsuranceIdsListInDatabase().add(newInsuranceId);
}
}
Well, nothing strange. You trying to add a new item into the Map object while you're iterating through it.
My advise would be trying to save the insurance data you created when iterating through the Map into a temporary Map object. And, after you finished iterating the Map. Then, you could save the temporary map into the initial map.
example :
public void storeInsuranceInformationToDataBase(int patientId) throws SQLException
{
//It gives arrayList of isuranceIds which are already in the data base.
ArrayList<Integer> insuranceIdsListInDatabase = getInsuranceIdsListInDatabase();
//It returns HashMap of insurance ids for given patient id.
HashMap<Integer, InsuranceInfo> insuranceMap = getInsuranceDetails(patientId);
Map<Integer, InsuranceInfo> tempInsuranceMap = new HashMap<>();
Set<Integer> insuranceIdsInHashMap = insuranceMap.keySet();
//Here I am getting ConcurrentModificationException
for (int insuranceIdInHashMap : insuranceIdsInHashMap)
{
//Here I am comparing the both ids..
if (insuranceIdsListInDatabase.contains(insuranceIdInHashMap))
{
String updateInsuranceQuery = "UPDATE jp_InsuranceInfo SET typeOfPolicy='" + insuranceMap.get(insuranceIdInHashMap).getTypeOfPolicy() + "', amount=" + insuranceMap.get(insuranceIdInHashMap).getAmount() + ", duration=" + insuranceMap.get(insuranceIdInHashMap).getDuration()
+ ", companyName='" + insuranceMap.get(insuranceIdInHashMap).getCompanyName() + "' WHERE insuranceId=" + insuranceIdInHashMap + ";";
getDataBase().getStatement().executeUpdate(updateInsuranceQuery);
}
else
{
String insertInsuranceQuery = "INSERT INTO jp_InsuranceInfo VALUES(" + insuranceMap.get(insuranceIdInHashMap).getPatientId() + ",'" + insuranceMap.get(insuranceIdInHashMap).getTypeOfPolicy() + "'," + insuranceMap.get(insuranceIdInHashMap).getAmount() + ","
+ insuranceMap.get(insuranceIdInHashMap).getDuration() + ",'" + insuranceMap.get(insuranceIdInHashMap).getCompanyName() + "')";
getDataBase().getStatement().executeUpdate(insertInsuranceQuery);
ResultSet generatedInsuranceId = getDataBase().getStatement().executeQuery("SELECT SCOPE_IDENTITY()");
int newInsuranceId = 0;
if (generatedInsuranceId.next())
{
newInsuranceId = generatedInsuranceId.getInt(1);
}
//Here it returns an insurance object which contains insurance details
InsuranceInfo insuranceObject = insuranceMap.get(insuranceIdInHashMap);
insuranceObject.setInsuranceId(newInsuranceId);
//Here I am trying to store the newly inserted insurance object into main hashmap
storeInsuranceInfoToHashMap(patientId, insuranceObject); <-- make this function to save those information into the temporary map
//I am removing previous insurance object with temporary insurance id
getInsuranceMap().get(patientId).remove(insuranceIdInHashMap);
// Adding newly generated insurance id to array list
getInsuranceIdsListInDatabase().add(newInsuranceId);
}
}
insuranceMap.putAll(tempInsuranceMap);
}

Android - SQlite insert not inserting

So i am trying to insert some data in the internal sqlite database but after i run the insert no data has been added. There are, as far as i can see no errors in the logs and every debug log i put into it is shown. If i try to run the query that is returned in the log in sqlitestudio it works without a problem so i haven't got a clue as to what is going wrong.
#Override
public void onCreate(SQLiteDatabase db) {
String SQL = pictureTable();
db.execSQL(SQL);
}
private String pictureTable() {
return "CREATE TABLE geophoto_db_pictures ( picid integer,"
+ "name varying character(50),"
+ "city varying character(20) NOT NULL,"
+ "zipcode varying character(20) NOT NULL,"
+ "country varying character(20) NOT NULL,"
+ "picdate datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,"
+ "tags varying character(200),"
+ "image varying character(200) NOT NULL,"
+ "uploaded integer NOT NULL DEFAULT 0, PRIMARY KEY (picid))";
}
#Override
public void savePicture(Picture pic) {
Log.d(LOG_TAG, "saving picture started. Data: " + pic.getName());
// clean the inputs
String name = pic.getName();
String city = pic.getCity();
if (city != null) {
city = "'" + city + "'";
}
String country = pic.getCountry();
if (country != null) {
country = "'" + country + "'";
}
String zip = pic.getZipcode();
if (zip != null) {
zip = "'" + zip + "'";
}
String tags = tagsToString(pic.getTags());
String image = pic.getImage();
// Insert Query, all possible null values on "not null" rows will be
// replaced by a default value.
String SQL = "INSERT INTO geophoto_db_pictures(name, city, zipcode, country, tags, image)"
+ "VALUES('"
+ name
+ "',"
+ "IFNULL("
+ city
+ ", 'Unknown')"
+ ","
+ "IFNULL("
+ zip
+ ", 'Unknown')"
+ ","
+ "IFNULL("
+ country + ",'Unknown')" + ",'" + tags + "','" + image + "')";
Log.d(LOG_TAG, SQL);
executeWriteQuery(SQL);
ArrayList<Picture> list = getAllPictures();
Log.d(LOG_TAG, "Size :"+list.size());
}
private Cursor executeWriteQuery(String query){
Log.d(LOG_TAG, "execute write query");
SQLiteDatabase db = getWritableDatabase();
Cursor response = db.rawQuery(query, null);
Log.d(LOG_TAG, "write query executed");
return response;
}
All tips/help greatly appreciated!
Thomas
Try to put a semicolon at the end of table creation query. In your case as show below
private String pictureTable() {
return "CREATE TABLE geophoto_db_pictures ( picid integer,"
+ "name varying character(50),"
+ "city varying character(20) NOT NULL,"
+ "zipcode varying character(20) NOT NULL,"
+ "country varying character(20) NOT NULL,"
+ "picdate datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,"
+ "tags varying character(200),"
+ "image varying character(200) NOT NULL,"
+ "uploaded integer NOT NULL DEFAULT 0, PRIMARY KEY (picid));";
}
While providing a query through an external String, you will need to provide SQL query with an end of statement ;. Using the primitive SQLite does not require ; as it just takes arguments and create function query itself. I have experienced both cases and I ended up understanding the way I have put it here.
The problem you are facing is that you are trying to use rawQuery() to insert a record, when you should be using execSQL() instead (see this answer).
So, the correct code for executeWriteQuery would be as follows:
private void executeWrite(String command){
Log.d(LOG_TAG, "execute write");
SQLiteDatabase db = getWritableDatabase();
db.execSQL(command);
Log.d(LOG_TAG, "write executed");
}
Also, consider using insert() instead as that will allow you to get a return value to determine whether or not the data was inserted successfully.

My ResultSet will only print first row

I have a ResultSet that I know contains 8 rows of data because I checked it with a direct query of the DB. My code will only display the first row.
If anyone can give me some help I would greatly appreciate it. The first row is what should I expect it to be, I just don't know how to get it to move on to print subsequent rows.
term= Integer.parseInt(args[1]);
// Select a list of the surveys that fall under the term
query= "Select cid,subject,course_number,instructor_id from Courses where term=" + Integer.parseInt(args[1]);
result = statement.executeQuery(query);
String query2="";
while(result.next())
{
// Pull in the data
cid = result.getInt("cid");
subject = result.getString("subject");
courseNumber= result.getInt("course_number");
instructorId= result.getInt("instructor_id");enter code here
// Get the instructors last name
query2= "Select last_name from Instructors where fid=" + instructorId;
subResult= statement.executeQuery(query2);
while(subResult.next())
{
instructorLName= subResult.getString(1);
}
// Get the averages and num submitted
query2= "Select num_submitted, sum_q1, sum_q2, sum_q3, sum_q4, survey_id from surveys where cid=" + cid;
subResult= statement.executeQuery(query2);
while(subResult.next())
{
numSub= subResult.getInt(1);
sumQ1= subResult.getInt(2);
sumQ2= subResult.getInt(3);
sumQ3= subResult.getInt(4);
sumQ4= subResult.getInt(5);
surveyId= subResult.getInt(6);
}
// Print everything necessary
System.out.println( surveyId + " " + term + " " + subject + " " + courseNumber +
" " + instructorLName + " " + sumQ1/numSub + " " + sumQ2/numSub + " " + sumQ3/numSub
+ " " + sumQ4/numSub);
}
}
Not sure, but the problem might be that you are using same Statement object to execute different queries. Create separate statement instances for query and query2 and try.

Categories

Resources