I'm trying to scroll over all the contents of a database. How do I properly do this:
conc conclass = new conc();
Connection conn = conclass.dbConnect();
try{
Statement statement=conn.createStatement();
ResultSet rs;
String sql;
rs=statement.executeQuery("SELECT * FROM q_table");
if(rs.next()){
String yo=rs.getString("Question");
jTextArea1.setText(yo);
}
}catch(Exception e){e.printStackTrace();}
And here's my class for connecting to the database:
public Connection dbConnect() {
try {
String db_connect_string="jdbc:mysql://localhost:3306/questions";
String db_userid="root";
String db_password="1234";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection(db_connect_string, db_userid, db_password);
return conn;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
What is wrong with my code? It loads the first record when I click on the scroll button. But when I click it again. It doesn't do anything at all.
To collect all results from table (I assume you mean the table rather than the whole database):
while(rs.next()) {
String yo=rs.getString("Question");
// add 'yo' to a list or similar...
}
You need to iterate across your ResultSet. The ResultSet scrolls over each row returned from the database in sequence. See this example for more details.
You need to keep the Resultset open. For every click on the button, you must call rs.next() once. After that, a new row will copied into the ResultSet.
Related
I'm trying to display movie titles from the database, the problem is that if I call the rs.getString() method it always returns null. The database table is properly configured with one column/two rows and connected to the java application, so I don't know where the problem is..
This is my class which I call from the main function:
import java.sql.*;
public class Driver {
public Driver() {
Connection c = null;
try {
Class.forName("org.sqlite.JDBC");
// DriverManager.registerDriver(new org.sqlite.JDBC());
c = DriverManager.getConnection("jdbc:sqlite:test.db");
Statement stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM Movies");
rs.next();
System.out.println(rs.getString("title")); // <---- prints null
stmt.close();
c.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
3 things that seem weird:
you are using rs.next() before even using the first resultset.
it's not in a loop, meaning you'll only get the first result no matter how many rows there are
you are returning it in one string (getString) so I don't think it will return it properly.
So Sorry if this Looks newbie Question, Im not Skilled in Mysql, I need to Get Entries of All Rows in My Mysql Database like We Do with Sqlite in Android :
Cursor mCursor = mDb.query("MyTable",new String[]{"My Column"},null,null.null,null);
ArrayList<> mylist = new ArrayList<>();
do{
mylist.add(mCursor.getString(mCursor.getColumnIndex("_id")));
while(mCursor.moveToNext());
How does This Work in Mysql Guys?
first you have to create connection to your database, You can use JDBC for it.
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
public Dbconnection()
{
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename","root","root");
}
catch(Exception e)
{
System.out.println("Error in connection"+e);
}
}
connection created in the constructor,
method to get all rows from a table
public void getData()
{
try{
ps=con.prepareStatement("select * from tbl_name");
rs=ps.executeQuery();
while(rs.next())
{
System.out.println(rs.getString(1)); //here you can get data, the '1' indicates column number based on your query
}
}
catch(Exception e)
{
System.out.println("Error in getData"+e);
}
}
In the while loop you can all data from rs using rs.getString(1)
NB: change column number for different column.
To get more idea please refer the links:
http://www.tutorialspoint.com/jdbc/index.htm
http://www.w3schools.com/sql/
I am working on a project "Hospital Management System" in java swing. Now I have a text field whose value is supposed to be increased by one whenever page loads. It basically contain the value of patient Id. Now I want to retrieve the maximum or last value from database and increase it by one and want to set that value in a text field whose variable is "textField_1". Here table name is "patient" and column name is "patid" and this snippet is written in page load event. Select query is successfully executed but the problem is not fetching the maximum value from the database. Control reached in the if block but it's not printing the value if "i". Please help!!
try
{
Connection con;
Statement st;
ResultSet rs;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("Jdbc:Odbc:hos_man");
st=con.createStatement();
rs=st.executeQuery("select * from patient where patid = (select max(patid) from patient);");
if (rs.next()==true)
{
int i=rs.getInt(1);
i++;
textField_1.setText(""+i);
}
else
{
textField_1.setText(""+100);
}
con.close();
st.close();
rs.close();
}
catch (Exception e)
{
}
Firstly your Query is right, but its bad practice. if you need only max(patid) then use this query:
select max(patid) from patient
Then modify your code like below.
try
{
Connection con;
Statement st;
ResultSet rs;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("Jdbc:Odbc:hos_man");
st=con.createStatement();
rs=st.executeQuery("select max(patid) from patient");
int i=100;
while (rs.next())
{
i=rs.getInt(1);
}
textField_1.setText(""+i);
con.close();
st.close();
rs.close();
}
catch (Exception e)
{
e.printStackTrace();
}
This should work
Hi this is my java code for next button.
but it goes onto only 1 record i.e after the last record it moves to the 1st one only.
how to move it through the entire database entries.
plz provide me some suggestions.
public void Next() {
Connection con = null;
ResultSet rs = null;
try {
con = DBConnection();
PreparedStatement pstmt = con.prepareStatement("select * from data", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = pstmt.executeQuery();
if (rs.next()) {
field1.setText(rs.getString("Name"));
field2.setText(String.valueOf(rs.getInt("Age")));
} else {
rs.previous();
JOptionPane.showMessageDialog(nxtbtn, "end of file");
}
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
rs.close();
} catch (SQLException err) {
JOptionPane.showMessageDialog(nxtbtn, err.getMessage());
// TODO: handle exception
}
}
}
When you call next, it reloads all the results from the database and moves the cursor to just before the first row, calling rs.next will move to the first row.
Do you're query once, presumably when you need to display the next record.
In your next method, simply call rs.next() to move the cursor to the next available row in the result set.
Of course, you'll need continue to manage the error states ;)
you need to get the resultset out side of the next() method. calling next() every-time resets the resultset, and cursor moves to start again.
if understand it correctly you want to use the next button to click throup the resultset?
then you shoul read the database an have it stored in your resultset outside the next button method.
at the moment it seems that your making a new resultset with every click and only reading the first set of data.
private Connection con = DBConnection();
private ResultSet rs = null;
private Statement stmt = null;
public void onLoad()
{
stmt = con.createStatement();
rs = stmt.executeQuery("YOUR-CODE-HERE");
}
and now in the next method go through the rs with each click
rs.next() move the cursor to the next available row.thats why it show one record. use while(rs.next())
Move one record forward like below
rs.next()
Move through all the 'next' records like below
while(rs.next())
Move back like below
rs.previous()
I am trying to create a simple web app that saves user data from a form to a database and reads the content of the database back to browser upon request. Following are the functions I have written so far.
connectToDB() // connects to database
addEmployee() // adds employee to database
displayEmployee() // returns a resultSet
isExisted(int staffID) // checks if the staff already exists
Database connection function:
public void connectToDB(){
try{
// load Apache derby driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
} catch(ClassNotFoundException e) {
System.err.println(e);
}
try{
connection = DriverManager.getConnection(DBNAME, USERNAME, PASSWORD);
} catch(SQLException e){
System.err.println(e);
}
} // end connectToDB
Display Employee function:
public ResultSet displayEmployee(){
connectToDB();
ResultSet result = null;
try{
Statement stmt = connection.createStatement();
String query = "SELECT * FROM APP.ADDRESSBOOK";
result = stmt.executeQuery(query);
} catch(SQLException e) {
System.err.println(e);
}
return result;
}
Check if employee exists:
public boolean isExisted(int StaffID){
connectToDB();
try{
Statement stmt = connection.createStatement();
String query = "SELECT StaffNum FROM APP.ADDRESSBOOK WHERE StaffNum = " + staff_number;
ResultSet result = stmt.executeQuery(query);
while(result.next()){
int temp = result.getInt(1);
if(temp == staff_number){return true;}
}
} catch(SQLException e) {
System.err.println(e);
}
return false;
}
As you can see, if you compare the displayEmployee() and isExisted(), I am repeating mysel. Both the function works but I am looking to refactor the code. In those function I havent closed the connection. If there were 20 functions in the web app that connects to the database my code would stink.
I am looking something like this:
* THIS CODE DOESNT WORK ******
private Statement queryDB(query){
connectToDB();
Statement stmt;
try{
stmt = connection.createStatement();
} catch(SQLException e) {
System.err.println(e);
}
return stmt;
// code for closing connection
}
public ResultSet DisplayEmployee(){
String query = "SELECT * FROM APP.ADDRESSBOOK";
Statement stmt = queryDB(query);
ResultSet result = stmt.executeQuery(query);
return result;
}
Thanks.
Using raw JDBC produces a lot of unsightly boilerplate code. One solution is to use Spring JDBC Template.
In addition you will get the sql exception hierarchy which will manage the underlying JDBC exceptions automatically as runtime exceptions.
For more see:
Introduction to Spring Framework JDBC
A couple of comments:
The catch statement of ClassNotFoundException should throw an exception and shouldn't continue further.
It is not a good idea to return resultsets from a method that obtained them upon statement execution, since it is the responsibility of that method to close it. Instead, you should either read out the results into objects or cache them into CachedRowSet if your downstream functions expect a resultset.
The connectToDB method should return a successful connection or throw exception.
You could write a method that takes in an SQL query and return the results as objects so that this method can be used for retrieving based on different criteria as long you are retrieving the objects of same type.
isExisted is using staff_number which I think you intend it to be staffID. If you found a row with this value, then there is no need to check if the result set contained the row with this value, right?
My two cents!