I am facing a strange problem when I try to update a certain row in my table.
I am using the Connection class from java.sql library. Following is my table script:
CREATE TABLE `crd_web_request` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_id` varchar(30) NOT NULL,
`trn_notes` varchar(200) DEFAULT NULL,
`trn_date` date NOT NULL,
`amount` double(20,3) DEFAULT '0.000',
`other_amount` double(20,3) DEFAULT '0.000',
`card_fees` double(20,3) DEFAULT '0.000',
`shipping_fees` double(20,3) DEFAULT '0.000',
`sys_trtype_id` int(11) DEFAULT NULL,
`crd_agent_mast_id` int(11) DEFAULT '0',
`sys_phase_id` int(11) DEFAULT '0',
`sys_user_id` int(11) DEFAULT NULL,
`cust_aname` varchar(250) DEFAULT NULL,
`cust_ename` varchar(250) DEFAULT NULL,
`sys_nationality_id` int(11) DEFAULT NULL,
`passport_id` varchar(45) DEFAULT NULL,
`sys_doc_type_id` int(11) DEFAULT NULL,
`cust_doc_id` varchar(45) DEFAULT NULL,
`cust_email` varchar(250) DEFAULT NULL,
`cust_address` varchar(250) DEFAULT NULL,
`cust_tel` varchar(30) DEFAULT NULL,
`card_holder_name` varchar(400) DEFAULT NULL,
`status` int(1) NOT NULL DEFAULT '0',
`cardType_ID` int(20) DEFAULT NULL,
`sys_org` int(2) DEFAULT NULL,
PRIMARY KEY (`id`,`order_id`)
) ENGINE=InnoDB AUTO_INCREMENT=237 DEFAULT CHARSET=utf8;
and following is my java code to update the table:
Statement stmt = null;
String query = "UPDATE smcpp16.crd_web_request SET status = 1 WHERE order_id = '" + orderId + "'";
try {
stmt = conn.createStatement();
System.out.println(query);
stmt.execute(query);
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
I can it figure out why this is happening. Every time when executing the update statement, the table inserts a new record with the same values of the updated row. Can you please help?
I removed the closing of the connection from this code and the duplication is not happening any more.
I just removed:
conn.close();
It is a practice to close the connection in the finally block, something like this :
try{
// update data
}
catch{
//catch exception
}
finally{
//close connection
conn.close();
}
Let me know if this helps.
Related
So I'm trying to add to database using JDBC with HSQLDB from files. And I need to insert the List<Object> as a variable into the database.
This is what it looks like as a Java object:
public class Plant {
private Long id;
private String plantName;
private List<PlantParts> plantParts;
...
}
public class PlantParts {
private String leaves;
private String pedicle;
private String petals;
...
}
In folder resources I have a file called insert_plant.sql that contains this query:
INSERT INTO PLANTS (id, plantname, plantparts)
VALUES (NEXT VALUE FOR sequence, ?, ?);
And the table is generated with this:
CREATE SEQUENCE sequence START WITH 1;
CREATE TABLE PLANTS (
id BIGINT NOT NULL PRIMARY KEY,
plantname VARCHAR(255) NOT NULL,
plantparts VARCHAR(255) NULL, //No idea what to put here
);
And now in Java I am calling this:
public static void insertIntoOrderTable(BasicDataSource basicDataSource, String plantname, List<PlantParts> plantparts) throws SQLException{
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = basicDataSource.getConnection();
stmt = conn.prepareStatement(Util.readFileFromClasspath("insert_plant.sql"), new String[]{"id"});
stmt.setString(1, plantname);
stmt.setString(2, plantparts); //And no idea what to do here
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
}
The requests will usually come as a JSON:
{ "id": 5,
"plantName": "awesome plant",
"plantParts":[
{"leaves":"green","pedicle":"yellow","petals":"many"},
{"leaves":"red","pedicle":"yellow","petals":"few"}
]
}
My guess is that they should be held in the separate tables, but how can I do that and when I would need to get the object then how could I get it as a whole.
The SQL model of your data will be different from Java in how the Plant and PlantParts objects are linked together. In the Java model, Plant has a collection of PlantParts objects. In the SQL model, the PlantParts objects reference the Plant object.
So you need these two tables:
CREATE TABLE plants (
id BIGINT NOT NULL PRIMARY KEY,
plantname VARCHAR(255) NOT NULL,
);
CREATE TABLE plantparts (
id BIGINT NOT NULL PRIMARY KEY,
leaves VARCHAR(255) NOT NULL,
pedicles VARCHAR(255) NOT NULL,
petals VARCHAR(255) NOT NULL,
plantid BIGINT NOT NULL,
FOREIGN KEY (plantid) REFERENCES plants(id)
);
Note there is no column in the plants table for the PlantParts objects. The data for the PlantParts in your JSON object goes into two rows of the plantparts table. The plantid column of both of these rows will contain the id of the Plant object, which is 5.
This question already has answers here:
Getting the date from a ResultSet for use with java.time classes
(3 answers)
Closed 4 years ago.
I run a simple query to retrieve a row from a MySQL database.
I get ResultSet and I need to retrieve a LocalDateTime object from it.
My DB table.
CREATE TABLE `some_entity` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`title` varchar(45) NOT NULL,
`text` varchar(255) DEFAULT NULL,
`created_date_time` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
I need to retrieve some entity by id.
String SELECT = "SELECT ID, TITLE, TEXT, CREATED_DATE_TIME FROM some_entity WHERE some_entity.id = ?";
PreparedStatement selectPreparedStatement = connection.prepareStatement(SELECT);
try {
selectPreparedStatement.setLong(1, id);
ResultSet resultSet = selectPreparedStatement.executeQuery();
if (resultSet.next()) {
Long foundId = resultSet.getLong(1);
String title = resultSet.getString(2);
String text = resultSet.getString(3);
LocalDateTime createdDateTime = null;// How do I retrieve it???
}
} catch (SQLException e) {
throw new RuntimeException("Failed to retrieve some entity by id.", e);
}
Try retrieving this as java.sql.Timestamp and then converting to LocalDateTime using Timestamp.toLocalDateTime:
LocalDateTime createdDateTime = resultSet.getTimestamp(4).toLocalDateTime()
EDIT: As Gord Thompson pointed out in his comment, there's an even better solution when working with a recent enough JDBC driver:
resultSet.getObject(4, LocalDateTime.class)
This skips creating a redundant java.sql.Timestamp instance.
this is my Table vehicletlb !
Field Type
v_branch varchar(255) NULL
v_segment varchar(255) NULL
v_company varchar(255) NULL
v_name varchar(255) NULL
v_plateno varchar(255) NULL
v_seats int(11) NULL
v_fuel varchar(255) NULL
v_priceperkm int(11) NULL
v_driver varchar(255) NULL
Now I am trying to Update the table using Prepared Statement in Servlet. But unfortunately it is giving error for unknown column:v_plateno
Also the update query is working fine for other Tables in the database
public void updateVehicle(Vehicle vehicle) {
String updateQuery = "UPDATE vehicletlb SET v_branch=?, v_segment=?, v_company=?, v_name=?, v_seats=?, v_fuel=?, v_priceperkm=?, v_driver=? WHERE v_plateno = ? ";
try {
pStmt = dbConnection.prepareStatement(updateQuery);
pStmt.setString(1, vehicle.getVbranch());
pStmt.setString(2, vehicle.getVsegment());
pStmt.setString(3, vehicle.getVcomp());
pStmt.setString(4, vehicle.getVname());
pStmt.setInt(5, vehicle.getVseats());
pStmt.setString(6, vehicle.getVfuel());
pStmt.setInt(7, vehicle.getVprice());
pStmt.setString(8, vehicle.getVdriver());
pStmt.setString(9, vehicle.getVplateno());
pStmt.executeUpdate();
} catch (SQLException e) {
System.err.println(e.getMessage());
}
}
I am using Apache Tomcat 7.0
But it gives error
Unknown column 'v_plateno' in 'where clause'
How can I solve it !!!!
There were no errors in the program and now
I tried Refreshing the Browser, and it started working
Thanks for support !
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
i have stumbled on an error which i have spend 3hours trying to fix.
i'm trying to save some data from my server onto my mysql db on my webhost.
i do already have my vps ip set in my remote sql thing.
But i'm stumbling into a mysql syntax error.
Would be very grateful if you can help me,
thanks in advance!
my console:
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your S
QL syntax; check the manual that corresponds to your MySQL server version for th
e right syntax to use near '' at line 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2941)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1623)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1715)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3243)
at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1343)
at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1260)
at org.dementhium.mysql.hiscores.query(hiscores.java:53)
at org.dementhium.mysql.hiscores.saveHighScore(hiscores.java:80)
my java file:
package org.dementhium.mysql;
import java.sql.SQLException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.dementhium.model.player.Player;
import org.dementhium.model.player.Skills;
import org.dementhium.model.player.Skills;
import org.dementhium.mysql.DatabaseManager;
/**
*
* #author 'Mystic Flow <Steven#rune-server.org>
*/
#SuppressWarnings("unused")
public class hiscores extends Thread {
public static final String[] SKILLS = {"Attack", "Defence",
"Strength", "Constitution", "Ranged", "Prayer", "Magic", "Cooking",
"Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting",
"Smithing", "Mining", "Herblore", "Agility", "Thieving", "Slayer",
"Farming", "Runecrafting", "Hunter", "Construction", "Summoning",
"Dungeoneering"
};
public static Connection con = null;
public static Statement stmt;
public static boolean connectionMade;
public static void createConnection() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://slash-scape.org/slash756_highsco","slash756_highsco","");
stmt = con.createStatement();
System.out.println("Highscores updated for ");
} catch (Exception e) {
e.printStackTrace();
}
}
public static ResultSet query(String s) throws SQLException {
try {
if (s.toLowerCase().startsWith("select")) {
ResultSet rs = stmt.executeQuery(s);
rs.updateRow();
return rs;
} else {
stmt.executeUpdate(s);
}
return null;
} catch (Exception e) {
destroyConnection();
createConnection();
e.printStackTrace();
System.out.println("Highscores updated for,hgjhkhkjhkj ");
}
return null;
}
public static void destroyConnection() {
try {
stmt.close();
con.close();
connectionMade = false;
} catch (Exception e) {
e.printStackTrace();
}
}
public static boolean saveHighScore(Player player) {
try {
//query("DELETE FROM `highscores` WHERE username = '"+player.getUsername()+"';");
//query("DELETE FROM `highscores` WHERE username = '"+player.getUsername()+"';");
System.out.println("Highscores updated for,hgjhkhkjhkj ");
query("INSERT INTO `highscores` (`username`,`attack_xp`,`defence_xp`,`strength_xp`,`hitpoints_xp`,`ranged_xp`,`prayer_xp`,`magic_xp`,`cooking_xp`,`woodcutting_xp`,`fletching_xp`,`fishing_xp`,`firemaking_xp`,`crafting_xp`,`smithing_xp`,`mining_xp`,`herblore_xp`,`agility_xp`,`thieving_xp`,`slayer_xp`,`farming_xp`,`runecraft_xp`,`hunter_xp`,`construction_xp`,`summoning_xp`,`dungeoneering_xp`,`overall_xp`,`rights`) VALUES ("+player.getUsername()+","+player.getSkills().getXp(0)+","+player.getSkills().getXp(1)+","+player.getSkills().getXp(2)+","+player.getSkills().getXp(3)+","+player.getSkills().getXp(4)+","+player.getSkills().getXp(5)+","+player.getSkills().getXp(6)+","+player.getSkills().getXp(7)+","+player.getSkills().getXp(8)+","+player.getSkills().getXp(9)+","+player.getSkills().getXp(10)+","+player.getSkills().getXp(11)+","+player.getSkills().getXp(12)+","+player.getSkills().getXp(13)+","+player.getSkills().getXp(14)+","+player.getSkills().getXp(15)+","+player.getSkills().getXp(16)+","+player.getSkills().getXp(17)+","+player.getSkills().getXp(18)+","+player.getSkills().getXp(19)+","+player.getSkills().getXp(20)+","+player.getSkills().getXp(21)+","+player.getSkills().getXp(22)+","+player.getSkills().getXp(23)+","+player.getSkills().getXp(24)+","+((player.getSkills().getXp(0)) + (player.getSkills().getXp(1)) + (player.getSkills().getXp(2)) + (player.getSkills().getXp(3)) + (player.getSkills().getXp(4)) + (player.getSkills().getXp(5)) + (player.getSkills().getXp(6)) + (player.getSkills().getXp(7)) + (player.getSkills().getXp(8)) + (player.getSkills().getXp(9)) + (player.getSkills().getXp(10)) + (player.getSkills().getXp(11)) + (player.getSkills().getXp(12)) + (player.getSkills().getXp(13)) + (player.getSkills().getXp(14)) + (player.getSkills().getXp(15)) + (player.getSkills().getXp(16)) + (player.getSkills().getXp(17)) + (player.getSkills().getXp(18)) + (player.getSkills().getXp(19)) + (player.getSkills().getXp(20)) + (player.getSkills().getXp(21)) + (player.getSkills().getXp(22)) + (player.getSkills().getXp(23)) + (player.getSkills().getXp(24)))+","+player.getRights()+";");
//query("INSERT INTO `skillsoverall` (`playerName`,`lvl`,`xp`, `prestige`) VALUES ('"+player.getUsername()+"',"+(player.getSkills().getLevel(0) + player.getSkills().getLevel(1) + player.getSkills().getLevel(2) + player.getSkills().getLevel(3) + player.getSkills().getLevel(4) + player.getSkills().getLevel(5) + player.getSkills().getLevel(24) + player.getSkills().getLevel(6) + player.getSkills().getLevel(7) + player.getSkills().getLevel(8) + player.getSkills().getLevel(9) + player.getSkills().getLevel(10) + player.getSkills().getLevel(11) + player.getSkills().getLevel(12) + player.getSkills().getLevel(13) + player.getSkills().getLevel(14) + player.getSkills().getLevel(15) + player.getSkills().getLevel(16) + player.getSkills().getLevel(17) + player.getSkills().getLevel(18) + player.getSkills().getLevel(19) + player.getSkills().getLevel(20) + player.getSkills().getLevel(21) + player.getSkills().getLevel(22) + player.getSkills().getLevel(23))+" ,"+((player.getSkills().getXp(0)) + (player.getSkills().getXp(1)) + (player.getSkills().getXp(2)) + (player.getSkills().getXp(3)) + (player.getSkills().getXp(4)) + (player.getSkills().getXp(5)) + (player.getSkills().getXp(6)) + (player.getSkills().getXp(7)) + (player.getSkills().getXp(8)) + (player.getSkills().getXp(9)) + (player.getSkills().getXp(10)) + (player.getSkills().getXp(11)) + (player.getSkills().getXp(12)) + (player.getSkills().getXp(13)) + (player.getSkills().getXp(14)) + (player.getSkills().getXp(15)) + (player.getSkills().getXp(16)) + (player.getSkills().getXp(17)) + (player.getSkills().getXp(18)) + (player.getSkills().getXp(19)) + (player.getSkills().getXp(20)) + (player.getSkills().getXp(21)) + (player.getSkills().getXp(22)) + (player.getSkills().getXp(23)) + (player.getSkills().getXp(24)))+";");
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
}
my MySQL database query:
CREATE TABLE IF NOT EXISTS `highscores` (
`id` int(11) NOT NULL primary key AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`rights` int(1) NOT NULL DEFAULT '0',
`overall_xp` bigint(20) NOT NULL,
`attack_xp` int(11) NOT NULL,
`defence_xp` int(11) NOT NULL,
`strength_xp` int(11) NOT NULL,
`constitution_xp` int(11) NOT NULL,
`ranged_xp` int(11) NOT NULL,
`prayer_xp` int(11) NOT NULL,
`magic_xp` int(11) NOT NULL,
`cooking_xp` int(11) NOT NULL,
`woodcutting_xp` int(11) NOT NULL,
`fletching_xp` int(11) NOT NULL,
`fishing_xp` int(11) NOT NULL,
`firemaking_xp` int(11) NOT NULL,
`crafting_xp` int(11) NOT NULL,
`smithing_xp` int(11) NOT NULL,
`mining_xp` int(11) NOT NULL,
`herblore_xp` int(11) NOT NULL,
`agility_xp` int(11) NOT NULL,
`thieving_xp` int(11) NOT NULL,
`slayer_xp` int(11) NOT NULL,
`farming_xp` int(11) NOT NULL,
`runecrafting_xp` int(11) NOT NULL,
`hunter_xp` int(11) NOT NULL,
`construction_xp` int(11) NOT NULL,
`summoning_xp` int(11) NOT NULL,
`dungeoneering_xp` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
I think you are constructing your query incorrectly by not quoting Strings. This is only going to be compounded if your Strings have additional quotes in them!
To get around this, use PreparedStatement. Not only is it simpler, it's safer and helps prevent SQL Injection attacks.
Basic example:
final static String INSERT_QUERY = "INSERT INTO highscores (username,attack_xp,defence_xp) values(?,?,?)"; // Etc...
PreparedStatement ps = connection.prepareStatement(INSERT_QUERY);
ps.setString(1, player.getUsername());
ps.setInt(2, player.getAttackXp());
ps.setInt(3, player.getDefenseXp());
// etc.
ps.execute();
Your query is incorrect, one of the mistake is varchar should be wrapped with ' you are not doing it, also it is messy and vulnerable so use PreparedStatement instead
So mySQL database keeps accepting duplicate entries despite the unique constraint I've added. I've been trying to look for a similar question but could not find anything related. I don't know if my prepared statement is wrong or if mySQL database is set up wrong. Here is my code:
Connection con = DB.getConnection();
PreparedStatement ps = null, ps1 = null, ps2 = null, ps3 = null, ps4 = null;
ResultSet rs = null;
try {
ps = con.prepareStatement("insert into users(user_id, username, password, email, phone_number,"
+ "name, fb_id, bio) values (DEFAULT, ?, ?, ?, ?, ?, ?, ?)");
ps.setString(1, username);
ps.setString(2, hashedPassword);
ps.setString(3, email_address);
ps.setString(4, phone_number);
ps.setString(5, name);
ps.setString(6, fb_id);
ps.setString(7, bio);
ps.execute();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
ps.close();
con.close();
} catch (Exception e) {
e.printStackTrace(); }
my table has the following columns:
user_id int(11) PRIMARY,
username varchar(20) UNIQUE,
password varchar(100),
email varchar(30) UNIQUE,
phone_number varchar(10) UNIQUE,
fb_id varchar(20) UNIQUE,
bio FULL TEXT
I've created the table using phpmyadmin and username and fb_id correctly gives me the MySQLIntegrityConstraintViolationException, but email and phone_number does not give me any errors when inserting duplicate entries. Is there any reason why this would happen? I am pretty lost as to why the unique constraint is not being enforced...
PS. First time posting!
EDIT: Here is the results of SHOW CREATE TABLE users:
CREATE TABLE users (
user_id int(11) NOT NULL AUTO_INCREMENT,
username varchar(20) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
password varchar(100) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
email varchar(30) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
phone_number varchar(10) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
name varchar(20) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
fb_id varchar(20) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
bio text CHARACTER SET utf8 COLLATE utf8_bin NOT NULL,
PRIMARY KEY (user_id),
UNIQUE KEY username (username,email,phone_number),
UNIQUE KEY fb_id (fb_id)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=latin1
You currently have your UNIQUE KEY setup as a composite key.
UNIQUE KEY username (username,email,phone_number)
This means that the combination of username, email and phone number must be unique. It is not specifying each individual column can't contain duplicate values.
For that you should add a UNIQUE INDEX to those columns individually where required. For example to make the email field a UNIQUE INDEX:
ALTER TABLE users ADD UNIQUE INDEX(email);