Parameter index out of range ( 2 number of parameters,which is 1) - java

I got this problem in my code java.sql.Exception: Parameter index out of range ( 2 number of parameters,which is 1).
This is my code:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/t201835006","root","p73421231");
String mysql = "insert into books (bookName,Author,Perinting,Available) VALUES ('?','?',?,'True')";
PreparedStatement pstmt = conn.prepareStatement(mysql);
pstmt.setString(1,jTextField1.getText());
pstmt.setString(2,jTextField2.getText());
pstmt.setInt(3,Integer.parseInt(jTextField3.getText()));
pstmt.executeUpdate();
JOptionPane.showMessageDialog(null,"insertion successful");
I tried :
"insert into books VALUES ('?','?',?,'True')";
"insert into books VALUES (?,?,?,'True')";
but it didn'T work.
My other codes in same project includes same databases but it works. I want to share iw for you:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/t201835006","root","p73421231");
String sql ="insert into customerinfo values (?, ?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1,jTextField3.getText());
pstmt.setString(2,jTextField1.getText());
pstmt.setInt(3,Integer.parseInt(jTextField2.getText()));
pstmt.setString(4,jTextField4.getText());
pstmt.executeUpdate();
JOptionPane.showMessageDialog(null,"insertion successful");
new Menu().setVisible(true);
dispose();
I don't know why the first code doesn't work help me.

Related

Java String insertion to MySQL field of type MEDIUMTEXT

I'm taking a string and inserting it into a mySQL database field of type MEDIUMTEXT. When I print it out, there is a bunch of '-' characters and whitespace surrounding a slightly corrupted version of my original text. Am I doing this wrong?
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/tripDB?characterEncoding=utf8","root","pass");
Statement stmt = con.createStatement();
query = "insert into trip (name, date, details) values (?, ?, ?)";
PreparedStatement preparedStmt = con.prepareStatement(query);
preparedStmt.setString(1, name); //Inserts correctly (varchar)
preparedStmt.setString(2, date); //Correct (varchar)
preparedStmt.setString(3, details); //Corrupted (MEDIUMTEXT)
preparedStmt.execute();
con.close();

Insert multiple data (List) in MySQL using JDBC

I am trying it from last 2 hour i dont know what is going wrong. also let me know how could i test if the connection is successfull or not.. it is for now.. but still i wanted to know..
Error:
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 '?, ?)'
My code:
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/medicinedb";
static final String USER = "root";
static final String PASS = "";
static final String DRIVER = "com.mysql.jdbc.Driver";
public boolean saveMedicine(List<MedicineName> medicineName) throws ClassNotFoundException {
Connection conn = null;
Statement stmt = null;
try {
Class.forName(DRIVER);
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
for (MedicineName element : medicineName) {
String sql;
sql = " insert into medicinename (name, pgurl)" + " values
( ?, ?)";
System.out.println(conn);
PreparedStatement preparedStmt = conn.prepareStatement(sql);
preparedStmt.setString(1, element.getName());
preparedStmt.setString(2, element.getPgurl());
stmt.executeUpdate(sql);
}
stmt.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
Why you are using Statement and Prepared statement. You are performing operations with Statement. Thus it does not have value. Remove the Statement
stmt = conn.createStatement();
And do the following
PreparedStatement preparedStmt = conn.prepareStatement(sql);
preparedStmt.setString(1, element.getName());
preparedStmt.setString(2, element.getPgurl());
//stmt.executeUpdate(sql);
preparedStmt .executeUpdate(sql);
use
String sql = "insert into medicinename (name, pgurl) values (?, ?)";
PreparedStatement preparedStmt = conn.prepareStatement(sql);
preparedStmt.setString (1, element.getName());
preparedStmt.setString (2, element.getPgurl());
preparedStmt.executeUpdate();
you should delete executeUpdate(sql); to executeUpdate();
You mix between your stm and preparedStmt, you have to execute preparedStmt and not stm.
Another thing when you want to executing multiple statements as one unit, its good to work with Statement Batching instead for example :
PreparedStatement preparedStmt;
String sql;
conn.setAutoCommit(false);
for (MedicineName element : medicineName) {
sql = "insert into medicinename (name, pgurl) values (?, ?)";
System.out.println(conn);
preparedStmt = conn.prepareStatement(sql);
preparedStmt.setString(1, element.getName());
preparedStmt.setString(2, element.getPgurl());
preparedStmt.addBatch(sql);
}
preparedStmt.executeBatch();
conn.commit();

Insert database mysql get issue

i got issue when i go to Insert value to DB (do nothing).
before that i do select table to get last id, and it worked.
Here's my Code:
IDBManager dbManager = getParentExtension().getParentZone().getDBManager();
Connection connection = null;
int idRoom = params.getInt("idRoom");
String betsmall = params.getUtfString("betsmall");
int Uid = params.getInt("recid");
try{
connection = dbManager.getConnection();
PreparedStatement stmt = connection.prepareStatement("SELECT id_game from detail_game ORDER BY id_game DESC LIMIT 1");
ResultSet res = stmt.executeQuery();
if (!res.first())
{
trace("bla bla");
}
int id = res.getInt("id_game");
trace (id);
// **till here there is no problem, i can get id from select query
PreparedStatement stmts = connection.prepareStatement("INSERT INTO detil_bet (id_user, id_room, id_bet, bettype) VALUES (?, ?, ?, ? ");
stmts.setInt(1, Uid);
stmts.setInt(2, idRoom);
stmts.setInt(3, id);
stmts.setString(4, betsmall);
stmts.executeUpdate();
}
}
Here's the problem, insert do nothing.
PreparedStatement stmts = connection.prepareStatement("INSERT INTO detil_bet (id_user, id_room, id_bet, bettype) VALUES (?, ?, ?, ? ");
Looks like you need some end parentheses in "VALUES".
A catch block to print stack trace would have told you the issue here as well. I'm not the best SQL guy, I always use this to check my SQL syntax as well to double check if I've done everything right.
your connection seems not auto commit. Try to add
stmts.commit();
after "stmts.executeUpdate();".

How to get sequence.nextval from SQL in JDBC?

I have 5 tables where I use the same sequence's next value. The problem is, the subsequent tables gets a bigger value than the previous ones.
My code is like this:
String sql = "INSERT INTO table1(id, name) VALUES (id_seq.nextval, ?)";
ps.setString(1, "bar");
ps.executeUpdate();
sql = "INSERT INTO table2(id, name) VALUES (id_seq.nextval, ?)";
ps.setString(1, "tar");
ps.executeUpdate();
sql = "INSERT INTO table3(id, name) VALUES (id_seq.nextval, ?)";
ps.setString(1, "par");
ps.executeUpdate();
sql = "INSERT INTO table4(id, name) VALUES (id_seq.nextval, ?)";
ps.setString(1, "car");
ps.executeUpdate();
sql = "INSERT INTO table5(id, name) VALUES (id_seq.nextval, ?)";
ps.setString(1, "rar");
ps.executeUpdate();
My sequence is like this:
CREATE SEQUENCE "ID_SEQ" MINVALUE 1 MAXVALUE 9999999999 INCREMENT BY 1 START WITH 10 CACHE 20 NOORDER NOCYCLE ;
Now when I look at my tables, table1's ID is 10, but table2's ID is 11 and table3's ID is 12..... I want all the tables' IDs to be same. What should I do?
Thank you in advance.
edit: Had to include more tables than 2 to have more general question
Actually I found the answer online. I need to do this:
String sql = "select ID_SEQ.nextval from DUAL";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if(rs.next())
int nextID_from_seq = rs.getInt(1);
And when I insert this value to database, I type this:
String sql2 = "INSERT INTO table1(id, name) VALUES (?, ?)";
ps.setInt(1, nextID_from_seq);
ps.setString(2, "tar");
ps.executeUpdate();
sql2 = "INSERT INTO table2(id, name) VALUES (?, ?)";
ps.setInt(1, nextID_from_seq);
ps.setString(2, "par");
ps.executeUpdate();
...
...
The first string sql is "select ID_SEQ.nextval from DUAL." That "DUAL" in the end is not table name or anything. It's just one of the given or provided functionality by oracle. I can get any sequence's nextval by using it.
You can use id_seq.currval for the second table. It will reuse the same id.
sql = "INSERT INTO table2(id, name) VALUES (id_seq.currval, ?)";

Java Netbeans MySql database Connection

I want to insert row into MySql database with a normal Program for Mysql connection in Java Netbeans,but when i run this code my database remains unaffected.I had setup connection with Netbeans and Mysql and it is working fine.
Code:
import java.sql.*;
public class MySqlConnection {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/migration";
static final String USER = "root";
static final String PASS = "ngts12345";
public static void main(String[] args) {
Connection conn = null;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
System.out.println("Inserting records into the table...");
String sql = "INSERT INTO document (document_id, document_name, format)" +
"VALUES (?, ?, ?)";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setInt(1, 1);
preparedStatement.setString(2, "Test2");
preparedStatement.setString(3, "Test3");
preparedStatement.executeUpdate();
preparedStatement.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
}catch(Exception e){
//Handle errors for Class.forName
}
}
}
there is not space after format) and values
Change this line to
String sql = "INSERT INTO document (document_id, document_name, format)" +
"VALUES (?, ?, ?)";
to
String sql = "INSERT INTO document(document_id, document_name, format) " +
"VALUES (?, ?, ?)";
Try doing this:
preparedStatement.executeUpdate(sql);
and you should also specify database
String sql = "INSERT INTO database_name.document (document_id, document_name, format)" +"VALUES (?, ?, ?)";
try{
Class.forName("com.mysql.jdbc.Driver"); // MySQL database connection
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306","root","");
String sql = "select * from 'table_name'.database_name where user=? and pass=?";
pst = conn.prepareStatement(sql);
rs= pst.executeQuery();
}
Note preparedStatement.executeUpdate() returns true (record was successful in insert, update, or delete) or false (not successful). Therefore I suggest printing out the result to see if it worked.
As for not getting an error message, are you consuming exceptions and not printing out the error? In your catch block, put e.printStackTrace() to see what the error is.

Categories