I have code to retrieve a database item and it displays that in a mobile application using J2ME. I also use JSP for this so that my mobile app can get information from this.
I want to know how I can retrieve multiple items??
JavaBean:
public String doQuery() throws ClassNotFoundException, SQLException {
//register driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//establish connection
Conn = DriverManager.getConnection ("jdbc:mysql://localhost:3306/a1electric?user=root&password=raam030");
//Create a Statement object from the Connection
Statement stmt = Conn.createStatement();
String sql = "SELECT JobID FROM employee WHERE employeeID=" +this.jobID;
ResultSet rs = stmt.executeQuery(sql);
String rt = "";
rs.next();
rt = rs.getString("JobID");
Conn.close();
return rt;
}
JSP Page:
<jsp:useBean id="bean0" scope="session" class="data.queryBean"/>
<jsp:setProperty name="bean0" property="jobID" param="jobID"/>
<%= bean0.doQuery() %>
I would like to retrieve all the job IDs for this employee ID and display it.
If there are multiple JobIDs for a given EmployeeID, then your result set has all those items and you should browse through the resultset:
String sql = "SELECT JobID FROM employee WHERE employeeID=" +this.jobID;
ResultSet rs = stmt.executeQuery(sql);
List<String> jobIds = new ArrayList<String>();
while (rs.next()) {
jobIds.add(rs.getString("JobID"));
}
On a related note, you should
try to use a connection pool (apache DBCP), instead of registering the driver and connecting to the DB everytime.
use PreparedStatement to avoid potential SQL injection attacks:
PreparedStatement stmt = con.prepareStatement(
"SELECT JobID FROM employee WHERE employeeID= ?");
stmt.setInt(1, this.jobID);
ResultSet rs = stmt.executeQuery();
Related
I'm trying to send in ORDER table last ID from CUSTOMER and all IDs from PRODUCT tables. In "idproduct"(ORDER table) should appears all IDs with white spaces between them. I used here rs.next() twice and I know that it isthe reason why error appears, but how can I handle it? Here is a code:
List<String> IDproducts = new ArrayList<>();
Connection conn = db.getConnect();
PreparedStatement pst = conn.prepareStatement("SELECT * FROM `onlineshop`.`customer`");
ResultSet rs = pst.executeQuery();
while (rs.next()){
rs.getString(1);
}
Connection conn1 = db.getConnect();
PreparedStatement pst1 = conn1.prepareStatement("SELECT * FROM `onlineshop`.`product`");
ResultSet rs1 = pst1.executeQuery();
while (rs1.next()){
IDproducts.add(rs1.getString(1));
}
db.Query("INSERT INTO `onlineshop`.`order` (`idcustomer`, `idproduct`)
VALUES ('"+rs.getString(1)+"','" + IDproducts + ")");
error:
java.sql.SQLException: After end of result set
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:959)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:862)
com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:790)
com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5244)
com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5167)
The function below will pick the highest value and it will display value which are in column place1(in table placeseen) as output based on the ID.So far I only can get the highest value but not the value in place1.
I don't know what's wrong with my coding because the output is always shows empty.
private void pick_highest_value_here_and_display(ArrayList<Double> value) throws Exception {
// TODO Auto-generated method stub
double aa[]=value.stream().mapToDouble(v -> v.doubleValue()).toArray();
double highest=aa[0+1];
for(int i=0;i<aa.length;i++)
{
if(aa[i]>highest){
highest=aa[i];
String sql ="Select* from placeseen where ID =aa[i]";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
String aaa;
aaa=rs.getString("place1");
System.out.println(aaa);
}
ps.close();
rs.close();
conn.close();
}
}
System.out.println(highest);
}
instead of
String sql ="Select * from placeseen where ID =aa[i]";//aa[i] taking a value
use
String sql ="Select place1 from placeseen where ID =?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, aa[i]);
passing aa[i] variable value .
Avoid sql injection
You can try this
// as you are using preparedStatement you can use ? and then set value for it to prevent sql injection
String sql = "Select * from placeseen where ID = ?";
DatabaseConnection db = new DatabaseConnection();
Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, aa[i]); // 1 represent first attribute represented by ?
System.out.println(ps); // this will print query in console
ResultSet rs = ps.executeQuery();
if (rs.next()) {
System.out.println("Inside rs.next()"); // for debug purpose
String aaa;
aaa=rs.getString("place1");
System.out.println(aaa);
}
// remaining code
This question already has an answer here:
How to perform an SQL insert in Java
(1 answer)
Closed 7 years ago.
I am writing java application using sqllite
public Product createProduct(String productName) throws SQLException {
String query = "INSERT into tbl_Product (name) values (?) ";
PreparedStatement preparedStatement = null;
Connection connection = null;
ResultSet rs = null;
Product product = null;
try {
connection = ConnectionFactory.getConnection();
preparedStatement = connection.prepareStatement(query);
//preStatement.setInt(1, 0);
preparedStatement.setString(1, productName);
preparedStatement.executeUpdate();
} finally {
//preparedStatement.close();
DbUtil.close(rs);
DbUtil.close(preparedStatement);
DbUtil.close(connection);
}
return product;
}
My product table have (ID,Name) column, where Id is auto generated. What all java changes are required so that preStatement can insert auto generated id in db.
String query = "INSERT into tbl_Product values (?) ";
ResultSet rs = null;
Product product = null;
try {
connection = ConnectionFactory.getConnection();
preStatement = (PreparedStatement) connection.prepareStatement(query);
preStatement.setString(1, productName);
rs = preStatement.executeQuery();
String sqlQuery = "INSERT into tbl_Product values (?)
PreparedStatement stmt = conn.prepareStatement(sqlQuery);
stmt.setString( 1, "val" ); //nameText variable contains the text of the jtextfield)
stmt.executeUpdate();
use execute update instead of execute query.
executeQuery():
Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.
executeUpdate():
Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement.
Hey I am trying to verify the password matches the one they entered with the email I have been searching for the web for a few hours and everything else I have tried does not work this is what i have so far:
try {
Class.forName(driver).newInstance();
Connection conn = (Connection) DriverManager.getConnection
(url + dbName, userName, password);
PreparedStatement checkUserInfo = (PreparedStatement) conn.prepareStatement
("SELECT password FROM profiles WHERE email = ?");
checkUserInfo.setString(1, emailT); //emailT is email pulled from an editText
//checkUserInfo.setString(2, pass1);
//Statement state = (Statement) conn.createStatement();
//String querychk = "SELECT * FROM profiles WHERE email = '"+emailT+"'";
//ResultSet rs = state.executeQuery(querychk);
ResultSet rs = checkUserInfo.executeQuery();
while (rs.next()){
String pass = rs.getString(2);
if (pass.equals(pass1)) {
return success;
}
}
conn.close();
}
catch (Exception e) {
e.printStackTrace();
}
Simply modify your SQL Query to:
"select * from profiles where email=? and password=?"
And be-aware to validate input fields for preventing from SQL injection
And for getting PreparedStatement object or Connection object, you don't have to externally typecast it, cause it is returning the same object as you assigning to it. Even java doc also provided the below statement for the PreparedStatement
PreparedStatement pstmt = con.prepareStatement(Query);
I have a mysql database that I am trying to retrieve from our website host (godaddy). I followed a format that seems to be right but it tells me that:
java.sql.SQLException: No database selected
Code:
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// STEP 2: Register JDBC driver
Class.forName(JDBC_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();
String sql;
sql = "SELECT * FROM item_master";
ResultSet rs = stmt.executeQuery(sql); //<-- This is where the error is.
// STEP 5: Extract data from result set
while (rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
// Display values
System.out.print("ID: " + id);
}
...
}
I did a print statement of the conn to maybe think the connection could of been null and was shown this:
com.mysql.jdbc.JDBC4Connection#2a6*****
Anyone have any ideas what could cause something like this?
Your URL for your database should include your database name. This is normally your URL followed by a "/DBNAME".
String URL = "jdbc:mysql://localhost:3306/mydb";
Where "mydb" is your database name.
What is the value of DB_URL? As far as I am aware, the URL needs to be of the form:
"WEBURL/DATABASENAME:PORT"
Are you just trying to connect to the WEBURL, without specifying a DATABASE?
I had the same problem.
Just run one more query (before your 'SELECT' statement) to connect to your database.
First:
sql = "USE <yourdatabase>";
ResultSet rs = stmt.executeQuery(sql);
And after:
sql = "SELECT * FROM item_master";
rs = stmt.executeQuery(sql);