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)
Related
I created a table in Mysql using
Create table
(
id int auto_increment,
us varchar(100),
ps varchar(1000)
);
And used java for adding values thru my GUI application:
I used the following method to add values into my database:
public static void Mysql(String u, String p) throws NoSuchAlgorithmException, InvalidKeySpecException
{
String hashpass=passhash(p);//throws declaration for this statement
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bs","root","root");
String query = " insert into login (id,us,ps)"
+ " values (?,?, ?)";
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from login");
int id=0;
while(rs.next())
{
id= rs.getInt(1);
}
PreparedStatement preparedStmt = con.prepareStatement(query);
preparedStmt.setInt(1, id++); //I don't want this method because id is auto increment
preparedStmt.setString(2,u);
preparedStmt.setString(3,hashpass);
preparedStmt.execute();
con.close();
}catch(Exception e){ System.out.println(e);}
}
Everything works fine
But the id is the auto_increment and I don't need to add value to id while adding other column values.
I can't add like that while adding thru java like only adding us, ps columns and the id will be automatically incremented.
Are there any methods to add data without passing the parameters?
Remove the column id from the sql statement:
String query = "insert into login (us, ps) values (?, ?)";
and don't set any value for it in the prepared statement, so remove this line:
preparedStmt.setInt(1, id++);
The column id is auto_inrement so its value will be set by MySql.
Of course change the indices of the other lines to 1 and 2:
preparedStmt.setString(1,u);
preparedStmt.setString(2,hashpass);
You might insert data without ID as it will be auto-generated from SQL
public static void Mysql(String u,String p) throws NoSuchAlgorithmException, InvalidKeySpecException {
String hashpass=passhash(p);
try{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/bs","root","root");
String query = " insert into login (us,ps) values (?, ?)"; // CHECK HERE
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from login");
PreparedStatement preparedStmt = con.prepareStatement(query);
preparedStmt.setString(1,u);
preparedStmt.setString(2,hashpass);
preparedStmt.execute();
con.close();
}catch(Exception e){
System.out.println(e);}
}
}
public boolean saveScore1(Score obj) {
boolean returnValue = false;
String sql = "insert into score(e_id,u_id,u_score,y_id,b_id) values(?,?,?,?,?)";
try {
Connection connection = DBConnectionHandler.getConnection();
PreparedStatement ps = connection.prepareStatement(sql);
ps.setInt(1, obj.getEId());
ps.setInt(2, obj.getUId());
ps.setString(3, obj.getUScore());
ps.setInt(4, obj.getYId());
ps.setInt(5, obj.getBId());
int i = ps.executeUpdate();
if (i > 0) {
returnValue = true;
}
} catch (Exception e) {
e.printStackTrace();
}
return returnValue;
}
Here are the three table i'm using
Examtable: e_id integer(auto increment) pk,e_name varchar
UserTable: u_id integer(auto increment)pk,u_name varchar
ScoreTable: s_id integer(auto increment)pk ,u_id integer fk, e_id integer fk, u_score
I want to send multiple data to score table at a time with one sql query for same u_id but different e_id, beacuse e_id will contains different value like B.B.A,M.B.A, B.sc, M.sc etc. So one user can have different exam pass.
I'm using above java code to insert but i just take the last value from front-end jsf form.
How can i send multiple rows for same u_id with different e_id at a time.
First of all, you don't insert data with a SQL query. A query is a SELECT statement.
Using JDBC, you can batch multiple insert statements, such that number of round trips to the database are reduced (for performance). Functionally, it is the same as inserting one row at a time.
Since you are inserting multiple rows, you probably want all to succeed, or all to fail, so you need to do your own commit or rollback.
Of course, since to do want to insert multiple score rows, your method should take a List<Score>.
public boolean saveScores(List<Score> scores) {
String sql = "insert into score(e_id,u_id,u_score,y_id,b_id) values(?,?,?,?,?)";
try (Connection connection = DBConnectionHandler.getConnection()) {
connection.setAutoCommit(false);
try {
try (PreparedStatement ps = connection.prepareStatement(sql)) {
for (Score score : scores) {
ps.setInt (1, score.getEId());
ps.setInt (2, score.getUId());
ps.setString(3, score.getUScore());
ps.setInt (4, score.getYId());
ps.setInt (5, score.getBId());
ps.addBatch();
}
ps.executeBatch();
}
connection.commit();
} catch (Exception e) {
connection.rollback();
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
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).
This is code section:
public int deleteStatement() throws SQLException {
Connection conn = null;
try {
conn = getConnectivity(conn);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String sql = "DELETE from USER_DETAILS where USERNAME=?";
getConnectivity(conn);
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(4, "rother09");
int rows = ps.executeUpdate();
System.out.println(rows + " DELETED");
return rows;
}
Connection Valid
Connection Valid
java.sql.SQLException: Invalid column index
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
atoracle.jdbc.driver.OraclePreparedStatement.setStringInternal(OraclePreparedStatement.jav a:5360)
at oracle.jdbc.driver.OraclePreparedStatement.setString(OraclePreparedStatement.java:5352)
atcom.platform.BilalsProject.DataAccessUtility.deleteStatement(DataAccessUtility.java:163)
at com.platform.BilalsProject.DataAccessUtility.main(DataAccessUtility.java:40
I am trying to delete from my table and it keeps giving me "invalid column index", can't see where I am going wrong.
In my database I have column 4 as password and 5 as username. The code works fine in sql worksheet.
First thing why getConnectivity(conn); twice in the same method
Secondly your query
String sql = "DELETE from USER_DETAILS where USERNAME=?"; takes in one parameters
so in that case your ps.setString(4, "rother09");
should change to
ps.setString(1, "rother09");
Note it that setString(int parameterIndex, String x) doesnot mean you column index it actually means the index of the parameters used in the query suppose you query is like
SELECT * from USER_DETAILS WHERE USERNAME=? AND PASSWORD = ?
Then
ps.setString(1, "rother09");// for the first parameter i.e USERNAME
ps.setString(2, "password");// for the second parameter i.e PASSWORD
I need to check the box no if exist in the database under the remittance id that I enter if the box no exists then i need to show the message that the box no already exists but if it doesn't the it should insert new box i have written some code but its showing error
private void txtboxnoFocusLost(java.awt.event.FocusEvent evt) {
DBUtil util = new DBUtil();
try {
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement(
"select box_no from dbo.soil_det where rm_id = ? and box_no = ?");
stmt.setLong(1, Long.parseLong(tf_rm_id.getText()));
stmt.setString(1, (txtboxno.getText()));
ResultSet rs=stmt.executeQuery();
while(rs.next()){
rs.equals().txtboxno.getText());
}
JOptionPane.showMessageDialog(rootPane, "hello!S");
} catch (Exception ex) {
Logger.getLogger(DATAENTRY.class.getName()).log(Level.SEVERE, null, ex);
}
Try this code
private void txtboxnoFocusLost(java.awt.event.FocusEvent evt) {
DBUtil util = new DBUtil();
try {
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement(
"select box_no from dbo.soil_det where rm_id = ? and box_no = ?");
stmt.setLong(1, Long.parseLong(tf_rm_id.getText()));
stmt.setString(2, (txtboxno.getText()));
ResultSet rs=stmt.executeQuery();
bool recordAdded = false;
while(!rs.next()){
/// Do your insertion of new records
recordAdded = true;
}
if( recordAdded ){
JOptionPane.showMessageDialog(rootPane, "Record added");
}else{
JOptionPane.showMessageDialog(rootPane, "Record already exists");
}
} catch (Exception ex) {
Logger.getLogger(DATAENTRY.class.getName()).log(Level.SEVERE, null, ex);
}
or you could use a count:
String query = "select count(*)
from dbo.soil_det where rm_id = ? and box_no = ?";
then after executing the query you get the count with
rs.getInt(1)
using that you can decide which info to show to the user
very First You have to get count using sql if count is greater than zero then do not insert records and show message like already exists and in else part insert record. see following example
private boolean findCount(int rm_id,String box_no)
{
int count=0;
//write query here
count = assign query result;
//check count
if(count>0)
{
return false;//records exists
}else{
return true;//records do not exists
}
}
public void insertData()
{
if(findCount(1,"1")){//pass values
//Write down your insert logic
}else{
JOptionPane.showMessageDialog(rootPane, "Records Already Exists");
}
}
Note: Friend in Your Example you have not written the insert logic. only select was there
First you could add -- on the db table -- a unique constrain on the columns (rm_id, box_no), this is anyway a good thing to do.
Then you could simply try to insert the box and catch the exception and check if it is a violation of the unique constraint.
Another option (still keeping the unique constraint) would be to make a more complicated SQL insert statement that inserts only if not existing, you may google "sql insert if not exist" to find some examples...
You need to get the appropriate record from the ResultSet e.g.
boolean found = rs.getString(1).equals().txtboxno.getText());
At the moment you're simply comparing the ResultSet object itself to a string, and that won't work. The above pulls the first record from the ResultSet and performs the comparison on that (note: your datatype may be different and you may need rs.getInt(1) etc.)
Perhaps its sufficient in your case just to check if you have a ResultSet result (via rs.next())
simplified version
private void txtboxnoFocusLost(java.awt.event.FocusEvent evt) {
DBUtil util = new DBUtil();
try {
Connection con = util.getConnection();
PreparedStatement stmt = con.prepareStatement(
"select box_no from dbo.soil_det where rm_id = ? and box_no = ?");
stmt.setLong(1, Long.parseLong(tf_rm_id.getText()));
stmt.setString(2, (txtboxno.getText()));
ResultSet rs=stmt.executeQuery();
if(!rs.next()){
JOptionPane.showMessageDialog(rootPane, "Record added");
}else{
JOptionPane.showMessageDialog(rootPane, "Record already exists");
}
} catch (Exception ex) {
Logger.getLogger(DATAENTRY.class.getName()).log(Level.SEVERE, null, ex);
}
rs.next() followed by if condition returns true if the record exists in a table. if not, return false.