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);}
}
}
Related
I want to insert the product the user selected into a table called cart which has two columns: cart_id and item_id_FK both are foreign keys. User_id and id are passed in the constructor and then inserted into cart_id and item_id_fk.
No errors are showing in the code, I double checked the connection username and password, everything works fine except for the cart table.
I tried putting a try and catch statement inside and repeating the steps it didn't work.
if (e.getSource()==AddToCartBtn)
{
//Check to see if item is available
String SizeSelection;
SizeSelection = SizeCmbx.getSelectedItem().toString();
String DBURL ="JDBC:MySql://localhost:3306/shoponline?useSSL=true";
String USER ="root";
String PASSWORD ="12345678";
try {
Connection con = DriverManager.getConnection(DBURL, USER, PASSWORD);
String sql2 = String.format("select itemid,size,productid_fk from items where size='%s' and productid_fk=%d",SizeSelection,id);
PreparedStatement statement = con.prepareStatement(sql2);
ResultSet result = statement.executeQuery(sql2);
String sql3 = "insert into cart (CartID, ItemID_FK)" + " values (?, ?)";
PreparedStatement preparedStmt = con.prepareStatement(sql3);
preparedStmt.setInt(1, user_ID);
preparedStmt.setInt(2, id);
if(result.next())
{
//if item is available
// execute the preparedstatement
preparedStmt.execute();
}//end if
con.close();
}// end try
catch (SQLException ex){
ex.printStackTrace();
}//end catch
Change executeQuery to executeUpdate:
executeQuery(sql3)
to
executeUpdate(sql3)
I believe integers don't need the ' ' around them to be inserted, you may try removing those as well. It may be mistaking them as characters or something similiar.
Otherwise if neither of those above fixes work, try something like this:
String query = "insert into cart (CartID, ItemID_FK)"
+ " values (?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt(1, xInt);
preparedStmt.setInt(2, yInt);
// execute the preparedstatement
preparedStmt.execute();
conn.close();
I have simple program that works with mysql db. I need to switch to oracle db.
I am trying to insert data into database but I'm getting this error. I tried manually to insert data everyting is fine but programatically I got error.
This is my code.
public void saveHasta(List<Hasta> hastaList) {
try {
// PreparedStatement stmt = connection.prepareStatement("INSERT INTO tblHasta (hasta_tc_kimlik,hasta_isim, hasta_soyisim,hasta_dogum_tarih,hasta_meslek,randevu_ID) VALUES (12345678912, 'Mert', 'Akel', '1995-07-21', 'Yazilim', 2)");
//
// System.out.println("Oldu");
PreparedStatement stmt = connection.prepareStatement("INSERT INTO tblHasta (hasta_tc_kimlik,hasta_isim, hasta_soyisim,hasta_dogum_tarih,hasta_meslek,randevu_ID) VALUES (?,'?','?','?','?',?)");
Iterator<Hasta> it = hastaList.iterator();
while (it.hasNext()) {
Hasta h = it.next();
stmt.setLong(1, h.getTcKimlik());
stmt.setString(2, h.getIsim());
stmt.setString(3, h.getSoyIsim());
stmt.setString(4, h.getDogumTarih());
stmt.setString(5, h.getMeslek());
PreparedStatement pst = connection.prepareStatement(
"SELECT randevu_ID FROM tblRandevu where tc_kimlik = '" + h.getTcKimlik() + "'");
ResultSet rs = pst.executeQuery();
while (rs.next()) {
randevu_id = rs.getInt("randevu_ID");
}
stmt.setInt(6, randevu_id);
stmt.addBatch();
}
stmt.executeUpdate();
System.out.println("Oldu");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This is my table
CREATE TABLE tblhasta
( hasta_ID INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1) NOT NULL,
hasta_tc_kimlik INTEGER,
hasta_isim varchar2(50),
hasta_soyisim varchar2(50),
hasta_dogum_tarih varchar2(50),
hasta_meslek varchar2(50),
randevu_ID INTEGER,
CONSTRAINT hasta_pk PRIMARY KEY (hasta_ID)
);
You have used the prepared statements in a wrong way
PreparedStatement stmt = connection.prepareStatement("INSERT INTO tblHasta (hasta_tc_kimlik,hasta_isim, hasta_soyisim,hasta_dogum_tarih,hasta_meslek,randevu_ID)
VALUES (?,'?','?','?','?',?)");
Change values to
PreparedStatement stmt = connection.prepareStatement("INSERT INTO tblHasta (hasta_tc_kimlik,hasta_isim, hasta_soyisim,hasta_dogum_tarih,hasta_meslek,randevu_ID)
VALUES (?,?,?,?,?,?)");
I have to insert values from jsp form to database table and to the same table I need to insert values for two columns from 2 different tables.
Here is the code:
public class ForgotPassWordDAO {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
public void createSecretQnA(ForgotPassWord forgotPassWord) {
String sql = "INSERT INTO forgotpassword (PwdId,SecretQuestion1,SecretAnswer1,SecretQuestion2,SecretAnswer2)VALUES(?,?,?,?,?)"; // Here am inserting form values to database.
String sql1="INSERT INTO forgotpassword (CustId) SELECT CustId FROM signup";// Here am trying to get value from another table and insert
String sql2="INSERT INTO forgotpassword (LoginId) SELECT LoginId FROM login"; // Here am trying to get value from another table and insert
Connection conn = null;
try {
conn = dataSource.createConnection();
PreparedStatement ps = conn.prepareStatement(sql);
PreparedStatement ps1 = conn.prepareStatement(sql1);
PreparedStatement ps2 = conn.prepareStatement(sql2);
ps.setInt(1, forgotPassWord.getId());
ps.setString(2, forgotPassWord.getSq1());
ps.setString(3, forgotPassWord.getAnSq1());
ps.setString(4, forgotPassWord.getSq2());
ps.setString(5, forgotPassWord.getAnSq2());
ps.executeUpdate();
ps1.executeUpdate();
ps2.executeUpdate();
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
}
catch (NullPointerException e1){
}
finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
}
}
But on each executeUpdate() its incrementing and the values from the form are stored in one row and in the next row the values from the signup and login tables are getting stored. How to make all this get stored in a single row? Any help is appreciated.
You are doing 3 inserts, so at least 3 rows are created. Also, when you do SELECT CustId FROM signup, how can you ensure that only one and the right value of CustId is taken from signup table? With this query you are fetching all the CustId. Same goes for login table and query.
To merely resolve your problem you have to create a single query:
String sql = "INSERT INTO forgotpassword (PwdId,SecretQuestion1,SecretAnswer1,SecretQuestion2,SecretAnswer2,CustId,LoginId)VALUES(?,?,?,?,?,(SELECT CustId FROM signup),(SELECT LoginId FROM login))";
^ ^ ^ ^
but I don't think you have thought this enough.
There should be something like:
SELECT LoginId FROM login WHERE CustId=? //Here I'm guessing, I don't know your tables.
The point is to get the correct value both in login table and signup table that corresponds to the user who forgot his password. This can be easily done with a WHERE clause (supposing your foreign key are setted correctly).
EDIT
As per your comment I'm going to clarify the way you should add your new user.
First of all you need to create the new user, so as soon as the information needed is sent and checked you insert a new row in signup table. But wait to execute the query.
You need the CustId. Because is an auto-increment column, you don't know which value MySQL created. You must fetch it and you can do it directly when you create the new user adding a parameter to the prepared statement:
PreparedStatement pstmt = conn.prepareStatement(sqlForNewUser, Statement.RETURN_GENERATED_KEYS);
pstmt.executeUpdate();
ResultSet keys = pstmt.getGeneratedKeys();
keys.next();
custId = keys.getInt(1);
Now you have the new user Id and can use it to insert the other values:
String sql = "INSERT INTO forgotpassword (PwdId,SecretQuestion1,SecretAnswer1,SecretQuestion2,SecretAnswer2,CustId,LoginId)VALUES(?,?,?,?,?,(SELECT CustId FROM signup WHERE CustId = ?),(SELECT LoginId FROM login WHERE CustId = ?))";
//...
ps.setString(6, custId);
ps.setString(7, custId);
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
Hi i am trying to insert the values in to mysql table. i am trying this code.
i have assigned values to variable and i want to pass that variable to that insert statement.
Is this correct?
code
int tspent = "1";
String pid = "trng";
String tid = "2.3.4";
String rid = "tup";
String des = " polish my shoes!";
INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"');
here is what i have tried, but i am not able to insert values
try
{
conn=DBMgr.openConnection();
String sqlQuery = "INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"');";
st = conn.createStatement();
rs = st.executeQuery(sqlQuery);
}
You should use executeUpdate() method whenever your query is an SQL Data Manipulation Language statement. Also, your current query is vulnerable to SQL Injection.
You should use PreparedStatement:
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUES (?, ?, ?, ?, ?)");\
Then set the variables at those index:
pstmt.setString(1, pid);
// Similarly for the remaining 4
// And then do an executeUpdate
pstmt.executeUpdate();
Try this,
String driver="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/dbname";
String uname="username";
String pass="password";
Class.forName(driver);
Connection c=(Connection) DriverManager.getConnection(url,uname,pass);
Statement s=c.createStatement();
s.executeUpdate("INSERT INTO `time_entry`(pid,tid,rid,tspend,description) VALUE ('"+pid+"','"+tid+"','"+rid+"',"+tspent+",'"+des+"')");
Use a PreparedStatement and set the values using its setXXX() methods.
PreparedStatement pstmt = con.prepareStatement("INSERT INTO `time_entry`
(pid,tid,rid,tspend,description) VALUE
(?,?,?,?,?)");
pstmt.setString(1, pid );
pstmt.setString(2, tid);
pstmt.setString(3, rid);
pstmt.setInt(4, tspent);
pstmt.setString(5,des );
pstmt.executeUpdate();
import java.sql.*;
class Adbs1{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/rk","root","#dmin");
//here rk is database name, root is username and password
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into emp values('rk11','Irfan')");
// stmt.executeUpdate("delete from emp where eid ='rk4'");
//stmt.executeUpdate("update emp set ename='sallu bhai' where eid='rk5'");
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getString(1)+" "+rs.getString(2));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}