I have a MySQL table with a Double datatype column, when I insert the value contained in a Java Double I always get a truncation error.
Mrz 19, 2015 11:26:00 AM databaseimport.MyImport executeQuery
SCHWERWIEGEND: null java.sql.SQLException: Data truncated for column
'SHARE' at row 1
I tried changing column to a higher precision with DOUBLE PRECISION(30,30) which seems the maximum for the DOUBLE but the error remains.
Here sample snippet:
Double share = (Double) shareRow.get("share");
sql = ("INSERT INTO `SHARE_VALUES` (`ID`, `SHARE`)" +
"VALUES (NULL, "+share+");");
try
{
// Create a Preparedstatement
PreparedStatement ps;
ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.execute();
ResultSet generatedKeys = ps.getGeneratedKeys();
}
catch (SQLException ex)
{
java.util.logging.Logger.getLogger(Shares.class
.getName()).log(Level.SEVERE, null, ex);
return -1;
}
Try doing this instead:
sql = String.format(Locale.US, "INSERT INTO `SHARE_VALUES` (`ID`, `SHARE`)" +
"VALUES (NULL, %.3f);", share);
When concatenating strings java might use your locale to turn, for example 6.80 into "6,80" <- the comma (',') sign has different meaning for MySQL and that may certainly cause a lot of problems.
If you intend to use prepared statement, then this would be more like it:
NumberFormat nf = NumberFormat.getInstance(Locale.getDefault());
Double share = nf.parse(shareRow.get("share")).doubleValue();
sql = ("INSERT INTO `SHARE_VALUES` (`ID`, `SHARE`)" +
"VALUES (NULL, ?);");
try
{
// Create a Preparedstatement
PreparedStatement ps;
ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setDouble(1, share);
ps.execute();
ResultSet generatedKeys = ps.getGeneratedKeys();
}
catch (SQLException ex)
{
java.util.logging.Logger.getLogger(Shares.class
.getName()).log(Level.SEVERE, null, ex);
return -1;
}
Note that the query string comes with "?" signs, these indicate parameters. When you call:
ps.setDouble(1, share);
that will specify that, parameter 1 value is share, thus the first "?" sign is replaced by the value of share (totally aware of java to mysql conversions and no issues with locale).
Related
I get an sql error when trying to insert something into my DB.
I give a bunch of input to my method, convert that input into strings or sql time and want to store it.
public static void setCourseList(String courseDescription, String courseName, LocalTime courseStart, LocalTime courseEnd, LocalDate courseDate, DayOfWeek courseDay) {
Connection conn = null;
try {
// db parameters
// path to db relative to run time directory
String url = "jdbc:sqlite:Holiday.db";
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (?, ?,?, ?,?, ?,);";
conn = DriverManager.getConnection(url);
System.out.println("Connected");
Statement stmt = conn.createStatement();
PreparedStatement pstmt = conn.prepareStatement(sqlInsertCourse);
pstmt.setString(1, courseName);
String courseStartString = courseStart.toString();
pstmt.setString(2, courseStartString);
java.sql.Time courseEndTime = Time.valueOf(courseEnd);
pstmt.setTime(3, courseEndTime);
java.sql.Date courseDateDate = java.sql.Date.valueOf(courseDate);
pstmt.setDate(4, courseDateDate);
String courseDayString = courseDay.toString();
pstmt.setString(5, courseDayString);
pstmt.executeUpdate();
pstmt.close();
System.out.println("Connection to SQLite has been established.");
// create tables if they do not exists
stmt.execute(sqlInsertCourse);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
I would expect it to store the input in my db.
I do get an [SQLITE_ERROR] SQL error or missing database (near ")": syntax error) error instead.
Any help is appreciated.
I am new to sql.
Change
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (?, ?,?, ?,?, ?,);";
To
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (?, ?,?, ?,?, ?);"; //<<<<<<<<<< extra comma removed
As per the comment on the line the final comma after the last ? has been removed.
Same as what Mike has answered, you can change it to
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (""put values here"");";
If you are wondering why it doesn't throw you an error, it's because there is no syntax error in the java, there's an error in the SQL which only the database can throw, but you're computer can't recognize. Hope this answers your question.
My java code for SQL Query is
String sqlSt="INSERT INTO users(id,name,place) values ("+null+",'"+request.getParameter("name")+"','"+request.getParameter("place")+"');";
I have tried out
name= a'); DROP TABLE users; --
as well as
place =a'); DROP TABLE users; --
but it returns an Ecxeption as below
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 'DROP TABLE users; --','chennai')' at line 1
Note: when i tried the same in mysql command line. It worked!!!! i don't know what happens in jdbc
The real problem is actually JDBC, it only allows one sql if you dont tell it otherwise.
Look at this question for more info:
Multiple queries executed in java in single statement
But also i would try this instead, name =
a',''); DROP TABLE users; --
Since you specificed 3 columns in your insert:
(id,name,place)
You need to provide 3 values for the sql to be valid, not just 2.
Also you can sent the text null, sending a java null value is not necessary and i am not even sure how that works. I think this might be better:
String sqlSt="INSERT INTO users(id,name,place) values (null,'"+request.getParameter("name")+"','"+request.getParameter("place")+"');";
Instead of null, use an empty string ''
String sqlSt = "INSERT INTO users(id, name, place) values ('', '" + request.getParameter("name") + "', '" + request.getParameter("place") + "');";
It's better to use prepared statements to avoid confusion.
String sqlSt = "INSERT INTO users(id, name, place) values ('', ?, ?)";
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(query);
ps.setString(1, request.getParameter("name"));
ps.setString(2, request.getParameter("place"));
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
ps.close();
}
The real problem is with your Query. It is better to use a PreparedStatement for executing a query.
Your Code should be :
String sqlSt="INSERT INTO users(id,name,place) values (?,?,?)";
PreparedStatement pstmt = null;
try{
pstmt = dbConnection.prepareStatement(sqlSt);
pstmt.setString(1,null);
pstmt.setString(2,request.getParameter("name"));
pstmt.setString(3,request.getParameter("place"));
pstmt.executeUpdate();
}catch (Exception e) {
e.printStackTrace();
} finally {
pstmt.close();
}
If you don't want to use a PreparedStatement, just remove last ; from your query.
So your query will be :
String sqlSt="INSERT INTO users(id,name,place) values ("+null+",'"+request.getParameter("name")+"','"+request.getParameter("place")+"')";
How can I insert into a table with primary key autoincrement?
I want to use prepared statements and I keep getting this error 0<1...
I tried with statement and it works :S
public void insertDobavitelj (String dobavitelj,String naslov, String telefon) {
String query = "INSERT INTO dobavitelj(ime,naslov,telefon) VALUES ('"+dobavitelj+"','"+naslov+"','"+telefon+"')";
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
stmt.executeUpdate(query);
/*stmt = conn.prepareStatement(query);
// stmt.setInt(1, 0);
stmt.setString(0, dobavitelj);
stmt.setString(1, naslov);
stmt.setString(2, telefon);
if (stmt.executeUpdate() == 1) {
JOptionPane.showMessageDialog(frame, "Uspesno ste dodali novega dobavitelja");
}
*/
}catch (ClassNotFoundException e) {
JOptionPane.showMessageDialog(frame,"Class not found - insert dobavitelj" );
}catch (SQLException exception) {
JOptionPane.showMessageDialog(frame, "SQL Exception - insert dobavitelj");
exception.printStackTrace();
}
I've tried with:
"INSERT INTO dobavitelj(ime,naslov,telefon) VALUES ('?'.'?','?')"
"INSERT INTO dobavitelj(idDobavitelja,ime,naslov,telefon) VALUES (?.'?'.'?','?')"
Thanx good people :)
You are using stmt.setString(0, dobavitelj); with a zero as index, the statement indexes start at 1.
Also change your query syntax to this: INSERT INTO dobavitelj(ime,naslov,telefon) VALUES ('?'.'?','?')
you can create a random number variable which you will insert in the auto increment column in mysql. multiply the random number by 1000 to get 999 values or 10000 to have 9999 values limit;
int randomnumber = (int) math.random() * 1000
statement.setInt(1, randomnumber)
Hi I've been trying to insert a string into a sqlite database through java. but the string parameter I'm passing in the values sql statement has quotation marks in it as content. I'm thinking that is the error I'm getting why it isn't inserting into the database. is there a way to bypass the quotation marks in the insert statement. thank you.
this is the code:
public void addNote(String topicadd, String contentadd) throws Exception
{
try
{
getConnection();
statement = conn.createStatement();
statement.executeUpdate("insert into tbl_notes (notes_topic, notes_content) values ('" + topicadd + "', '" + contentadd +"')");
System.out.println("inserted note");
}
catch (Exception m)
{`enter code here`
System.out.println("error insert topic");
System.out.println(m.getMessage());
}
}
this is the parameter kind of long... this is all in contentadd
import java.sql.*;
Resultset rset = null; (this has no new ResultSet() initialization)
Connection conn = null; (this has no new initialization too...)
Statement statement = null; (this has now new initialization)
always.....
try
{
}
catch (Exception e) <- can switch e for any other alphabet
{
e.getMessage();
System.out.println("error this module"); <- personal practice
throw e;
}
- getting connection
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:m.db");
*** this is sqlite connection format 'm.db' is the database name
establish connection first..
statement syntax follows:
statement = conn.createStatement();
rset = statement.executeQuery("select * from tbl_notes");
- executeQuery is used for SELECT sql statements
rset = statement.executeUpdate("insert into tbl_notes (ID, status) values
('100', 'status here');
the whole text is in string contentadd, I'm making a short note-taking program... Well, it doesn't execute the insert statement... error somewhere near (word from text) on command prompt... I'm using sqlite... Please let me know if you need more detail. thank you again.
Use a PreparedStatement to insert values containing special characters:
getConnection();
PreparedStatement statement = conn.prepareStatement("insert into tbl_notes (notes_topic, notes_content) values (?, ?)");
statement.setString(1, topicadd);
statement.setString(2, contentadd);
statement.executeUpdate();
As you see you can use parameters with a PreparedStatement which can contain also quotation marks.
Also you get some protection against SQL injection because the Strings given to a PreparedStatement are escaped accordingly.
I bumped into this problem and i cannot figure out what is wrong with this code. I use jdbc and ms managment system for the databse and its connection.
code:
try {
//create user
preparedStatement = conn.prepareStatement("INSERT INTO Users(name, pass, type) VALUES (nick=?,pass=?,type=?)",
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
preparedStatement.setString(1, user.getNickName());
preparedStatement.setString(2, user.getPassword());
preparedStatement.setInt(3, type);
rs = preparedStatement.executeQuery();
System.out.println(rs.toString());
catch (Exception e) {
System.out.println("Exception: " + e);
}
error:
Exception: com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near '='.
The way you are using the ? characters is invalid in JDBC:
"INSERT INTO Users(name, pass, type) VALUES (nick=?,pass=?,type=?)
One ? represents the whole bind variable. Try
"INSERT INTO Users(name, pass, type) VALUES (?, ?, ?)"
Also, use executeUpdate to execute an insert statement (or update, or delete).
Remove the field names from the value list. These are already in the name list. Also use executeUpdate for database write operations:
preparedStatement =
conn.prepareStatement("INSERT INTO Users(name, pass, type) VALUES (?,?,?)",
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
preparedStatement.setString(1, user.getNickName());
preparedStatement.setString(2, user.getPassword());
preparedStatement.setInt(3, type);
int rowCount = preparedStatement.executeUpdate();