No value specified for parameter Java application with database - java

I have an application with a list of people and you can change the info of one certain person when you click on a button. So I am trying to update my database but it says that I do not have a value for the 7th parameter, however I do have 7 values. When I print it, it does give me 7 values. It doesn't have a problem with the null (in my if else) because I already tried it without that.
This is my msql
CREATE TABLE Persoon(
persoonId int(3) NOT NULL AUTO_INCREMENT,
leeftijd int(3),
voornaam varchar(40) NOT NULL,
achternaam varchar (40) NOT NULL,
datum date,
locatieId int(3),
filmId int(3) NOT NULL,
PRIMARY KEY (persoonId),
FOREIGN KEY (filmId) references Film(filmId),
FOREIGN KEY (locatieId) references Locatie(locatieId));
My java code
private void btnWijzigenActionPerformed(java.awt.event.ActionEvent evt) {
Object geselecteerdeObject = lstPersonen.getSelectedValue();
Persoon geselecteerdePersoon = (Persoon) geselecteerdeObject;
if(txtLeeftijd.getText() != ""){
try {
String string = txtDatum.getText();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
Date datumString = format.parse(string);
Persoon nieuwePersoon = new Persoon(geselecteerdePersoon.getPersoonId(),Integer.parseInt(txtLeeftijd.getText()), txtVoornaam.getText(), txtAchternaam.getText(),datumString,geselecteerdePersoon.getLocatieId(),geselecteerdePersoon.getFilmId());
System.out.println("1p "+geselecteerdePersoon.getPersoonId() + " 2p " +Integer.parseInt(txtLeeftijd.getText()) + " 3p "+txtVoornaam.getText() + " 4p " + txtAchternaam.getText() + " 5p " + datumString + " 6p "+ geselecteerdePersoon.getLocatieId()+ " 7p " +geselecteerdePersoon.getFilmId());;
PersoonDao.updatePersoon(nieuwePersoon);
} catch (ParseException ex) {
Logger.getLogger(HoofdGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
else{
Persoon nieuwePersoon = new Persoon(geselecteerdePersoon.getPersoonId(),0, txtVoornaam.getText(), txtAchternaam.getText(),null,geselecteerdePersoon.getLocatieId(),geselecteerdePersoon.getFilmId());
PersoonDao.updatePersoon(nieuwePersoon);
}
updatePersoonsLijst();
}
My method updatePersoonsLijst
public void updatePersoonsLijst() {
mijnModel.clear();
ArrayList<Persoon> lijstVanPersonen = PersoonDao.getPersonen();
for (Persoon huidigePersoon : lijstVanPersonen) {
mijnModel.addElement(huidigePersoon);
}
}
And my updatePersoon
public static int updatePersoon(Persoon nieuwePersoon) {
int aantalAangepasteRijen = 0;
try {
aantalAangepasteRijen = Database.voerSqlUitEnHaalAantalAangepasteRijenOp("UPDATE Persoon SET leeftijd=?,voornaam=?,achternaam=?,datum=?,locatieId=?,filmId=? WHERE persoonId=?", new Object[] { nieuwePersoon.getLeeftijd(),nieuwePersoon.getVoornaam(), nieuwePersoon.getAchternaam(), nieuwePersoon.getDatum(), nieuwePersoon.getLocatieId(),nieuwePersoon.getFilmId() });
} catch (SQLException ex) {
ex.printStackTrace();
// Foutafhandeling naar keuze
}
return aantalAangepasteRijen;
}

Your update statement is missing last parameter personid - your last is filmid currently.
aantalAangepasteRijen = Database.voerSqlUitEnHaalAantalAangepasteRijenOp("UPDATE Persoon
SET leeftijd=?,voornaam=?,achternaam=?,datum=?,locatieId=?,filmId=?
WHERE persoonId=?", new Object[]
{ nieuwePersoon.getLeeftijd(),
nieuwePersoon.getVoornaam(),
nieuwePersoon.getAchternaam(),
nieuwePersoon.getDatum(),
nieuwePersoon.getLocatieId(),
nieuwePersoon.getFilmId()
// persoonId missing!!
});

Related

NumberFormatException: null

I am getting this error:NumberFormatException: null when I am trying to add score/points to my app.
I created separated table for this because I need multiple tables .
I have no clue what the problem is so thanks to you all.
if(count==4) {
my_db=new DBHelper(this);
sqdb = my_db.getWritableDatabase();
Cursor c_oldPoints= sqdb.query(DBHelper.TABLE_NAME2,null,DBHelper.NICKNAME+"=?",new String[]{Username},null,null,null);
int col_Points=c_oldPoints.getColumnIndex(DBHelper.POINTS);
c_oldPoints.moveToFirst();
while (!c_oldPoints.isAfterLast())
{
OldPoints=c_oldPoints.getString(col_Points);
c_oldPoints.moveToNext();
}
sqdb.close();
int OldP = Integer.parseInt(OldPoints);
OldP+=countPoints;
String SoldP = Integer.toString(OldP);
my_db=new DBHelper(this);
sqdb = my_db.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(my_db.POINTS,SoldP);
Cursor c = sqdb.query(DBHelper.TABLE_NAME2,null,DBHelper.NICKNAME+"=?",new String[]{Username},null,null,null);
c.moveToFirst();
while (!c.isAfterLast())
{
sqdb.update(DBHelper.TABLE_NAME2,cv, DBHelper.POINTS+"=?",new String[]{OldPoints});
c.moveToNext();
}
sqdb.close();
countPoints=0;
}
This is the logcat :-
2019-05-15 18:18:14.101 8513-8513/com.example.user.soundsequ E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.soundsequ, PID: 8513
java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:483)
at java.lang.Integer.parseInt(Integer.java:556)
at com.example.user.soundsequ.Game.onClick(Game.java:353)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
The error appears to be in this line
int OldP = Integer.parseInt(OldPoints);
The error is saying that the value of OldPoints is not a string that can be converted to an integer e.g. if it were A or null;
As such either a value extracted from the POINTS column is not a numeric or the value of Username does not match the column NICKNAME in a row. In which case OldPoints will be whatever value it has been set to before the loop.
As the data itself is not available you need to ascertain which of the two situations is causing the issue.
I'd suggest adding some Logging in to determine which.
e.g. by using something like :-
OldPoints = "my debugging value";
Log.d("MYDEBUGGING","OldPoints, before doing anything is " + OldPoints);
Cursor c_oldPoints= sqdb.query(DBHelper.TABLE_NAME2,null,DBHelper.NICKNAME+"=?",new String[]{Username},null,null,null);
int col_Points=c_oldPoints.getColumnIndex(DBHelper.POINTS);
c_oldPoints.moveToFirst();
while (!c_oldPoints.isAfterLast())
{
OldPoints=c_oldPoints.getString(col_Points);
c_oldPoints.moveToNext();
Log.d("MYDEBUGGING","Extracted the value " + OldPoints + " from position + String.valueOf(c_oldPoints.getPosition());
}
sqdb.close();
Log.d("MYDEBUGGING","Trying to convert the value " + OldPoints + " to an integer");
int OldP = Integer.parseInt(OldPoints);
You could also not make the above changes and add a breakpoint (on the line initially indicated) and then use Run/Debug App and inspect the variables (or use multiple breakpoints at suitable places). You may find this useful in regard to debugging Debug your app.
The following code protects against the exception and also protects against an attempt being made to update a non-existent user :-
if (count == 4) {
SQLiteDatabase sqdb = my_db.getWritableDatabase();
Cursor c_oldPoints= sqdb.query(
DBHelper.TABLE_NAME2,null,
DBHelper.NICKNAME+"=?",
new String[]{Username},
null,null,null
);
int col_Points=c_oldPoints.getColumnIndex(DBHelper.POINTS);
if (c_oldPoints.moveToFirst()) {
Oldpoints = c_oldPoints.getString(col_Points);
//Oldpoints = "oops";
int OldP = 0;
boolean can_convert_to_int = true;
try {
OldP = Integer.parseInt(Oldpoints) + countPoints;
can_convert_to_int = true;
} catch (NumberFormatException e) {
e.printStackTrace(); //TODO not necessary probably remove. just for checking the log
}
if (can_convert_to_int) {
ContentValues cv = new ContentValues();
cv.put(DBHelper.POINTS,OldP);
sqdb.update(DBHelper.TABLE_NAME2,cv, DBHelper.NICKNAME + "=?", new String[]{Username});
}
} else {
Log.d("NICKNAMENOTFOUND","No row was found when attemtping to get the old score for User " + Username);
}
}
However
I would suggest that you add a couple of methods to your DBHelper class, these being :-
public int increasePoints(String user, int points_to_add) {
SQLiteDatabase db = this.getWritableDatabase();
SQLiteStatement sql = db.compileStatement(
"UPDATE " + TABLE_NAME2 +
" SET " + POINTS + "=" + POINTS + " +? " +
"WHERE "+ NICKNAME + "=?"
);
sql.bindLong(1,points_to_add);
sql.bindString(2,user);
return sql.executeUpdateDelete();
}
public int getPoints(String user) {
SQLiteDatabase db = this.getWritableDatabase();
int rv = -1;
String whereclause = NICKNAME + "=?";
String[] whereargs = new String[]{user};
Cursor csr = db.query(TABLE_NAME2,new String[]{POINTS},whereclause,whereargs,null,null,null);
if (csr.moveToFirst()) {
rv = csr.getInt(csr.getColumnIndex(POINTS));
}
csr.close();
return rv;
}
The first method increasePoints performs the change to the points via an UPDATE sql statement and does away for the need to convert the points extracted as a string to an integer. It returns the number of rows that have been updated (1 if the NICKNAME column is always a unique value, 0 if nothing was updated).
The second method getPoints does as it says, it gets the points for the given user, if the user doesn't exist it will return -1.
Your code could then be :-
if (count == 4) {
boolean updated = false; //TODO remove when happy
int old_points = my_db.getPoints(Username); //TODO remove when happy
if (my_db.increasePoints(Username,countPoints) > 0) {
updated = true;
}
int new_points = my_db.getPoints(Username); //TODO remove when happy
//TODO remove following code when happy
String result = "The result of the attempt to update the points for user " + Username;
if (updated) {
result = result + " was successful. ";
} else {
result = result + " was unsuccessful.";
}
Log.d("POINTSINCREASE",result +
" Points were " + String.valueOf(old_points) + " points are now " + String.valueOf(new_points));
}
Note where //TODO remove when happy is coded the lines are just for testing, so the above could be :-
if (count == 4) {
my_db.increasePoints(Username,countPoints);
}

Insert Button Not working after verifying duplicate entry

Hi I am beginner I am trying to create a reservation system somehow I can check now if there is duplicate entry however if there's no duplicate entry it is not inserting the data into the database but it if I remove my function to check the duplicate it can insert the data in database. Any suggestion? I am trying to figure it out but it still not working.No error but not adding.
private void btnreserveActionPerformed(java.awt.event.ActionEvent evt) {
try {
DB_Operation DB =new DB_Operation();
String cx1,contactnum11,email1,t11,venuee;
String amount1=aval.getText();
String bal1=b1.getText();
cx1=cx.getText();
contactnum11=contactnum1.getText();
email1=email.getText();
t11=t1.getSelectedItem().toString();
venuee=v.getSelectedItem().toString();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String Dateee = sdf.format(dad.getSelectedDate().getTime());
boolean unique;
unique = true;
String c1="8am to 12 pm";
String c3="8am to 5pm";
String c2="1pm to 5 pm";
ResultSet rsa= DB.searchQuery("SELECT * FROM `reserve1` WHERE `Date`='"+Dateee+"'");
if ( cx.getText().trim().length() == 0|| contactnum1.getText().trim().length() == 0||email.getText().trim().length() == 0){
final JPanel panel = new JPanel();
JOptionPane.showMessageDialog(panel, "All fields must be completed", "Error", JOptionPane.ERROR_MESSAGE);
}
else if(rsa.isBeforeFirst()){
while(rsa.next()){
if(rsa.getString("Venue").equalsIgnoreCase(venuee)&&
rsa.getString("Date").equalsIgnoreCase(Dateee)&& rsa.getString("Time").equals(t11)){
JOptionPane.showMessageDialog(null,"Duplicate Resevation!");
unique = false;
}
else if((t11.equals(c3))&&(rsa.getString("Venue").equalsIgnoreCase(venuee)&&
rsa.getString("Date").equalsIgnoreCase(Dateee)&& rsa.getString("Time").equals(c1))){
JOptionPane.showMessageDialog(null,"Half Day Resevation Exist!");
unique = false;
}
else if((t11.equals(c3))&&(rsa.getString("Venue").equalsIgnoreCase(venuee)&&
rsa.getString("Date").equalsIgnoreCase(Dateee)&& rsa.getString("Time").equals(c2))){
JOptionPane.showMessageDialog(null,"Half Day Resevation Exist!");
unique = false;
}
else if(unique=true){
try
{
String url="jdbc:mysql://localhost:3306/reservation?zeroDateTimeBehavior=convertToNull";
String userdb="root";
String passdb="";
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection(url,userdb,passdb);
Statement stmt=(Statement)conn.createStatement();
stmt.executeUpdate ("INSERT INTO `reserve1`( `Customer Name`, `Contact Number`, `Email Address`, `Venue`, `Date`, `Time`, `Price`, `Balance`) "+ "VALUES ("+"\""+cx1+"\""+","+"\""+contactnum11+"\""+","+"\""+email1+"\""+","+"\""+venuee+"\""+","+"\""+Date1+"\""+","+"\""+t11+"\""+","+"\""+amount1+"\""+","+"\""+bal1+"\""+")");
JOptionPane.showMessageDialog(null,"Data Added!");
}
catch( HeadlessException | ClassNotFoundException | SQLException e)
{
JOptionPane.showMessageDialog(null, e.getMessage() ,"Error", 1);
}
}
}
}
} catch (SQLException ex) {
Logger.getLogger(reservation.class.getName()).log(Level.SEVERE,
null, ex);
}
I think you should put the if(unique=true) as a separate if statement and not as the part of else if ladder.

DatabaseMetada.getImportedKey is empty even if foreign are existing

For my project i try to get all foreign key in my table using DatabaseMetada Object form jdbc but when i execute the following code the result set is always empty even if my table contain foreign key ?
ResultSet v_resultPrimaryKey = p_metadata.getImportedKeys(null, Tools.getDBName(), "bookmarks_tags");
if (v_resultPrimaryKey.next()) {
System.out.println("test");
v_resultPrimaryKey.beforeFirst();
v_resultPrimaryKey.beforeFirst();
while (v_resultPrimaryKey.next()) {
if (p_att.equals(v_resultPrimaryKey.getString("FKCOLUMN_NAME"))) {
v_fk = v_resultPrimaryKey.getString("PKTABLE_NAME") + "."
+ v_resultPrimaryKey.getString("PKCOLUMN_NAME");
v_fkName = v_resultPrimaryKey.getString("FK_NAME");
}
}
if(!v_fk.equals("")){
v_foreignKey = new ForeignKey(v_fkName, v_fk);
}
}
stumbled upon this and this may help in case anyone may see it
DatabaseMetaData p_metadata= connection.getMetaData();
ResultSet v_resultPrimaryKey = p_metadata.getImportedKeys(null, Tools.getDBName(), "bookmarks_tags");
if (v_resultPrimaryKey.next()) {
System.out.println("test");
v_resultPrimaryKey.beforeFirst();
v_resultPrimaryKey.beforeFirst();
while (v_resultPrimaryKey.next()) {
if (p_att.equals(v_resultPrimaryKey.getString("FKCOLUMN_NAME"))) {
String v_fk = v_resultPrimaryKey.getString("PKTABLE_NAME") + "."
+ v_resultPrimaryKey.getString("PKCOLUMN_NAME");
String v_fkName = v_resultPrimaryKey.getString("FK_NAME");
}
}
if(!v_fk.equals("")){
v_foreignKey = new ForeignKey(v_fkName, v_fk);
}
}

SQLiteException: near "null": syntax error (code 1): , while compiling: create table

Please help me, i get this errors when i run my app use Idea
here is screen of error
http://prntscr.com/en3lcu
here is part of code where create table
private String getTableDDL(final Class<? extends GlassContract.Table> table) {
return getTableDDL(table, GlassContract.getTableName(table));
}
private String getTableDDL(final Class<? extends GlassContract.Table> table, String tableName) {
final StringBuilder sql = new StringBuilder(128);
sql.append("create table ").append(tableName).append(" (");
for (final Field field : table.getFields()) {
if (field.getName().startsWith("_") || field.isAnnotationPresent(Deprecated.class))
continue;
try {
sql.append(field.get(null));
} catch (Exception ignore) {
}
try {
final Field type = table.getDeclaredField("_SQL_" + field.getName() + "_TYPE");
sql.append(' ').append(type.get(null));
} catch (Exception ignore) {
sql.append(" TEXT");
}
sql.append(',');
}
try {
final Field type = table.getDeclaredField("_PK_COMPOSITE");
sql.append("PRIMARY KEY(").append(type.get(null)).append(")");
sql.append(',');
} catch (Exception ignore) {
// ignore
}
try {
final Field type = table.getDeclaredField("_UNIQUE_COMPOSITE");
sql.append("UNIQUE(").append(type.get(null)).append(")");
sql.append(',');
} catch (Exception ignore) {
// ignore
}
sql.setLength(sql.length() - 1); // chop off last comma
sql.append(')');
Log.v(TAG, "DDL for " + table.getSimpleName() + ": " + sql);
return sql.toString();
}
I please help me, because I break my head))
Are you really trying to create text fields in your table that are named null?
Even if this works (and I am not sure it does), you are duplicating this and creating two identically named fields called null
The first field in that CREATE TABLE statement doesn't have a proper name (it is "null"). That's why it blows up.
There's more fields with illegal names as well.

How to get a specific value from a string name via config

The green is the lore
and the yellow is the displayname
http://puu.sh/k2iI7/62619f9536.jpg
I'm trying to seperate them in there rightful places for some odd reason there both appearing in both of the places.
items.java
public ItemStack applyLore(ItemStack stack, String name, String lore1){
ItemMeta meta = stack.getItemMeta();
meta.setDisplayName(name.replaceAll("&([0-9a-f])", "\u00A7$1"));
ArrayList<String> lore = new ArrayList<String>();
lore.add(lore1.replaceAll("&([0-9a-f])", "\u00A7$1"));
meta.setLore(lore);
stack.setItemMeta(meta);
return stack;
}
// p.getInventory().addItem(new ItemStack(Integer.parseInt(s), 1));
public void giveItemfromConfig(Player p)
{
String name ="name:";
String lore ="lore:";
for ( String s : plugin.file.getFile().getStringList(plugin.file.path) ) {
try {
s.split(" ");
if ( s.contains(name) || s.contains(lore) )
{
String namelength = s.substring(name.length());
String lorelength = s.substring(lore.length());
p.getInventory().addItem(applyLore(new ItemStack(Integer.parseInt(s.split(" ")[0])),
namelength.replace("_", " ").replace("ame:", "").replace("e:", "").replace("lor", "").replace("ore", ""),
lorelength.replace("_", " ").replace("lor:", "").replace("e:", "").replace("am", "").replace("lor", "").replace("ore", "")));
p.sendMessage("debug");
} else {
///nope.exe
p.getInventory().addItem(new ItemStack(Integer.parseInt(s)));
}
} catch(Exception e)
{
e.printStackTrace();
Bukkit.getConsoleSender().sendMessage(ChatColor.AQUA + "Error in Config, Your id must be a integer ERROR:" + e);
}
}
}
config.yml
ChestPopulater:
items:
- 276 name:cookie
First thing is the problem is because of "Integer.parseInt(s)".
I dont know why you added this one as we dont have full source code or idea what you are trying to do with String "s" so that you will get result.
If you are doing it to get "276" , I will suggest you to do following :
String s2 = s.replaceAll("[A-Za-z]","").replace(":","").trim();
Integer i = Integer.parseInt(s2);

Categories

Resources