I have a table attendance in which columns are id,name,date,status.Here what's the my problem is,If i select two dates(start date and end date) in my html page,I want to generate a attendance report of a student between the range of dates with name also no of present days also.How to write query for selecting name of the student and count of present days of particular student.For all help thanks in advance.
i wrote query like below.
String sql = "select student_name,count(status) from attendance where attendance.date>=? and attendance.date<=? and attendance.status=?";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test_schema", "root", "root");
String sql = "select student_name from attendance where attendance.date>=? and attendance.date<=? and attendance.status=?";
PreparedStatement pstmt = con.prepareStatement(sql);
//pstmt.setString(1, "Present");
pstmt.setString(1, stDate);
pstmt.setString(2, enDate);
pstmt.setString(3, "Present");
rs = pstmt.executeQuery();
while (rs.next()) {
java.sql.ResultSetMetaData rsmd=rs.getMetaData();
int colCount = rsmd.getColumnCount();
System.out.println("colCount :" + colCount);
System.out.println("count>>"+colCount);
StudentMark ge = new StudentMark();
ge.setStudentName(rs.getString(1));
stList.add(ge);
}
out.print(stList);
out.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
You can use the ResultSetMetaData to get the column count for any select query's result.
ResultSet rs= ... //Statement's result.
ResultSetMetaData rsmd= rs.getMetaData();
int colCount = rsmd.getColumnCount();
Related
public String searchSinger(String singer) throws SQLException
{
PreparedStatement ps = null;;
ResultSet rs = null;
String query = "SELECT id FROM ng_singers WHERE name = ?";
try{
ps = connection.prepareStatement(query);
ps.setString(1, singer);
rs = ps.executeQuery();
if(rs.next())
{
String id = rs.getString(1);
display = display + "\t" + id;
}
System.out.println(display);
return display;
}
catch(Exception e){
return display;
}
finally{
ps.close();
rs.close();
}
}
so this code works if I enter the name in the first record, but does not work for all record. I have table ng_singers in the db with records id:1 name: michael, id:2 name:janet, and so on. total 9 rows in the table. So the query only works for the name michael and 3 other names in row 5,7 and 9. the query does not retrieve data for rows 2,3,4,6 and 8. Any suggestions?
Not sure if i understand your question correctly.
If you want to retrieve all the records you have to do a
while(rs.Next()){
}
That iterates over all records and automatically assigns the next value to rs.
If you want to retrieve your commented fields, you have to add them to your "SELECT dob" like "SELECT dob,name,sex,record FROM" ..etc
I am trying to return a tuples within a certain year and I can't get the prepared statement to return anything but an empty set. Here is the parameter I call it with: year.valueOf("2014-01-01"); not sure if that's already the problem, and this is just for testing it's normally a value from a textfield.
public List<Sales> findYear(Date date) {
try {
List<Sales> listSales = new ArrayList<>();
I tried it with two parameters so this is just the test version.
When I hard code both dates into the prepared statement it works, so the method itself seems fine. Adding ' ' around the ? makes no difference.
PreparedStatement ps = ConnectDB
.getConnection()
.prepareStatement(
"select * from sales where sale_date between ? and '2014-12-30'");
ps.setDate(1, date);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Sales s = new Sales();
s.setEmpno(rs.getInt("empno"));
s.setOutno(rs.getInt("outno"));
s.setPno(rs.getInt("pno"));
s.setCno(rs.getInt("cno"));
s.setOno(rs.getInt("ono"));
s.setQty(rs.getInt("qty"));
s.setSale_date(rs.getDate("sale_date"));
s.setSale_time(rs.getTime("sale_time"));
listSales.add(s);
}
return listSales;
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
"select * from sales where sale_date between ?-?-? and ?-?-?"
Then set the dates:
prepare.setInt(1, day1);
prepare.setInt(2, month1);
prepare.setInt(3, year1);
prepare.setInt(4, day2);
prepare.setInt(5, month2);
prepare.setInt(6, year3);
You can also turn a date into a string:
"select * from sales where sale_date between ? and ?"
...
String date1Str = SimpleDateFormat("dd-MM-yyyy").format(date1);
String date2Str = SimpleDateFormat("dd-MM-yyyy").format(date2);
prepare.setString(1, date1Str);
prepare.setString(2, date2Str);
Expanded example:
try {
PreparedStatement ps = ConnectDB.getConnection()
.prepareStatement(
"select * from sales where sale_date between ? and ?");
ps.setDate(1, date);
// whatever date2 is
ps.setDate(2, date2);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Sales s = new Sales();
s.setEmpno(rs.getInt("empno"));
s.setOutno(rs.getInt("outno"));
s.setPno(rs.getInt("pno"));
s.setCno(rs.getInt("cno"));
s.setOno(rs.getInt("ono"));
s.setQty(rs.getInt("qty"));
s.setSale_date(rs.getDate("sale_date"));
s.setSale_time(rs.getTime("sale_time"));
listSales.add(s);
}
return listSales;
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
I have
employee(id, name, company, salary);
Need to display data for given id
public static void Connect(String conString, String username, String password, int id) throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection(conString, username, password);
String query = "select * from employee where id = " + id + "" ;
ResultSet rs = null;
Statement stmt = null;
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
while(rs.next()){
String name = rs.getString("name");
String company = rs.getString("company");
int salary = rs.getInt("salary");
System.out.println("Name: " + name + "\tCompany: " + company + "\tSalary: " + salary);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But here we are passing the id directly. How can we pass it like parametrized queries (like how we pass ? during PreparedStatement)
in that case your query should be
String query = "select * from employee where id = ?";
instead of Statement you need to create PreparedStatement
PreparedStatement preparedStatement = conn.prepareStatement(query);
and then set your id to the prepared statement
preparedStatment.setInt(1, id);
finally execute the query
resultSet = preparedStatement.executeQuery();
It's old post but I would still like to add my answer.
I don't have enough reputation to comment on #prasad's answer, so I am adding small correction as separate answer. Actually, passing query inside praparedStatement.executeQuery() throws MySQLSyntaxErrorException because still it calls Statement.executeQuery instead of PreparedStatement.executeQuery(). And how do I know? I had to spent ample amount of time in figuring out this issue.
So use PreparedStatement.executeQuery() instead of PreparedStament.executeQuery(query).
This is my function. It gets two parameter id of the product and a name. the function delete with MySQL command a row in a database. I know the that there are missing lines in my code, I'm stuck and I don't know how to finish it. I also know that my SQL line is not correct. I'm not sure if combined the String "name" right.
public static deletePro(int cat, String name) {
DB db = new DB();
String sql = "delete from products where pname=+'name' and catid=" + cat;
ResultSet rs = db.getResultSet(sql);
try {
while (rs.next()) {
Products prod = new Products();
prod.setNamePro(rs.getString(name));
prod.setAmount(rs.getInt(cat));
}
rs.close();
db.closeCon();
} catch (SQLException e) {
e.printStackTrace();
}
return
}
String sql = "delete from products where pname=+'name' and catid=" + cat;
This should be:
String sql = "DELETE FROM products WHERE pname='" + name + "' and catid = " + cat;
And the preferred way is to use PreparedStatement, which would alleviate the pain of string manipulation in your query by using placeholders:
String sql = "DELETE FROM products WHERE pname= ? and catid = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, name);
ps.setInt(2, cat);
ps.executeUpdate();
Hope this helps.
I have a mySQL table named userinfo with colums- userId, userName, Password, city, age- userId is Pkey and Autoincremnt
When a user Login on a login.jsp, he submits username and Pasword.
These two parameters of login.jsp are received in UserLogin servlet and then checked in userinfo Table. If matched, he could log in.
I tried SELECT but I get numerous error. What should be the correct way:-
try {
String sql = "Select UserName, UserPW From SocialNetwork.RegisteredUser";
conn = ConnectionFactory.getConnection();
PreparedStatement ptmt = (PreparedStatement) conn
.prepareStatement(sql);
ptmt.executeQuery();
Statement stmt = (Statement) conn.createStatement();
s = connection.prepareStatement("select id_usuario, id_grupo from usuarios_grupos where id_grupo = ?");
//storing user data in ResultSet
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String refName = rs.getString("UserName");
String refPass = rs.getString("UserPW");
if (user.equals(refName) && pw.equals(refPass) ) {
out.println("<html>");
out.println("<body>");
out.println("You are In");
out.println("</body>");
out.println("</html>");
System.out.println("sucess");
}
}
}catch (SQLException e) {
e.printStackTrace();
}
by using Statement interface you can not dynamically set the values. use PreparedStatement interface for second query.
import package in you class import javas.sql.*;
try {
String sql = "Select UserName, UserPW From SocialNetwork.RegisteredUser UserName = ?";
conn = ConnectionFactory.getConnection();
PreparedStatement ptmt =conn.prepareStatement(sql);
ptmt.setString(1, user)
ResultSet rs= ptmt.executeQuery();
while (rs.next()) {
String refName = rs.getString(1);//field index of user name
String refPass = rs.getString(2);//field index of password
if (user.equals(refName) && pw.equals(refPass) ) {
out.println("<html>");
out.println("<body>");
out.println("You are In");
out.println("</body>");
out.println("</html>");
System.out.println("sucess");
}
}
}catch (SQLException e) {
e.printStackTrace();
}
Are you asking for the entire code listing? in your current code you seem to be executing some queries for no reason, then getting a list of all users and iterating through them looking for a match. Try using a query like
sql ="Select UserName, UserPW From SocialNetwork.RegisteredUser where UserName=?"
ResultSet rs = stmt.executeQuery(sql);
then check the password in code
if(rs.next()){
String refPass = rs.getString("UserPW");
if (pw.equals(refPass) )
}