This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Update a record if ID exist else Insert values
I am trying to update a value if the record exists else insert the values in the database. However, that is not working. I have written the code below :
NOTE: (Moderators, this is a repeated questions that I asked few mins ago. I am not able to edit previous one. Apologies if any inconvenience. Requesting you to delete.)
<%
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:sqlserver://10.222.10.19:1433", "sa", "admin1");
String empId = request.getParameter("empid");
String fName = request.getParameter("fName");
String lName = request.getParameter("lName");
String sqlCheck = "Select * from [UAP].[dbo].[UAP_EMPLOYEE] where EMP_EMPLOYEE_ID = "empId" ";
PreparedStatement prpStatementCheck = conn.prepareStatement(sqlCheck);
prpStatementCheck.setInt(1, Integer.parseInt(empId));
prpStatementCheck.setString(2, fName);
prpStatementCheck.setString(3, lName);
ResultSet rsCheck=prpStatementCheck.executeQuery();
String check=null;
boolean exists = false;
while(rsCheck.next())
{
Statement stmt = conn.createStatement();
String sql= "UPDATE [UAP].[dbo].[UAP_EMPLOYEE] SET EMP_EMPLOYEE_ID="+empId+", EMP_FNAME='"+fName+"', EMP_LNAME='"+lName+"' WHERE EMP_EMPLOYEE_ID= ?";
stmt.executeUpdate(sql);
exists = true;
}
if(!exists)
{
String sql2 = "INSERT INTO [UAP].[dbo].[UAP_EMPLOYEE] (EMP_EMPLOYEE_ID, EMP_FNAME, EMP_LNAME ) VALUES (?,?,?)";
PreparedStatement prpStatement1 = conn.prepareStatement(sql2);
prpStatement1.setInt(1, Integer.parseInt(empId));
prpStatement1.setString(2, fName);
prpStatement1.setString(3, lName);
prpStatement1.execute();
prpStatement1.close();
}
%>
As EMP_EMPLOYEE_ID is an INTEGER field you will need to use:
prpStatementCheck.setInt(1, Integer.parseInt(empId));
Also, you can remove the quotes around this field for the UPDATE string:
String sql= "UPDATE [UAP_EMPLOYEE] SET EMP_EMPLOYEE_ID=" + empId + ", EMP_FNAME='" + fName+"', EMP_LNAME='" + lName + "' WHERE EMP_EMPLOYEE_ID= " + empId;
Again for prpStatement1:
prpStatement1.setInt(1, Integer.parseInt(empId));
Related
The thing i want to achieve here is that i have a table name total_product in mysql database and i want to retrieve the value of SNo = 1 from the table and update the Quantity in the table.
There is a text box i am using in GUI in which the additional product produced will be written.
The output from the table is stored in variable id and the new quantity that is produced is stored in the variable q1.
so the new product quantity will be q1 = q1 + id.
I am not able to understand what should i put in the sql statement that is used in stmt.executeUpdate(sql) because the sql is a string and i have to pass an integer value to Qunty in the sql string.
Please Help.
Connection conn = null ;
Statement stmt = null ;
String url = "jdbc:mysql://localhost:3306/project";
String user = "root";
String password = ".dpadpep";
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url,user,password);
String sql = "Select Qunty from total_product " + "where SNo = 1";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
int id=0;
int q1 = Integer.parseInt(fld1[0].getText());
while(rs.next()) {
id = rs.getInt(1);
System.out.println("Quantity="+id);
}
q1 = q1+id;
sql = "UPDATE total_product " + "set Qunty = q1 where SNo=1";
stmt.executeUpdate(sql);
You don't need to explicitly retrieve the current value in the database, you can simply add the additional amount directly:
int q1 = Integer.parseInt(fld1[0].getText());
String sql = "UPDATE total_product SET Qunty = Qunty + ? WHERE SNo = 1";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, q1);
ps.executeUpdate();
I'm trying to do an INSERT INTO SELECT which are inserting into in 1 table by selecting specific data in columns from 2 tables. The thing is, it will involve with user input from JTextField as well. I have searched for many solutions but still got an error and I just dunno what else to do. I'm using Java as PL and Oracle as DB. This is what I have got so far :
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","ghost","slayer");
stmt = con.createStatement();
String sbjC = sbjCode.getText(); //textfield for subjectCode
String sbjN = sbjName.getText(); //textfield for subjectName
String matricsno = textstudentid.getText(); //textfield for matrics number
String sbjG = sbjGrade.getText(); //textfield for subjectGrade (not gonna be use in db, just for comparison)
String sql1 = "INSERT INTO transferred (subjectCode,subjectName,credit,prequisite,matricsNo) "
+ "SELECT b.subjectCode,b.subjectName,b.credit,b.prequisite,s.matricsNo "
+ "FROM bitm b, student s "
+ "WHERE b.subjectCode = '"+sbjC+"' AND b.subjectName = '"+sbjN+"' AND s.matricsNo = '"+matricsno+"'";
/* table Transferred has 5 column which are subjectCode,subjectName,credit,prequisite,matricsNo [matricsno as FK]
* table bitm has 5 column [subjectCode as PK]
* table student has 6 column [matricsno as PK]
*/
ps = con.prepareStatement(sql1);
ps.setString(1, sbjC);
ps.setString(2, sbjN);
ps.setString(3, "SELECT credit FROM bitm WHERE subjectCode = '"+sbjC+"' AND subjectName = '"+sbjN+"'");
ps.setString(4, "SELECT prequisite FROM bitm WHERE subjectCode = '"+sbjC+"' AND subjectName = '"+sbjN+"'");
ps.setString(5, "SELECT matricsno FROM student WHERE matricsno = '"+matricsno+"'");
ps.executeUpdate(sql1);
The only error I have got after executing and insert all data needed into JTextField is java.sql.SQLException : Invalid column index.
The SQL statement has been test in SQL Developer and succeed. Just I'm bit confused on how to do it on Java.
Thank you for all of your response and time.
I'm a newbie in Java.
For PreparedStatement, you'd code ? Into the sql and later replace that with values.
String sql1 = "INSERT INTO transferred (subjectCode,subjectName,credit,prequisite,matricsNo) "
+ "SELECT b.subjectCode,b.subjectName,b.credit,b.prequisite,s.matricsNo "
+ "FROM bitm b, student s "
+ "WHERE b.subjectCode = ? AND b.subjectName = ? AND s.matricsNo = ? ";
ps = con.prepareStatement(sql1);
ps.setString(1, sbjC);
ps.setString(2, sbjN);
ps.setString(3,matricsno);
ps.executeUpdate ();
This should do it.
Your error came from giving parameters (setString...) without matching ?
Unfortunately you absolutely misunderstood what the preparedStatemet does.
You have to write ? -s into the query and the preparedSatement is going to replace it on a typed way:
String sql1 = "INSERT INTO transferred (subjectCode,subjectName,credit,prequisite,matricsNo) "
+ "SELECT b.subjectCode,b.subjectName,b.credit,b.prequisite,s.matricsNo "
+ "FROM bitm b, student s "
+ "WHERE b.subjectCode = ? AND b.subjectName = ? AND s.matricsNo = ?";
ps = con.prepareStatement(sql1);
ps.setString(1, sbjC);
ps.setString(2, sbjN);
ps.setString(3, matNo);
ps.executeUpdate();
To answer my own question, I'll put comment on the changes that I have made to the code and make it work:
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","aza","jaiza");
stmt = con.createStatement();
String sbjC = sbjCode.getText();
String sbjN = sbjName.getText();
String matricsno = textstudentid.getText();
String sbjG = sbjGrade.getText();
String sql1 = "INSERT INTO transferred (subjectCode,subjectName,credit,prequisite,matricsNo) "
+ "SELECT b.subjectCode,b.subjectName,b.credit,b.prequisite,s.matricsNo "
+ "FROM bitm b, student s "
+ "WHERE b.subjectCode = ? AND b.subjectName = ? AND s.matricsNo = ?"; // from textfield to ?
ps = con.prepareStatement(sql1);
ps.setString(1, sbjC);
ps.setString(2, sbjN);
ps.setString(3, matricsno);
//from all the SELECT statement to just 3 user-input-from-textfield column
ps.executeUpdate(); // remove the sql1 in ps.executeUpdate(sql1);
This question already has answers here:
Too many auto increments with ON DUPLICATE KEY UPDATE
(2 answers)
Closed 8 years ago.
I use this code , in first time it works but after ,I have an error (java.sql.sqlexception duplicate entry '1' for key 'primary')and (a) represent the primary key (auto-increment), please help.
public int a;
String url = "jdbc:mysql://localhost:3306/joebdd";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "12345";
try {
Class.forName(driver).newInstance();
Connection con = (Connection) DriverManager
.getConnection(url, user, pass);
Statement st = (Statement) con.createStatement();
ResultSet rs1 = (ResultSet) st
.executeQuery("select count(*) from Bill");
if (rs1.next()) {
if (rs1.getInt(1) == 0) {
a = 0;
}
if (rs1.getInt(1) == 1) {
a = 1;
}
else {
a = rs1.getInt(1);
}
st.executeUpdate("insert into Bill values('"
+ a
+ "','"
+ jTextField2.getText()
+ "','"
+ jLabel7.getText()
+ "','"
+ jTextPane1.getText()
+ "','"
+ Integer.parseInt(jTextField1
.getText()) + "')");
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
If a is autoincrement, then you don't need to insert it in the sql query.
No need to insert a value in the auto-incremented field. Use
INSERT INTO Bill (field2, field3, field4, field5) VALUES (...);
Current style is very unsafe. Use a PreparedStatement to be safe from SQL Injection attacks. Refer to this article for how:https://www.owasp.org/index.php/Preventing_SQL_Injection_in_Java
I am writing a code in Java where user can type a last name in a JTextField named lastname and then search for possible match in MySQL database. Say for example, user begins to type letter "M" (case insensitive and without double quotes), all the last name that starts with letter "M*" will display on JTable. If user types a second letter, say for example "A", the results on JTable will only display last names with "MA", then if user types third letter, say for example "N", JTable will only display all the last names with "MAN***" and so on..
I have read about
SELECT * FROM table WHERE lastname LIKE value
and tried to use it on my program, however, I am getting an error.
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxError.Exception: 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 '%' at line 1
Here's my partial code in event when there's key pressed in JTextField lastname:
private void lastNameKeyPressed(java.awt.event.KeyEvent evt) {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "students_dbs";
Statement stmt = null;
ResultSet result = null;
String driver = "com.mysql.jdbc.Driver";
String databaseUserName = "user1";
String databasePassword = "test";
PreparedStatement pst = null;
try{
conn = DriverManager.getConnection(url + dbName, databaseUserName, databasePassword);
stmt = conn.createStatement();
System.out.println("Connected to the database.");
}catch(Exception e){
System.out.println("Failed to connect ot the database.");
}
try{
String sql = "SELECT studentno, lastname, firstname, middlename FROM student WHERE lastname LIKE '%" + lastname.getText() + "'%";
pst = conn.prepareStatement(sql);
result = pst.executeQuery();
studentsTable.setModel(DbUtils.resultSetToTableModel(result));
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
I googled it for a day or two now, however, I am stuck. I'm kinda new in using LIKE in MySQL. Any kind help is very much appreciated! Thank you in advance!
The position of the last ' char is wrong:
String sql = "SELECT studentno, lastname, firstname, middlename FROM student
WHERE lastname LIKE '% " + lastname.getText() + " '% ";
should be:
String sql = "SELECT studentno, lastname, firstname, middlename FROM student
WHERE lastname LIKE '% " + lastname.getText() + " %' ";
Try this:
String SQL="Select name from tablename where like %";
pst = conn.prepareStatement(sql);
pst.setString(1, txnam.gettext()+"%");
put one textfield for u to type
String sql = "SELECT studentno, lastname, firstname, middlename FROM student
WHERE lastname=?";
pst = conn.prepareStatement(sql);
pst.setString(1,jTextField1.getText());
result = pst.executeQuery();
you can use this code :
this is sql code
and then rename youre Jtabble, Like model in picture one. then call method in here initcomponent(){selectDataTable(""); }. then make event key released in youre textfield, and then write this in the event selectDatatable(textfield.gettext()); Done
This question already has an answer here:
ResultSet is not updatable [duplicate]
(1 answer)
Closed 4 years ago.
I am doing a simple GUI application in Java (NetBeans 7.3.1) in which I use ResultSet for retreiving and updating data in the virtual database of NetBeans.
I created the database "Employees" and a table, "WORKERS", in it. Tough, I can't update data in it.
The code is
public void doConnect() {
String host = "jdbc:derby://localhost:1527/Employees";
String uName = "adm";
String uPass = "admin";
String SQL = "SELECT * FROM APP.WORKERS ORDER BY ID";
try {
con = DriverManager.getConnection(host, uName, uPass);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery(SQL);
int conc = rs.getConcurrency();
System.out.println(conc);
rs.next();
int id_col = rs.getInt("ID");
String first_name = rs.getString("First_Name");
String last_name = rs.getString("Last_Name");
String job = rs.getString("Job_Title");
System.out.println(id_col + " " + first_name + " " + last_name + " " + job);
textId.setText(Integer.toString(id_col));
textName.setText(first_name);
textLast.setText(last_name);
txtJob.setText(job);
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
The outcome of getConcurrency(); is 1007 (ReadOnly).
What did I wrong? I can't find the error.
Isn't it because you make the result set updatable after rs.deleteRow(); ?
maybe if you place
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
before the rs.deleteRow(); it works.
You can try to write inside your try catch clause under your variable con this line:
con.setReadOnly(false);
If this does not solve the problem, you must find a way to access the database options within NetBeans and make sure the access and use of database objects is set to editable/updateable/read and write. I cannot help more since I use Eclipse and my NetBeans skills are a bit rusty.