Can someone please tell me what is wrong to my query.
I have textbox to update the occupantname but it doesn't work, Only Status works.
String gOccupied = "Occupied" ;
String query = "UPDATE `rooms` SET `occupantname` = '"+txtFirstNames.getText()+"' , `status`='"+gOccupied+"' WHERE roomnumber = " +CBRoomNumber.getSelectedItem();
executeSQlquery(query,""+" Updated");
Can someone please tell me what is wrong to my query. i have textbox
to update the occupantname but it doesn't work, Only Status works.
Don't use direct MySql SQL with these special characters `
String query = "UPDATE rooms SET occupantname =
'"+txtFirstNames.getText()+"' , status='"+gOccupied+"' WHERE
roomnumber = " +CBRoomNumber.getSelectedItem();
Blockquote
Instated Use below SQL
String query = "UPDATE rooms SET occupantname = ? , status= ? WHERE roomnumber = ?";
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Main {
private static PreparedStatement preparedStmt = null;
private static Connection connection = null;
public static void main(String[] args) {
String gOccupied = "Occupied";
String occupantname = txtFirstNames.getText();
String query = "UPDATE rooms SET occupantname = ? , status= ? WHERE roomnumber = ?";
try {
executeSQlquery(query, occupantname, gOccupied, "Updated");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void executeSQlquery(String query, String occupantname, String gOccupied, String status) throws SQLException {
try {
// create a java mysql database connection
String myDriver = "org.mysql.Driver";
String myUrl = "jdbc:mysql://localhost/test";
Class.forName(myDriver);
connection = DriverManager.getConnection(myUrl, "username", "password");
preparedStmt = connection.prepareStatement(query);
preparedStmt.setString(1, occupantname);
preparedStmt.setString(2, gOccupied);
preparedStmt.setInt(3, 101);
// execute the java preparedstatement
preparedStmt.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
//finally block used to close resources
if (preparedStmt != null) {
connection.close();
}
if (connection != null) {
connection.close();
}
}
}
}
It is generally a terrible idea to construct SQL queries the way you currently do, as it opens the door to all sorts of SQL injection attacks. To do this properly, you'll have to use Prepared Statements instead. This will also resolve all sorts of escaping issues that you're evidently having at the moment.
SQL select statement with where clause
Related
I am connecting my Java Program to a database stored in the program folder, and I am having users answer quiz questions and I want the results to be stored in the database. The Update statement is not working, and I don't know if it's a problem with the actual statement or the database connection.
I've tried creating a new database with the same tables and reconnecting to that database, but nothing seems to be working.
//database connection class
public class databaseConnection {
public static Connection dbConnector() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager
.getConnection("jdbc:sqlite:D:\\Users\\mariammahmoud\\eclipse-workspace\\ia_2019_final\\testjava.db");
return conn;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
public class student {
public static final String DB_NAME = "testjava.db";
public static final String TABLE_STUDENTS = "students";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_GRADE = "grade";
public static final String COLUMN_RESULTS = "results";
public static final String COLUMN_EVENTS = "events";
public static final String COLUMN_USERNAME = "username";
public void main() {
try {
String user_name = login_student.sendQuiz();
Connection conn = databaseConnection.dbConnector();
ArrayList<String> results = new ArrayList<String>(15);
instructions();
questions(results);
results.trimToSize();
System.out.println("Here are the events that you should consider competing in:");
System.out.println(results);
String separator = ",";
int total = results.size() * separator.length();
for (String finalResults : results) {
total += finalResults.length();
}
StringBuilder sb = new StringBuilder(total);
for (String finalResults : results) {
sb.append(separator).append(finalResults);
}
String resultsDatabase = sb.substring(separator.length());
String sql = "UPDATE students SET events = ? WHERE username = " +user_name;
PreparedStatement myStmt = conn.prepareStatement(sql);
myStmt.setString(1, resultsDatabase);
myStmt.executeUpdate();
} catch (SQLException e) {
System.out.println("Something went wrong:" + e.getMessage());
e.printStackTrace();
}
}
I expected the update statement to update the testjava.db database, but everything is staying the same. What should I do? Thank you in advance!
Your problem is that while you wisely used a prepared statement in your code for the update, you never actually used it for the username column in the WHERE clause. Hence, the query you are executing currently won't be interpreted as comparing some input against username. Rather, the username value will be interpreted as a column. Try this version:
String resultsDatabase = sb.substring(separator.length());
String sql = "UPDATE students SET events = ? WHERE username = ?";
PreparedStatement myStmt = conn.prepareStatement(sql);
myStmt.setString(1, resultsDatabase);
myStmt.setString(2, user_name);
myStmt.executeUpdate();
Note that you could have just tried the following:
String sql = "UPDATE students SET events = ? WHERE username = '" + user_name + "'";
But, please bind a value to a ? placeholder instead, as I have suggested above. One benefit of using statements is that it frees you from having to worry about how to escape your data in the query.
What is the problem in this code? where it is update the all column values with the same last one .
public class dbconnection {
java.sql.Connection con;
java.sql.Statement st;
ResultSet rs;
public EncBean getConnection()throws SQLException{
EncBean encBean1 = new EncBean();
String v_url= "jdbc:oracle:thin:#192.168.2.138:1522:orcl2";
String v_username= "scott";
String v_password = "tiger";
try
{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
con = DriverManager.getConnection(v_url,v_username,v_password);
System.out.println ("Connection to Oracle database was Established");
}
catch ( SQLException e)
{
e.printStackTrace();
}
return encBean1;
}
public EncBean selectRows()
{
EncBean encBean2 = new EncBean();
try
{
String SQLselect="select JOB_NAME from job";
st=con.createStatement();
rs=st.executeQuery(SQLselect);
while (rs.next()) {
encBean2.setName(rs.getString("JOB_NAME"));
}
}
catch ( Exception ex )
{
ex.printStackTrace();
}
return encBean2;
}
public void updateRows(String updatedname){
try
{
Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE);
ResultSet srs = stmt.executeQuery("select job_name from job " );
while (srs.next()) {
srs.updateString("job_name", updatedname);
srs.updateRow();
con.commit();}
System.out.println("An existing user was updated successfully!");}
catch(SQLException err){
System.out.println(err.getMessage());
}}}
This is the main
public class mainenc {
public static void main(String[] args) throws Exception{
dbconnection dbcon = new dbconnection();
EncBean encbeancon= dbcon.getConnection();
EncBean encBean5 = dbcon.selectRows();
enc concatinputs = new enc();
EncBean encBeanconcat = concatinputs.funconcat(encBean5.getName());
EncBean encBean4 = concatinputs.inputencryption(encBeanconcat.getConcatenatedData());
String vReserverbin= encBean4.getReversedBinary();
String ascistring= concatinputs.convertBinaryStringToString(vReserverbin);
dbcon.updateRows(ascistring);
}}
What is the problem in this code? where it is update the all column values with the same last one .
After updated method you should write list method again.
Try to take this example:
UPDATE tableB
SET tableB.value , tableA.value, tableB.value)
WHERE tableA.name = 'Joe'
It is kind of obvious: dbcon.updateRows(...) calls for the update method and that method does the job.
But as Erhan said, you don't get to see the result because you don't actually make use of updated records, e.g. show them etc. At least, you can check it out at the DB level if op is completed.
But I really disliked your comment:
plz can you do it for me?
You should do your own task and ask help when you need a hand. But never expect someone else to do your job mate.
im having a problem with my servlet whenever it was open from my JSP which is ShowPurchasingItems.jsp it will not go to the next JSP.
here is my ShowPurchasingItems.jsp
http://jsfiddle.net/0g3erumm/
and here is my Servlet that wont open my next JSP
package connection;
import java.io.*;
import java.sql.*;
import javax.servlet.http.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
#WebServlet("/CheckOutServlet")
public class CheckOutServlet extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String User = (String) session.getAttribute("username");
String id = (String) session.getAttribute("stockIdToPurchase");
float price = (float) session.getAttribute("UnitPriceToPurchase");
int stock = (int) session.getAttribute("OnStockToPurchase");
int quantityOrdered = (int) session.getAttribute("purchaseQuantity");
float totalPrice = price * quantityOrdered;
int newStock = stock - quantityOrdered;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String url = "jdbc:mysql://localhost:3306/inventory";
String user = "root";
String password = "password";
String query = "INSERT INTO purchases (username,stockId,price,quantityOrdered,totalPrice) VALUES ('"+User+"', '"+id+"', "+price+", "+quantityOrdered+", "+totalPrice+");";
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
if(rs.next())
{
String encodedURL = response.encodeRedirectURL("ShowInventoryList.jsp");
response.sendRedirect(encodedURL);
}
}
catch(Exception e)
{
out.println("There is an error here");
}
finally
{
out.close();
try
{
rs.close();
stmt.close();
conn.close();
}
catch (Exception e)
{
out.println("There is no error here");
}
}
}
}
it would keep on catching error on this statment out.println("There is an error here"); and i am stuck in here i dont know what else is wrong with my program hope someone can help me.
You're committing a cardinal sin by swallowing the exception and thus losing all information that may help you get to the bottom of your problem!
You should change how your exceptions are handled, at the very least you should be dumping the stacktrace:
catch(Exception e) {
out.println("There is an error here");
e.printStackTrace();
}
Once you have the stacktrace you'll be in a much better situation when it comes to diagnosing the problem (or asking more specific questions)!
Edit - Based on the exception posted in the comment:
java.sql.SQLException: Can not issue data manipulation statements with executeQuery()
Is being thrown because you are performing an update using the query method. You should change your code to this:
int updateCount = stmt.executeUpdate(query);
if(updateCount > 0) {
String encodedURL = response.encodeRedirectURL("ShowInventoryList.jsp");
response.sendRedirect(encodedURL);
}
executeQuery executes the given SQL statement, which returns a single ResultSet object.
You're making INSERT, which doesn't return anything. I suppose that's why you're getting an exception.
I'd recommend to use PreparedStatement where you can bind variables and prevent SQL injection + some DB work faster with prepared statements, and executeUpdate instead of executeQuery
PreparedStatement stmt = null;
...
String query = "INSERT INTO purchases (username,stockId,price,quantityOrdered,totalPrice) VALUES (?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(query);
stmt.setString(1, username);
...
int inserted = stmt.executeUpdate();
if (inserted > 0) {
// there was a successfull insert
...
There are a lot of examples on the Internet. For example: http://www.mkyong.com/jdbc/how-to-insert-date-value-in-preparedstatement/
I was trying to display the rows in the database using Java. My idea is to sort the rows in the database and display them in 3 columns and infinite rows. This is what I have. When I run it, I couldn't see any output. Where did I go wrong?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.SQLException;
public class Rows {
public static void main(String[] args) throws SQLException,ClassNotFoundException
{
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/testapp";
String user = "root";
String password = "root";
connection = DriverManager.getConnection(url, user, password);
Statement stmt = connection.createStatement();
String sql = "select * from site order by fname;";
stmt.execute(sql);
} catch (ClassNotFoundException e) {
System.err.println("Could not load database driver!");
} catch (SQLException e) {
e.printStackTrace();
}
finally
{
if (connection != null)
{
connection.close();
}
}
}
}
The database table I have is
datas(id int, fname varchar(20)
Statement stmt = connection.createStatement();
String sql = "select id, fname from site order by fname;";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){
int id=rs.getInt("id");
.............
}
Reference: Retrieving and Modifying Values from Result Sets
The code should obtain a ResultsSet and iterate through it.
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/testapp";
String user = "root";
String password = "root";
connection = DriverManager.getConnection(url, user, password);
Statement stmt = connection.createStatement();
//You shouldn't need the semi-colon at the end
String sql = "select * from site order by fname;";
//missing piece
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + "\t" + name);
}
I write a code in servlet for login checking I don't know why I get an error like java.sql.SQLException: No data found, if I had not commented out the String s4 = rs.getString(1) and out.println(s4) line if I commented out this lines I did not get any error.
Why do I get an error like this? I cannot find out the answer.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class login extends HttpServlet {
Connection conn;
Statement stmt;
ResultSet rs;
String s = "";
public void init() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection("Jdbc:Odbc:edsn");
s = "Your information is connected ......";
} catch (Exception e) {
s = "Exception 1....." + e.getMessage();
}
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {
res.setContentType("text/html;charset=UTF-8");
PrintWriter out = res.getWriter();
out.println(s);
try {
String ID = req.getParameter("T1");
String query = "select * from user_db ";
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
out.println("user" + " " + "pass");
while (rs.next()) {
try {
if ((rs.getString(1)).equals(ID)) {
String s4 = rs.getString(1);
out.println(s4);
out.println("<html><body><h> login Pass.....:(</h></body></html>");
}
} catch (Exception e) {
out.println(e);
}
}
} catch (Exception e) {
out.println("Unable To Show the info... . . ." + e.getMessage());
}
}
}
Why write the code like this ? It's very wasteful going over the whole table...
The IO alone...
Why not change to this:
ResultSet rs = null;
PreparedStatement st = null;
try {...
String ID = req.getParameter("T1");
String query = "select 1 from user_db where col_name = ?";
st = conn.prepareStatement(query);
st.setString(1, ID);
rs = st.executeQuery();
if (rs.next()) {
out.println(ID);
out.println("<html><body><h> login Pass.....:(</h></body></html>");
}
..
} finally {
if (rs != null) try { rs.close();}catch (Exception e) {}
if (st != null) try { st.close();}catch (Exception e) {}
}
notice prepared statements are cached and better for frequent use
you let the db do what its good at - search the data
select 1 instead of select * does not bring back data you dont really need
jdbc works harder the more columns and data in general you return, so only get what you
need
and add a finally block to always close your db connections properly
Calling methods on Connection, Statement, or ResultSet depend on which JDBC driver you've loaded. All the values of the ResultSet could be set as soon as the query is made, or they could be retrieved from the database as they're needed, depending on the implementation of the driver.
The JdbcOdbcDriver throws an SQLException after calling getString for a second time. This can be worked around be storing the values in Strings instead of making multiple calls, or by switching to a different driver.