I don't know what is wrong with my code below.
try {
String sql = "INSERT INTO `myporject`.`selectnation` (`nations` ,`package` ,`persons`) "
+ "VALUES ('?', ?, ?)";
PreparedStatement ps = connect.prepareStatement(sql);
if (ps.executeUpdate() != -1) {
ps.setString(1,"Japan" );
ps.setInt(2, this.pack);
ps.setString(3, jTextField1.getText());
And this is StackTrace
java.sql.SQLException: No value specified for parameter 1
You are trying to execute the prepareStatement before setting the parameters, so you need to change your code as follows:
PreparedStatement ps = connect.prepareStatement(sql);
//set the parameters first
ps.setString(1,"Japan" );
ps.setInt(2, this.pack);
ps.setString(3, jTextField1.getText());
//now execute the prepared statement
if (ps.executeUpdate() != -1) {
//add your code
}
I suggest you refer here to understand the jdbc concepts.
Related
Hello everyone can someone tell me what is wrong here ?
I have a task i was asked and i am new in connecting oracle databases with java servlet.
here is me code:
try {
out.print("first");
Class.forName("oracle.jdbc.OracleDriver");
out.print("aaa");
Connection con
= DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe", "myusername", "mypassword");
out.print("111");
PreparedStatement ps = con
.prepareStatement(
"INSERT INTO signup
values(fn, ln, date, em, pa, crnum)
");
out.print("222");
ps.setString(1, fn);
ps.setString(2, ln);
ps.setString(3, da);
ps.setString(4, em);
ps.setString(5, pa);
ps.setString(6, cr);
int i = ps.executeUpdate();
if (i > 0) {
out.print("You are successfully registered...");
}
} catch (Exception e2) {
out.println(e2);
}
out.close();
response.sendRedirect("address");
/* when press next bottom
it'll take me to add.html*/
and after i ran the whole code i get this :java.sql.sqlexception: invalid column index
In your SQL statement, you have to provide the tokens or placeholders for your bind variable like in the following...
PreparedStatement ps = con.prepareStatement("INSERT INTO signup values(?,?,?,?,?,?)");
ps.setString(1,fn);
ps.setString(2,ln);
ps.setString(3,da);
ps.setString(4,em);
ps.setString(5,pa);
ps.setString(6,cr);
You need to use placeholder ?:
PreparedStatement ps = con.prepareStatement("INSERT INTO signup values (?,?,?,?,?,?)");
I'm having an issue with adding data to a sql database through Java on Netbeans.
String bladeSerial;
String bladeType;
LocalTime startTime1;
private void startButton2ActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn = null;
Statement st = null;
try {
conn = DriverManager.getConnection ("jdbc:derby://localhost:1527/db01", "Administrator", "admin"); //run procedure getConnection to connect to the database - see below
st = conn.createStatement(); //set up a statement st to enable you to send SQL statements to the database.
} catch (SQLException ex) {
Logger.getLogger(FormTwo1.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println ("Successful Connection");
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values ('+bladeSerial+', '+itemText+', '+(String.valueOf(startTime1))+')";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, bladeSerial);
pstmt.setString(2, bladeType);
pstmt.setString(3, String.valueOf(startTime1));
pstmt.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(FormTwo1.class.getName()).log(Level.SEVERE, null, ex);
}
I get the error The column position '1' is out of range. The number of columns for this ResultSet is '0'.
In the database, Serial is VARCHAR(5), Bladetype is VARCHAR(80)and StartT1 is VARCHAR(12)
The startTime1 variable is saved in the format HH:mm:ss.SSS.
I appreciate any help on this error
You need to give placeholder in your query. Change your code as given here...
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, bladeSerial);
pstmt.setString(2, bladeType);
pstmt.setString(3, String.valueOf(startTime1));
pstmt.executeUpdate();
You don't need to give column names in query when you are using Prepared statement. Do the following changes:
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values (?, ?, ?)";
Hope it helps!!
Here you are forming query like simple statement and used it in prepared statement which is not possible, so change your query with place holder like below.
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values (?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, bladeSerial);
pstmt.setString(2, bladeType);
pstmt.setString(3, String.valueOf(startTime1));
pstmt.executeUpdate();
If you want to directly use variables names like bladeSerial, then you should use these String variables as if you're adding multiple Strings.
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values ("+bladeSerial+", "+itemText+", "+(String.valueOf(startTime1))+")";
But this is strictly not recommended as it would introduce serious security issues.
The recommended way is to use PreparedStatement. The query you've written is correct, it's just that you have to use placeholders instead of variable names.
String query = "insert into TB01(SERIAL,BLADETYPE,STARTT1) values (?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(query)) {
pstmt.setString(1, bladeSerial);
pstmt.setString(2, bladeType);
pstmt.setString(3, String.valueOf(startTime1));
pstmt.executeUpdate();
} catch (SQLException ex) {
// Exception handling
Logger.getLogger(FormTwo1.class.getName()).log(Level.SEVERE, null, ex);
}
I have a problem using mysql update in eclipse jsp file.
I just use pstmt.executeUpdate in my jsp file. that's work right.
but when I reuse pstmt.executeUpdate for updating another host's database i can't update mysql data.
when I update second executeUpdate without update's "where" query, it's work right. I can update mysql data.
but only the problem is that when i update executeUpdate with "where", I cannot update the mysql data.
case1(no problem)
use preparedStatement1, update query with 'where' -> OK
use preparedStatement2, update query without 'where' -> OK
case2(problem)
use preparedStatement1, update query with 'where' -> OK
use preparedStatement2, update query with 'where' -> update fail
(and I already test my code in mysql workbench, there is no problem first UPDATE and second UPDATE with 'where'. I have only a problem adding update with 'where' code in my eclipse.)
behind is a my code.
String DB_USER = (String)session.getAttribute("id");
String DB_PASSWORD = (String)session.getAttribute("password");
String DB_HOST = "jdbc:mysql://rds01.********.ap-northeast-2.rds.amazonaws.com:3306/inventory_" + DB_USER + "?useUnicode=true&characterEncoding=euckr";
Connection con;
PreparedStatement pstmt;
String query = "UPDATE inventory_"+DB_USER+" SET "
+ "color1_size1 = ?, color1_size2 = ?, color1_size3 = ?, color1_size4 = ?, color1_size5 = ?, color1_size6 = ?, color1_size7 = ?, color1_size8 = ? "
+ "WHERE NAME = ? AND YEAR = ?";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(DB_HOST, DB_USER, DB_PASSWORD);
pstmt = con.prepareStatement(query);
pstmt.setInt(1, color1_size1);
pstmt.setInt(2, color1_size2);
pstmt.setInt(3, color1_size3);
pstmt.setInt(4, color1_size4);
pstmt.setInt(5, color1_size5);
pstmt.setInt(6, color1_size6);
pstmt.setInt(7, color1_size7);
pstmt.setInt(8, color1_size8);
pstmt.setString(9, name);
pstmt.setString(10, year);
pstmt.executeUpdate();
pstmt.close();
con.close();
String query_all = "UPDATE inventory_all SET "
+ "color1_size1 = ?, color1_size2 = ?, color1_size3 = ?, color1_size4 = ?, color1_size5 = ?, color1_size6 = ?, color1_size7 = ?, color1_size8 = ? "
+ "WHERE NAME = ? AND YEAR = ?";
//behind host is another host with upper host.
DB_HOST = "jdbc:mysql://rds01.************.ap-northeast-2.rds.amazonaws.com:3306/inventory_all?useUnicode=true&characterEncoding=euckr";
con = DriverManager.getConnection(DB_HOST, DB_USER, DB_PASSWORD);
pstmt = con.prepareStatement(query_all);
pstmt.setInt(1, color1_size1);
pstmt.setInt(2, color1_size2);
pstmt.setInt(3, color1_size3);
pstmt.setInt(4, color1_size4);
pstmt.setInt(5, color1_size5);
pstmt.setInt(6, color1_size6);
pstmt.setInt(7, color1_size7);
pstmt.setInt(8, color1_size8);
pstmt.setString(9, name);
pstmt.setString(10, year);
//------------upper code is OK, behind code is a problem ----------------
pstmt.executeUpdate();
pstmt.close();
con.close();
} catch(Exception e) {e.printStackTrace();}
Use different PreparedStatement object for second query. Because
a
preparedstatement asks for the sql and immediatly compiles itself.
PreparedStatement pstmt1 = con.prepareStatement(sql1);
pstmt1.executeUpdate();
PreparedStatement pstmt2 = con.prepareStatement(sql2);
pstmt2.executeUpdate();
oh, I know the problem. I add the mysql privilege only update, delete, insert not select in database id.
as I add the 'select' privilege to my id, I can update in my database.
thank for all answer!
Can't seem to fix this. Been trying to get it to work for the past hour. any help would be appreciated.
INFO: Server startup in 868 ms
java.sql.SQLException: Can not issue data manipulation statements with executeQuery().Event{id=0, name='dads', venue='dasd', startDate='11/11/11', endDate='12/11/11'}
Seemed to be getting an error when I try to do an insert.
public void addEvent(Event event) throws DaoException{
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = this.getConnection();
String query = "INSERT INTO TABLE EVENT VALUES(null, ?, ?, ?, ?)";
ps = con.prepareStatement(query);
ps.setString(1, event.getName());
ps.setString(2, event.getVenue());
ps.setString(3, event.getStartDate());
ps.setString(4, event.getEndDate());
rs = ps.executeQuery();
}catch(SQLException e) {
System.out.println(event.toString());
e.printStackTrace();
}finally {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (con != null) {
freeConnection(con);
}
} catch (SQLException e) {
throw new DaoException("Couldn't " + e.getMessage());
}
}
}
for inserting or updating or deleting you should use executeUpdate()
executeUpdate() returns int value
so replace this line rs = ps.executeQuery(); with
int result = ps.executeUpdate();
Note you will get another error after modifying as per above because you sql query is also wrong
Use the following query
INSERT INTO EVENT VALUES(null, ?, ?, ?, ?)
it looks like incorrect syntax of INSERT Query, update it likewise
INSERT INTO EVENT VALUES(null, ?, ?, ?, ?) // remove TABLE word
//INSERT INTO TABLE_NAME VALUES(...) , this is correct syntax.
also correct here too
executeUpdate() instead of executeQuery()
// for insert/update/delete query always use executeUpdate(),
// for select query use executeQuery()
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();