Hello i am using prepared statement to insert the values into mysql.
I am facing an issue in an string which is inserting as "c2a054656e6e6973c2a0" for value " Tennis " and i tried to use trim to trim the whitespace in front of the "Tennis" it did not work .From this question Why trim is not working? i tried using the solution poNumber.replace(String.valueOf((char) 160), " ").trim(); and it worked. can any one give solution for this?
SAMPLE CODE
CREATE TABLE `news1` (
`article_id` int(11) NOT NULL AUTO_INCREMENT,
`article_title` varchar(500) COLLATE utf8_bin NOT NULL,
`article_subcategory` varchar(255) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`article_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=22 ;
//Sample category will be "Home » Tennis"
String category = item.getArticle_category();
String categoryArray[] = category.split("»");
preparedStatement = connect
.prepareStatement("INSERT INTO news1 VALUES(default,?,?)");
System.out.println(categoryArray[2].replace(String.valueOf((char) 160), " ")
.trim());
preparedStatement.setString(1, item.getArticle_title());
preparedStatement.setString(2, categoryArray[2]);
you are doing this categoryArray[2].replace(String.valueOf((char) 160), " ") .trim() in sys out but you do preparedStatement.setString(2, categoryArray[2]); in your statement
String temp = categoryArray[2].replace(String.valueOf((char) 160), " ") .trim();
System.out.println(temp);
and use temp in
preparedStatement.setString(2, temp);
Related
I have a problem with the auto incremented values in preparedStatement. Here is my database
CREATE TABLE `book` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`isbn` varchar(10) NOT NULL,
`title` varchar(20) NOT NULL,
`pages` int(11) NOT NULL,
`price` decimal(5,2) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `isbn` (`isbn`)
and here is my preparedStatement:
String title = fieldTitle.getText();
String isbn = fieldISBN.getText();
double price = Double.parseDouble(fieldPrice.getText());
int pages = Integer.parseInt(fieldPages.getText());
conn = DBUtil.connect();
try {
prepState = conn.prepareStatement("insert into book values(?,?,?,?)");
prepState.setString(1, isbn);
prepState.setString(2, title);
prepState.setInt(3, pages);
prepState.setDouble(4, price);
prepState.execute();
However, when I fill in the fields I get the following error:
java.sql.SQLException: Column count doesn't match value count at row 1. I know that when the field in the database is autoincremented I do not have to put it in the query...
Any ideas?
Modify you query to include column names:-
INSERT INTO book (isbn, title, pages, price) VALUES (?,?,?,?)
I have a string like these "Marko's place" "boulevard "Arequipa"" strings that containing single or double quotes, in Java using regular expressions how get that the previous strings get like this "Marko\s place" "boulevard \"Arequipa\"" I am no have experience with regex, thank for any answer
OK, I am reading records from a mysql table and constructing the insert sql to pass this information to a sqlite table
Statement qryMySQL= cnMySql.createStatement();
ResultSet rs = qryMySQL.executeQuery("select * from tblclientes ");
Statement qrySQLite = cnSqLite.createStatement();
qrySQLite.addBatch("begin transaction");
qrySQLite.addBatch("CREATE TABLE 'tblclientes' ('_id' INTEGER,'Nombres' varchar(25) DEFAULT NULL,'Apellidos' varchar(25) DEFAULT NULL,'RazSocial' varchar(20) DEFAULT NULL,'Direccion' varchar(50) DEFAULT NULL,'Ciudad' varchar(15) DEFAULT 'Arequipa','Fono' varchar(12) DEFAULT NULL,'Fax' varchar(12) DEFAULT NULL,'Email' varchar(35) DEFAULT NULL,'Ruc' varchar(12) DEFAULT NULL,'latitud' decimal(20,14) DEFAULT NULL,'longitud' decimal(20,14) DEFAULT NULL,'ruta' varchar(10) DEFAULT NULL,'sincro' CHAR(10),'copiar' BOOL DEFAULT 1)");
while (rs.next())
{
//System.out.println (rs.getInt(1) + " " + rs.getString (2) );
sql = "INSERT INTO tblclientes(_id,nombres,apellidos) " +
"VALUES("+rs.getInt("id")+", \""+rs.getString("nombres")+"\",\""+rs.getString("apellidos")+"\")";
qrySQLite.addBatch(sql);
// System.out.println (sql);
}
qrySQLite.addBatch("end transaction");
qrySQLite.executeBatch();
but some fields in the mysql table have the characters " and ' that causes error in sql insert sentence then I Need this
<Marko's place> ===> <Marko\'s place>
<boulevard "Arequipa"> ====> <boulevard \"Arequipa">
so the result must be add the \ before the " or '
I would probably use the Apache Commons StringEscapeUtils it catches a lot more corner cases then you have in your question -
StringEscapeUtils.escapeJava(str);
Otherwise, you could just use string replace like this
String str = "\"Marko's place\"";
System.out.println(str.replace("'", "\\'").replace("\"", "\\\""));
I have a table containing four columns:
CREATE TABLE `participants` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(128) NOT NULL,
`function` VARCHAR(255) NOT NULL,
`contact` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `name_function_contact` (`name`, `function`, `contact`)
)
From the application I get participants-objects, which might have values for name, functionand contactwhich are already in that exact matter in the database. In this case I want Hibernate to get me the idof that object, otherwise I want to save the object.
Using saveOrUpdate()I just get an:
org.hibernate.exception.ConstraintViolationException: Duplicate entry 'NAME-FUNCTION-CONTACT: NAME' for key 'name_function_contact'
How can I accomplish this? Thanks a lot!
Since the answers suggested that Hibernate cannot do it on its own (bummer!) I solved it the "native sql" way:
Participants tempParti = ((Participants) session.createQuery("FROM Participants WHERE name = '" + p.getName() + "' AND function = '" + p.getFunction() + "' AND contact = '" + p.getContact() + "'").uniqueResult());
if (tempParti != null) {
p = tempParti;
} else {
session.save(p);
}
Works like a charm! Thanks to all of you!
I am no expert in Hibernate. But from Mysql perspective, you do the following.
use INSERT IGNORE INTO... to add the value in the table. If the number of rows inserted is 0, then you can manually get the ID of the row by a SELECT statement.
EDIT: LAST_INSERT_ID() was wrong here. I have edited the answer.
I have a MySQL database, and I insert rows to a table from a Java class. Everything worked fine, but today, I cannot insert double values. Instead of the values, 0 is being inserted. This is my code in Java:
String str = "INSERT INTO PLAYERS (p_name, p_radius, p_lat, p_lon, p_offset) ";
str += "VALUES ('"+p.getName()+"', "+p.getRadius()+", ";
str += p.getLatitude()+", "+p.getLongitude()+", "+p.getOffset()+")";
PreparedStatement st = connection.prepareStatement(str, Statement.RETURN_GENERATED_KEYS);
st.executeUpdate();
I have also printed the str String and when I execute it on the MySQL Query Browser it gets inserted correctly. The String str is the following:
INSERT INTO PLAYERS (p_name, p_radius, p_lat, p_lon, p_offset)
VALUES ('John', 5, 37.976088, 23.7358438, -1011)
This is the table create statement:
CREATE TABLE PLAYERS (player_id int(11) NOT NULL AUTO_INCREMENT,
p_name varchar(30) DEFAULT NULL,
p_lat double NOT NULL,
p_lon double NOT NULL,
p_score int(11) NOT NULL DEFAULT '0',
p_highscore int(11) NOT NULL DEFAULT '0',
p_game_id int(11) NOT NULL DEFAULT '0',
p_status int(11) NOT NULL DEFAULT '0',
p_radius int(11) NOT NULL,
p_offset bigint(20) NOT NULL,
PRIMARY KEY (player_id)
)
I checked the table during the insert, and I saw the values being inserted correctly. After that when I refreshed the query browser the values were 0 again... So the parameterized statement didn't make a difference.
Finally, I got it. I am terribly sorry, it was my mistake! I have a method that sets these values to 0, when my application ends. Thank you for your responses!
You should use a parameterized statement. Try using this code instead:
String str = "INSERT INTO PLAYERS (p_name, p_radius, p_lat, p_lon, p_offset) VALUES(?,?,?,?,?)";
PreparedStatement st = connection.prepareStatement(str, Statement.RETURN_GENERATED_KEYS);
st.setString(1, p.getName());
st.setDouble(2, p.getRadius());
st.setDouble(3, p.getLatitude());
st.setDouble(4, p.getLongitude());
st.setInt(5, p.getOffset());
st.executeUpdate();
Try this:
String str = "INSERT INTO PLAYERS (p_name, p_radius, p_lat, p_lon, p_offset) VALUES (?, ?, ?, ?, ?)";
PreparedStatement st = connection.prepareStatement(str, Statement.RETURN_GENERATED_KEYS);
st.setString(1, p.getName());
st.setDouble(2, p.getRadius());
st.setDouble(3, p.getLatitude());
st.setDouble(4, p.getLongitude());
st.setInt(5, p.getOffset());
st.executeUpdate();
Take a look at this Link and the section on Supplying Values for PreparedStatement Parameters. Sometimes if you don't use parameterization it will truncate the doubles precision. Amongst other reasons it's really a good best practice.
Finally, I got it. I am terribly sorry, it was my mistake! I have a method that sets these values to 0, when my application closes. Again, I'm really sorry. My application is quite large and so I could not see this immediately. Thank you for your responses!
I am fairly new to MySQL with Java, but I have executed a few successful INSERT queries however cannot seem to get the CREATE TABLE query to execute without getting the MySQLSyntaxErrorException exception. My code is as follows:
Statement stmt;
String url = "jdbc:mysql://localhost:3306/mysql";
Connection con = DriverManager.getConnection(url, "root", "password");
stmt = con.createStatement();
String tblSQL = "CREATE TABLE IF NOT EXISTS \'dev\'.\'testTable\' (\n"
+ " \'id\' int(11) NOT NULL AUTO_INCREMENT,\n"
+ " \'date\' smallint(6) NOT NULL\n"
+ ") ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;";
stmt.executeUpdate(tblSQL);
stmt.close();
con.close();
And the error is as follows:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near ''dev'.'testTable' (
'id' int(11) NOT NULL AUTO_INCREMENT,
'date' smallint(6) N' at line 1
I would appreciate it if anyone could spot the mistake in this query, as I've tried executing this within phpMyAdmin and it works as it should.
\n will make press enter effect :) make it like
String tblSQL = "CREATE TABLE IF NOT EXISTS `dev`.`testTable`"
+ "("
+ "id INTEGER(11) NOT NULL AUTO_INCREMENT primary key,"
+ "date smallint(6) NOT NULL"
+ ")"
+ "ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;";