Retrieving data from mysql in Java - mysql

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try
{
Class.forName("java.sql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "parin");
Statement stmt=con.createStatement();
String query="Select * from Liblogin;";
ResultSet rs=stmt.executeQuery(query);
String username=rs.getString("username");
String password=rs.getString("password");
rs.close();
stmt.close();
con.close();
String enteredUsername=t1.getText().toString();
String enteredPassword = new String(t2.getText());
if(enteredUsername.contentEquals(username)&&enteredPassword.contentEquals(password))
{
Homepage a=new Homepage();
a.setVisible(true);
this.dispose();
}
else
{
JOptionPane.showMessageDialog(this,"Incorrect name and password.");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, e);
}
}
I am trying to retrieve my password and username from mysql database.But unable to do so because of some exception(Sql exception:Before start of result set.).

You need to call rs.first(); or rs.next(); before trying to read the values from a ResultSet row.
http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html#first%28%29
Calling rs.next(); is especially handy in a while-loop to process all the rows in the ResultSet.
// Get a result set from SQL query
while (rs.next()) {
// Process this row
}

Related

Java Sql Exception After End of Result Set

My code works fine but when I try to run the code it first shows java.sql.SQLException:After end of result set. I would like to know what is causing this and how to fix this as this is for a graded project.
public GenerateBill()
{
initComponents();
try
{
Class.forName("java.sql.DriverManager");
Connection con=(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstore","root","root");
Statement stmt=(Statement)con.createStatement();
String query, product;
query="select * from store;";
ResultSet rs=stmt.executeQuery(query);
while(rs.next());
{
product=rs.getString("productname");
jComboBox1.addItem(product);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e.toString());
}
}
When I execute the code a Message Dialog Box shows up first.
And when I click OK, the page I'm trying to make opens and executes normally.
So, I'm confused as to what it means. Also, I'm new to this site, so I don't really know how much of the code I need to add. The rest of the code is for different jButtons. The page is for Generating Bills/Receipts.
There are some parts in your code that could be better. Specifically,
Use com.mysql.jdbc.Driver as your DB is MySQL, instead of java.sql.DriverManager
No need to cast your Connection object.
After /bookstore you could add ?useSSL=false, although it is not mandatory, so something like jdbc:mysql://localhost:3306/bookstore?useSSL=false
Use java.sql.PreparedStatement instead of simply Statement.
Close your connection in a finally block after catch.
Eventually, your code should look somehow like the following,
public GenerateBill() {
initComponents();
Connection con = null;
ResultSet rs = null;
PreparedStatement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bookstore?useSSL=false","root","root");
String query = "select * from store";
stmt = con.prepareStatement(query);
String product;
rs = stmt.executeQuery();
while(rs.next())
{
product = rs.getString("productname");
jComboBox1.addItem(product);
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null,e.toString());
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
} catch (Exception e) {
LOG.error("Error closing the connection with the database...");
e.printStackTrace();
}
}
}
Try the above and let me know if it is OK. If not, please post the whole exception to see what causes the issue.

JavaFx combobox from mysql

Good Day I am completely new to coding. I am building an app which uses a combobox besides other library items. The problem I am facing is that while attempting to populate combobox items from a Mysql Db the item values get duplicated each time the drop down is clicked.
How I can keep this from happening ? I do understand that my approach itself could be erroneous.
#FXML
public void getStation() {
String sqlStationName = " select * from station ";
try {
conn = (Connection) DBConnection.connect();
PreparedStatement pstStn = conn.prepareStatement(sqlStationName);
ResultSet stnRS = pstStn.executeQuery(sqlStationName);
while (stnRS.next()) {
comboBoxStation.getItems().add(stnRS.getString("stationName"));
}
stnRS.close();
pstStn.close();
conn.close();
} catch (SQLException ex) {
System.err.println("ERR" + ex);
}
}
Ok so I moved the function to the initialize() method in the controller and created an Observabale list called station
private ObservableList<String> stationsList = FXCollections.observableArrayList();
#Override
public void initialize(URL url, ResourceBundle rb) {
//
String sqlStationName = " select * from station ";
try {
conn = (Connection) DBConnection.connect();
PreparedStatement pstStn = conn.prepareStatement(sqlStationName);
ResultSet stnRS = pstStn.executeQuery(sqlStationName);
while (stnRS.next()) {
stationsList.add(stnRS.getString("stationName"));
}
stnRS.close();
pstStn.close();
conn.close();
} catch (SQLException ex) {
System.err.println("ERR" + ex);
}
}
and then left only this line in the original function....seems to be working.
#FXML
private void getStation() {
comboBoxStation.setItems(stationsList);
}

inserting two tables from multiple databases in jdbc

How to insert the two tables from two databases in jdbc is it possible?
I have the code but its not working
public class MergeData {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
public static void main(String[] args) throws SQLException {
//"jdbc:mysql://localhost:3306/fhv1", "root", "root"
DBDataFetcher database1 = new DBDataFetcher("jdbc:mysql://localhost:3306/fhv1", "root", "root");
List<Object> restDetailsList = (List<Object>) database1.fetchTableRows("restdetails");
database1.closeConnection();
long restid = 0;
for(Object obj : restDetailsList) {
if (obj instanceof RestDetails) {
restid = ((RestDetails) obj).getRest_id();
System.out.print(restid + " ");
}
}
DBDataFetcher database2 = new DBDataFetcher("jdbc:mysql://localhost:3306/test", "root", "root");
List<Object> restLocationList = (List<Object>) database2.fetchTableRows("restlocation");
database2.closeConnection();
for(Object obj : restLocationList) {
if (obj instanceof RestLocation) {
((RestLocation) obj).setRest_id(++restid);
System.out.print(((RestLocation) obj).getRest_id() + " ");
restDetailsList.add(obj);
}
}
DBDataMerger merger = new DBDataMerger("jdbc:mysql://localhost:3306/db", "root", "root");
merger.mergeTable(restDetailsList, "restdetails");
merger.closeConnection();
}
}
In plain JDBC, you should create two connections (one for each database)
public Connection getDbConnection(String dbUrl, String driver, String user, String psw){
Connection conn=null;
try{
Class.forName(driver);
conn = DriverManager.getConnection(dbUrl,user,psw);
}catch(SQLException e){
//log exception
}
return conn;
}
And to insert records you can do something like
public void insertRecord(){
//add try and catch/finally
//inserting into 1st DB
Connection conn1 = getDBConnection(dbURl1, driver1, user1, psw1);
Statement stmt = conn1.CreateStatement();
String insert1 = "insert into tbl1 (a,b,c) values(1,2,2);
stmt.executeUpdate(insert1);
//inserting into 2nd DB
Connection conn2 = getDBConnection(dbURl2, driver2, user2, psw2);
stmt = conn2.CreateStatement();//reassing statement or use a new one
String insert2 = "insert into tbl2 (a,b,c) values(1,2,2);
stmt.executeUpdate(insert2);
}
Normally, you'll want to use a PreaparedStatement instead of Statement (because it's usually faster and more secure than a Statement)

How to get data from MYSQL database

I have a database named as "test" in which I have a table named as "first" which contains raw data, I want to get this table data. What should be the prepare statement I have to use in order to get data from table "first" ? Below is the code I am trying. Any help or guidance would be appreciable.
#Path("/database") // Specific URL
#GE
#Produces(MediaType.TEXT_PLAIN)
public String returnDB_Status() throws Exception {
PreparedStatement query = null;
String result = null;
Connection conn = null;
try {
conn = mysql_prac.dbConn().getConnection(); // this works fine ...
query = conn.prepareStatement("SELECT * from first" ); // Table named as "first" is placed inside the connected database.
ResultSet rs = query.executeQuery();
result = "Data received : " + rs;
query.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null)
conn.close();
}
return result;
}
and the source code used get a connection
public class mysql_prac {
private static DataSource mysql_prac = null;
private static Context context = null;
public static DataSource dbConn() throws Exception {
if (mysql_prac != null) {
return mysql_prac;
}
try {
if (context == null) {
context = new InitialContext();
}
mysql_prac = (DataSource) context.lookup("JDBC_ref"); //JNDI ID (JDBC_REF)
} catch (Exception e) {
e.printStackTrace();
}
return mysql_prac;
}
}
You must loop through the ResultSet to get the fields of each row. So I made the following edit together with some comments.Please notice the comments.
try {
conn = mysql_prac.dbConn().getConnection(); // this works fine ...
query = conn.prepareStatement("SELECT * from first" ); // Table named as "first" is placed inside the connected database.
ResultSet rs = query.executeQuery();//You must loop through the results set to get the fields of each row
while(rs.next()){
String dbUserID = rs.getString("column1");//this is just an example to retrieve all data in the column called 'column1'
result = "Data received : " + dbUserID;
System.out.println(result);
}
query.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null)
conn.close();
}

Store the results of ResultSet in a list

My goal is to centralize all the interactions with my MySql database in a single class (e.g. SqlUtils). I basically want to maintain access to ResultSet or a similar class even after the connection is closed. The following way doesn't work as after my business method receives the ResultSet, an exception is thrown because the underlying connection is already closed. I want to emphasize that opening and closing a connection to the database has to take place inside getResultSet().
public ResultSet getResultSet(String sql) {
try (Connection conn = getConnection();){
return conn.createStatement().executeQuery(sql);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
What I'm now thinking to do is something like this:
public List<ResultHolder> getResultSet(String sql) {
List<ResultHolder> list = new LinkedList<>();
try (Connection conn = getConnection();
ResultSet res = conn.createStatement().executeQuery(sql);) {
while(res.next()) {
list.add(res.convertToResultHolder());
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
Is there any class that does what I need, which I expressed as ResultHolder.
If you want to have access to all the resultset data even after connection is closed then I would suggest following:
public List<Map<String, Object>> getResultSet(String sql) {
// this list will hold all the data returned from resultset
List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
try (Connection conn = getConnection();
ResultSet rs = conn.createStatement().executeQuery(sql);) {
while(rs.next()) {
// this map corresponds to each row of the resultset
// key: column-name, value: column-value
Map<String, Object> row = new LinkedHashMap<String, Object>();
// populate each row using resultset's Meta data
ResultSetMetaData meta = rs.getMetaData();
for (int i=1; i<=meta.getColumnCount(); i++)
row.put(meta.getColumnName(i), rs.getObject(i));
rows.add(row);
}
} catch (Exception e) {
e.printStackTrace();
}
return rows;
}