I have a problem when I try to execute my query in Java. when I try to add an object to my database in SQL, it gives me a error saying that the instruction don't send the result set. When I execute the query in sql server, it work fine and it insert the object. Please help me.
public void addAlbum(String title, double price, String genre, String date, String home, String image) {
int number = getData().size();
boolean isThere = false;
Statement statement;
for(int i = 0; i < getData().size();i++){
if(getData().get(i).getTitle().equals(title)){
isThere = true;
}
}
if(!isThere){
try{
statement = connexion.createStatement();
String query = "use albums INSERT INTO dbo.Album(Album.artist_number, title, price, genre, date, home, image) VALUES(" + number + ", '" + title + "', " + price + ", '" + genre + "', '" + date + "', '" + home + "', '" + image + "')";
statement.executeQuery(query);
getData().add(new Album(String.valueOf(number),title, price, genre, date, home));
fireTableRowsInserted(getData().size() -1, getData().size() -1);
}catch(SQLException e){
JOptionPane.showMessageDialog(null,
"Error "
+ e.getMessage(), "Result",
JOptionPane.ERROR_MESSAGE);
}
}else{
JOptionPane.showMessageDialog(null,
"There is already an album with this name", "Result",
JOptionPane.ERROR_MESSAGE);
}
}
You need to use Statement.executeUpdate(String) for INSERT. Statement.executeQuery(String) is for SELECT.
PreparedStatements are better, easier and safer. Using Prepared Statements.
Related
I'm working on a SQL databse on java (android studio project) but i have a weird mistake.
Basically, everytime i have
near "Hello": syntax error in "INSERT INTO GAMES(_id, PRICE, NAME, DEV, PLATFORM) VALUES (0, 70, Hello, Henri, Terrain)"
I have tried like this
public void addGame(String Price, String Name, String Dev, String Platform) {
database = getWritableDatabase();
database.execSQL("INSERT INTO "+ SchemeDB.TAB_GAMES +"("
+ DBS.COL_GAMES_ID +", "
+ DBS.COL_GAMES_PRICE +", "
+ DBS.COL_GAMES_NAME +", "
+ DBS.COL_GAMES_DEV +", "
+ DBS.COL_GAMES_PLATFORM +") VALUES (" + i +", "
+ Price +", "
+ Name +", "
+ Dev +", "
+ Platform +")");
database.close();
}
My DBS is
public interface SchemeDB {
int VERSION = 1;
String DB_NAME = "????";
String TAB_GAMES = "???";
String COL_GAMES_ID = "_id";
String COL_GAMES_PRICE = "PRICE";
String COL_GAMES_NAME = "NAME";
String COL_GAMES_DEV = "DEV";
String COL_GAMES_PLATFORM = "PLATFORM";
}
And i really don't see where is the mistake. Because they're saying "syntax error", but for me, it's look pretty OKAY.
Anyone have a clue ? I'm just trying to insert some things in my Database.
Something like this...
+ "'" + Name + "', "
+ "'" + Dev + "', "
+ "'" + Platform + "')");
This is of course parts of a larger code. It will compile with no problem, but when I call this method I get the error
"syntax error near or at "."" at the position of stmt.executeQuery(SQL).
I would really appreciate the help!
private void Component() {
try {
Statement stmt = con.createStatement();
String SQL = "SELECT component.*, stock.amount_of_component, component.price component.component_type "
+ "FROM component JOIN stock "
+ "ON component.id = stock.component_id "
+ "ORDER BY component.component_type";
ResultSet rs = stmt.executeQuery(SQL);
rs.next();
int id = rs.getInt("ID");
int amount_of_component = rs.getInt("Amount");
String name = rs.getString("Name");
double price = rs.getDouble("Price");
String component_type = rs.getString("Type");
System.out.println(" " + id + amount_of_component + " " + name + " " + price + " " + component_type);
} catch (SQLException err)
{
System.out.println(err.getMessage());
}
}
Typo, missing a comma in the query between component.price and component.component_type :
SELECT component.*, stock.amount_of_component, component.price, component.component_type
FROM component JOIN stock
ON component.id = stock.component_id
ORDER BY component.component_type
Edit: To read the whole result set, put this cycle instead of rs.next()
while(result.next()) {
int id = rs.getInt("ID");
int amount_of_component = rs.getInt("Amount");
String name = rs.getString("Name");
double price = rs.getDouble("Price");
String component_type = rs.getString("Type");
System.out.println(" " + id + amount_of_component + " " + name + " " + price + " " + component_type);
}
Edit2: To print the header, you have to do it manually by putting a System.out.println(" id amount_of_component name price component_type "); before the while.
You missed a comma between 'component.price' and 'component.component_type'
This is the code:
#Override public void update(){
Statement stmt = null;
String company = "";
try {
Connect conn = new Connect();
stmt = conn.makeStatement();
// This creates the SQL statement to update an existing student.
System.out.println("Update employee"
+ " Set employeeID = employeeID,"
+ " firstName = firstName,"
+ " lastName = lastName,"
+ " paRating = paRating,"
+ " status = status,"
+ " manager = managerr,"
+ " level = level,"
+ " company = company"
+ " WHERE employeeID = " + get EmployeeID()
+ "Limit 1");
stmt.execute("Update employee"
+ " Set employeeID = employeeID,"
+ " firstName = firstName,"
+ " lastName = lastName,"
+ " paRating = paRating,"
+ " status = status,"
+ " manager = managerr,"
+ " level = level,"
+ " company = company"
+ " WHERE employeeID = " + get EmployeeID()
+ "Limit 1");
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
System.err.println("Unable to update employee in the database.");
} finally {
}
System.out.println("Employee successfully updated to the database.");
}
I am assuming I have missed something simple & obvious that i just can't see.
This query doesn't update anything - it just sets a whole lot of columns to their existing values. If you want to update them to something else, you'd better pass those "something else" values in somehow.
Two things I note, you probably want a space between getEmployeeID() and Limit 1; Also, assuming you're not running with autoCommit enabled, you need to call Connection.commit(). Finally, you should close your connection and statement objects in the finally block.
I have 80000 recodes that are need to insert into database especially in table: temp(ts, temp)
temp is INT.
The problem is almost 20000 recodes are null, so I am wondering how to insert NULL into DB when dataType is INT.
I tried this:
String val = null;
//insert(ts, val) into temp
String sql = "INSERT INTO temp" + "(val)" + " VALUES" + "('" + val + "')";
Statement st = (Statement) conn.createStatement();
count = st.executeUpdate(sql);
unfortunately insert is failure. Print out the exception message:
Incorrect integer value: 'null' for column 'val' at row 1"
Wish someone can help me with it. Thank you.
You should use a PreparedStatement and use setNull(int, int):
String sql = "INSERT INTO temp(val) VALUES (?)";
PreparedStatement st = con.prepareStatement(sql);
if (/* int value is not null */) {
st.setInt(1, value);
} else {
set.setNull(1, Types.INTEGER);
}
count = st.executeUpdate();
As an alternative to Mark Rotteveel's answer, you can also use PreparedStatement.setObject(int, Object, int).
You specify the SQL Type (3rd Parameter), and if the object is null, it inserts a null automatically. It's faster and easier.
String sql = "INSERT INTO temp(val) VALUES (?)";
PreparedStatement st = con.prepareStatement(sql);
st.setObject(1, value, Types.INTEGER);
count = st.executeUpdate();
You should consider using prepared statements. If you do, you'll find information on how to deal with nulls here and elsewhere.
If you're 100% sure your val value is clean and won't cause SQL Injection (rare, but possible), then the "built string" approach needs to explicitly use null when defining the value:
String sql = "INSERT INTO temp (val) VALUES (";
if (val == null) {
sql += "null";
} else {
sql += val;
}
sql += ")";
I have solved this problem.
The codes update as following:
String sql= null;
if(val.isEmpty()){
System.out.println(val);
System.out.println("Insert ts: " + ts + " val: null");
sql= "INSERT INTO " + table + "(ts,val,pointId)" + " VALUES" + "(" + "'" + ts + "'" + ", " + "NULL" + " , " + "'" + pointId + "'" + ")";
}
else{
System.out.println("Insert ts: " + ts + " val: " + val);
sql= "INSERT INTO " + table + "(ts,val,pointId)" + " VALUES" + "(" + "'" + ts + "'" + ", " + "'" + val + "'" + ", " + "'" + pointId + "'" + ")";
}
Statement st = (Statement) conn.createStatement(); //create the instances of statement
count = st.executeUpdate(sql);
Basically, if insert null into database, just do insert into table(val) value(NULL).
You should explicitly CAST the NULL as an INT
...VALUES(...CAST(NULL AS INT)
It sounds like your are sending "null" in when you should be sending an int. Perhaps try something like
(val == null ? "" : val)
I have two method one is working and other's not working for insert query
// this one fails
public void product(String product, String quantity, String price,
String date) throws SQLException {
try {
statement.execute("INSERT INTO product (productn,quantity,price,date) VALUES ('" + product + "','" + quantity + "','" + price + "','" + date + "')");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
// this one works
public void customer(String name, String q, String p, String pro)
throws SQLException {
try {
statement.execute("INSERT INTO Customer (name,price,product,quantity) VALUES ('" + name + "','" + q + "','" + p + "','" + pro + "')");
} catch (Exception e) {
System.out.println("problem in Customer insert !");
}
}
one method which is working fine mean it insert data into the table but the other is giving the following error:
[Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement
Try this:
INSERT INTO product ([productn],[quantity],[price],[date]) VALUES ('" + product + "','" + quantity + "','" + price + "','" + date + "')
And let me know if it works
You'll have more chance to do it in this way, like that you could check better the integrity of the values.
private static final String insert = "INSERT INTO product (productn,quantity,price,date) VALUES ('"+?+"','"+?+"','"+?+"','"+?+"')";
statement.clearParameters();
statement.set"Type_of_the_value"(1, productn) ;
statement.set"Type_of_the_value"(2, quantity) ;
statement.set"Type_of_the_value"(3, price) ;
statement.set"Type_of_the_value"(4, date) ;
statement.executeUpdate() ;