Select database columns for a JDBC statement query - java

I try to execute this:
<%String getComments = "select * from comments_tb where car_id = "
+ request.getParameter("id") + "\" order by time_stamp DESC";
KarimDatabase karim2 = new KarimDatabase();
Statement stm2 = karim2.getCon().createStatement();
ResultSet rs2 = stm2.executeQuery(query);
while (rs2.next()) {
out.println("<p>" + rs2.getString("comment_desc") + "</p>");
out.println("<p>" + rs2.getString("time_stamp") + "</p>");
}
karim2.getCon().close();
%>
but i get this result from my tomcat server logs:
java.sql.SQLException: Column 'comment_desc' not found.
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)...
Please take note that I have inspected by database tables and the comment_desc is a column. In fact I try another column's output string and I get a result.

If you only need those two columns you could do something like this:
<%String getComments = "select comment_desc,time_stamp from comments_tb where car_id = "
+ request.getParameter("id") + "\" order by time_stamp DESC";
KarimDatabase karim2 = new KarimDatabase();
Statement stm2 = karim2.getCon().createStatement();
ResultSet rs2 = stm2.executeQuery(query);
while (rs2.next()) {
out.println("<p>" + rs2.getString(1) + "</p>"); //get first column result
out.println("<p>" + rs2.getString(2) + "</p>"); //2nd
}
karim2.getCon().close();
%>
Try and see if that works. In regards to your error, doesn't really make much sense why you would get that unless the column doesn't exist or maybe because it's not a string?

Related

Search the MYSQL Database filtering using either first name or last name typed in JTextfield on JTable

I want to use either last name or first name to filter result shown on JTable from the database such that when i type either Nikola or Tesla in the JTextfield, the row with either of the names is filtered.
I have stored name as one field in the database i.e 'Nikola Tesla' when i type Nikola, it is working right and when i type Tesla it shows no result.
I have one field for name that stores both names.
I don't want to have separate First_Name and Last_Name field.
Please suggest what i should add on my code shown below:
private void jTextFieldSearchKeyReleased(java.awt.event.KeyEvent evt) {
try {
String selected = (String) jComboBoxSelected.getSelectedItem();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"
+ "employee_certificate", "root", "");
String sql = "SELECT stuff.Emp_Id,stuff.Emp_Name, stuff.Department, "
+ "certificate.Cert_Code, certificate.Cert_Name,\n"
+ "certificate.Cert, certificate.Vendor, certificate.Date_Taken, "
+ "certificate.Expiry_Date FROM stuff LEFT JOIN certificate"
+ " ON stuff.Emp_Id=certificate.Emp_Id "
+ "WHERE " + selected + " LIKE ? ORDER BY stuff.Emp_Name\n";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, jTextFieldSearch.getText() + "%");
ResultSet rs = pstmt.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
pstmt.close();
con.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
You need to add % before the jTextFieldSearch.getText() also. See below
pstmt.setString(1, "%" + jTextFieldSearch.getText() + "%");
The true solution is this, you should to use %% inside quots '%%', without quotes you get that error:
LIKE '%Name%'
so, with prepared statement we should to change Name with ? and the result is like that:
String sql = "SELECT stuff.Emp_Id,stuff.Emp_Name, stuff.Department, "
+ "certificate.Cert_Code, certificate.Cert_Name,\n"
+ "certificate.Cert, certificate.Vendor, certificate.Date_Taken, "
+ "certificate.Expiry_Date FROM stuff LEFT JOIN certificate"
+ " ON stuff.Emp_Id=certificate.Emp_Id "
+ "WHERE " + selected + " LIKE '%?%' ORDER BY stuff.Emp_Name\n";
i hope this can help you, good luck.

Query is working and giving accurate result in mysql but is resulting in a java.lang.nullpointerexception in jsp

I have used the sum function to calculate the total and then save it in another table. When i run this on mysql, it provides the right result. But when included in the jsp, it ends in java.lang.NullPointerException
You can see the same query working in mysql here
The error generated on running the code
rst = stmt.executeQuery("SELECT *
FROM invoicename
ORDER BY name DESC
LIMIT 1;");
if (rst.next()) {
String str = rst.getString("name");
rst1 = stmt.executeQuery("SELECT sum(price)
FROM invoices
WHERE invoicename='" + str + "';");
if (rst1.next()) {
int s = rst1.getInt(1);
if (rst1.wasNull()) {
s = 0;
}
stmt.executeUpdate("INSERT INTO invoice
VALUES('" + str + "',curdate(),curtime(),'" + s + "')");
}

Resultset.next returns true but doesn't return the value

I am trying to read from a mysql table and I am doing the following:
protected void pushRegisteredStudentsData() {
try {
conn = (Connection) DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String userID = "SELECT * FROM STUDENT";
rs = stmt.executeQuery(userID);
while (rs.next()) {
int id = rs.getInt("ID");
this.studentID = id;
String insertSql = "INSERT INTO REGISTEREDSTUDENTS(StudentID, ModuleCode) VALUES ('" + studentID + "', + '"
+ this.moduleCode + "')";
System.out.println("Inserting into REGISTEREDSTUDENTS.. [" + id + "]" + "[" + this.moduleCode + "]");
stmt.executeUpdate(insertSql);
}
} catch (SQLException e) {
}
}
..but for some reason,
while (rs.next()) {
int id = rs.getInt("ID");
always returns the same ID, even though the table has different ID's on every line!
Does anyone have an idea why that might be?
Thank you in advance! :(
EDIT:
I was using a single statement to execute 2 updates, which was causing the problem!
It is a bit weird that it returns always the same value because it should only return the first value ONCE.
If you print the stacktrace instead of just catching the exception and doing nothing, you will see that it will print something like:
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:794)
You are using THE SAME statement for a Select and then for an Insert. This causes the resultSet that is "attached" to the Statement to close because it is not supposed to be used again.
It can be easily fixed by creating another statement:
String insertSql = "INSERT INTO REGISTEREDSTUDENTS(StudentID, ModuleCode) VALUES ('" + studentID + "', + '"
+ this.moduleCode + "')";
System.out.println("Inserting into REGISTEREDSTUDENTS.. [" + id + "]" + "[" + this.moduleCode + "]");
Statement stmt2 = conn.createStatement();
stmt2.executeUpdate(insertSql);

LIKE Statements Not Working in Java SQL Prepared Statement

I'm working on creating a Java interface for an SQL database. I'm using prepared statements to perform the search queries, however they only work with "=" statements and not with LIKE statements.
The first sample code using "=" works successfully. The second sample, using a LIKE statement, does not work and just returns empty.
WORKS:
PreparedStatement SearchQuery = con.prepareStatement("Select * From Alumnus_A Where aFirstName = ? ORDER BY aLastName asc");
SearchQuery.setObject(1, FirstName);
ResultSet rs=SearchQuery.executeQuery();
DOESN'T WORK:
PreparedStatement SearchQuery = con.prepareStatement("Select * From Alumnus_A Where aFirstName LIKE ? ORDER BY aLastName asc");
SearchQuery.setObject(1, FirstName);
ResultSet rs=SearchQuery.executeQuery();
Any help is much appreciated, also if you could explain it to me keeping in mind I'm very new to Java and don't have a lot of programming experience yet.
The rest of my search button's code:
private void button_SearchActionPerformed(java.awt.event.ActionEvent evt) {
String FirstName = textField_FirstName.getText();
String LastName = textField_LastName.getText();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:Alumni_DB");
Statement st=con.createStatement();
con.commit();
System.out.print(FirstName + " ");
PreparedStatement SearchQuery = con.prepareStatement("Select * From Alumnus_A Where aFirstName LIKE ? ORDER BY aLastName asc");
SearchQuery.setString(1, FirstName);
ResultSet rs=SearchQuery.executeQuery();
String aUID="",aFName="",aLName="",aMInitial="",aHomePhone="",aCellPhone="";
while(rs.next())
{
aUID=rs.getString(1);
aFName=rs.getString(2);
aLName=rs.getString(3);
aMInitial=rs.getString(4);
aHomePhone=rs.getString(5);
aCellPhone=rs.getString(6);
System.out.println("UID " + aUID + " First Name " + aFName + " Last Name " + aLName + " Middle Initial " + aMInitial + " Home Phone " + aHomePhone
+ " Cell Phone " + aCellPhone);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
Note: Anything with the prefix 'a' is referring to a database column

select statement giving error for string variable

I am writing the following SQL query in my Java program
PreparedStatement pre = conn.prepareStatement("select ID,FirstName,LastName,Dept from "
+ "student where ID =" + ID + " or FirstName=" + firstName + ";");
However, I am getting the following error:
use the right syntax for FirstName="+Parker
How is this caused and how can I solve it?
You should take advantage of prepared statements by making use of prepared statements parameters. This way, you can set your parameters pragmatically using setters.
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html.
Here is a snippet from the Oracle docs:
PreparedStatement updateSales = null;
String updateString = "update " + dbName + ".COFFEES " + "set SALES =
? where COF_NAME = ?";
updateSales = con.prepareStatement(updateString);
updateSales.**setInt**(1, e.getValue().intValue());
updateSales.**setString**(2, e.getKey());
Just make sure you set the statements *in order a*s the sql query.
Use a PreparedStatement like this:
PreparedStatement pre = conn.prepareStatement("select ID,FirstName,LastName,Dept from student where ID = ? or FirstName = ?");
pre.setInt(1, ID);
pre.setString(2, firstName);
I haven't used sql in Java, but my guess is it is because you don't have single quotes around first name. You want:
PreparedStatement pre = conn.prepareStatement("select ID,FirstName,LastName,Dept from " + "student where ID =" + ID + " or FirstName='" + firstName + "';");
emphasis:
... FirstName='" + firstName + "';");

Categories