mysql Column not found loop - java

Hi have a method that creates a LinkedList of compMac object. CompMac object contain elements from a mysql table row. Each row contain a nickname and a location so I use a loop to create a 'compMac' for each row and add them in the linkedlist. I don't know why, but the first 'compMac' is created and is being added to the linkedlist, but after that I get
java.sql.SQLException: Column 'nickname' not found.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:920)
at com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1163)
at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5729)
at server.DbConnect.getArray(DbConnect.java:224)
at server.doComms.sendArray(doComms.java:127)
at server.doComms.whileChatting(doComms.java:107)
at server.doComms.run(doComms.java:32)
at java.lang.Thread.run(Thread.java:695)
Here is my method:
public LinkedList<compMac> getArray()
{
LinkedList<compMac> locArray = new LinkedList<compMac>();
try{
String query = "SELECT * FROM online";
rs = st.executeQuery(query);
while(rs.next()){
String nn = rs.getString("nickname");
String loc = rs.getString("location");//mac addresses
String cX=getCoorX(loc);
String cY=getCoorY(loc);
String building=getBuilding(loc);
String floor=getFloor(loc);
locArray.add(new compMac(nn,loc,cX,cY,building,floor));
}
}
catch(Exception e){e.printStackTrace();}
return locArray;
}
But I do have a nickname column, I like I said, the first compMac is created, when I pop the linkedlist I get the first row's informations.
Thanks to anyone having an idea whats wrong with my code.
EDIT: Here the class code:
package server;
import java.sql.*;
import java.util.LinkedList;
import com.example.client.Mac;
import com.example.client.compMac;
public class DbConnect {
private Connection con;
private Statement st;
private Statement stClean;
private ResultSet rs;
public DbConnect(){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://melucio.no-ip.biz:3306/TOC","XXXXX","XXXXXXX");
st = con.createStatement();
stClean = con.createStatement();
}catch(Exception ex){
System.out.println("Error: "+ex);
}
}
/*This method returns the x coor. of mac address*/
public String getCoorX(String mac){
String cX = "";
try{
String query = "SELECT * FROM coordinate";
rs = st.executeQuery(query);
while(rs.next()){
if(rs.getString("mac").equals(mac)){
return rs.getString("coorX");
}
}
}
catch(Exception e){}
return cX;
}
/*This method returns the y coor. of mac address*/
public String getCoorY(String mac){
String cY = "";
try{
String query = "SELECT * FROM coordinate";
rs = st.executeQuery(query);
while(rs.next()){
if(rs.getString("mac").equals(mac)){
return rs.getString("coorY");
}
}
}
catch(Exception e){}
return cY;
} public String getBuilding(String mac){
String buil = "";
try{
String query = "SELECT * FROM coordinate";
rs = st.executeQuery(query);
while(rs.next()){
if(rs.getString("mac").equals(mac)){
return rs.getString("building");
}
}
}
catch(Exception e){}
return buil;
}
public String getFloor(String mac){
String fl = "";
try{
String query = "SELECT * FROM coordinate";
rs = st.executeQuery(query);
while(rs.next()){
if(rs.getString("mac").equals(mac)){
return rs.getString("floor");
}
}
}
catch(Exception e){}
return fl;
}
/*Update the location table*/
public void updateLocation(String userNN,String location){//,long time){
long time = System.currentTimeMillis();
if(!isOnline(userNN))
{System.out.println("not online");
setOnline(userNN,location);}
else{
try{
//String query ="UPDATE online SET location = '" +location +"' WHERE nickname='" +userNN +"'";
String query ="UPDATE online SET location = '" +location +"', lastSeen = "+time +" WHERE nickname='" +userNN +"'";
st.executeUpdate(query);
}
catch(Exception e){System.out.println("ayayaya");}
}
}
public LinkedList<compMac> getArray()
{
LinkedList<compMac> locArray = new LinkedList<compMac>();
try{
String query = "SELECT * FROM online";
rs = st.executeQuery(query);
while(rs.next()){
String nn = rs.getString("nickname");
String loc = rs.getString("location");//mac addresses
String cX=getCoorX(loc);
String cY=getCoorY(loc);
String building=getBuilding(loc);
String floor=getFloor(loc);
locArray.add(new compMac(nn,loc,cX,cY,building,floor));
}
}
catch(Exception e){e.printStackTrace();}
return locArray;
}
public void clean()
{
long currentTime = System.currentTimeMillis();
long acceptableTime = currentTime-120000;
try{
String query = "SELECT * FROM online";
rs = st.executeQuery(query);
while(rs.next()){
String nn = rs.getString("nickname");
Long ls = rs.getLong("lastSeen");
if(ls<acceptableTime)//{}
{stClean.executeUpdate("DELETE FROM online WHERE nickname='"+nn+"'");}
}
}
catch(Exception e){e.printStackTrace();}
}
}

As per your code you are reusing the same Statement object in different methods. So after the first iteration the last method getFloor changes the st object to query on coordinate table. I suggest you initialize separate Statement objects in every method and close it in finally block.
import com.example.client.Mac;
import com.example.client.compMac;
public class DbConnect {
private Connection con;
public DbConnect(){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://melucio.no-ip.biz:3306/TOC","XXXXX","XXXXXXX");
}catch(Exception ex){
System.out.println("Error: "+ex);
}
}
/*This method returns the x coor. of mac address*/
public String getCoorX(String mac){
String cX = "";
try{
String query = "SELECT * FROM coordinate";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()){
if(rs.getString("mac").equals(mac)){
return rs.getString("coorX");
}
}
rs.close();
st.close();
}
catch(Exception e){}
return cX;
}
/*This method returns the y coor. of mac address*/
public String getCoorY(String mac){
String cY = "";
try{
String query = "SELECT * FROM coordinate";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()){
if(rs.getString("mac").equals(mac)){
return rs.getString("coorY");
}
}
rs.close();
st.close();
}
catch(Exception e){}
return cY;
} public String getBuilding(String mac){
String buil = "";
try{
String query = "SELECT * FROM coordinate";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()){
if(rs.getString("mac").equals(mac)){
return rs.getString("building");
}
}
rs.close();
st.close();
}
catch(Exception e){}
return buil;
}
public String getFloor(String mac){
String fl = "";
try{
String query = "SELECT * FROM coordinate";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()){
if(rs.getString("mac").equals(mac)){
return rs.getString("floor");
}
}
rs.close();
st.close();
}
catch(Exception e){}
return fl;
}
/*Update the location table*/
public void updateLocation(String userNN,String location){//,long time){
long time = System.currentTimeMillis();
if(!isOnline(userNN))
{System.out.println("not online");
setOnline(userNN,location);}
else{
try{
//String query ="UPDATE online SET location = '" +location +"' WHERE nickname='" +userNN +"'";
String query ="UPDATE online SET location = '" +location +"', lastSeen = "+time +" WHERE nickname='" +userNN +"'";
st.executeUpdate(query);
}
catch(Exception e){System.out.println("ayayaya");}
}
}
public LinkedList<compMac> getArray()
{
LinkedList<compMac> locArray = new LinkedList<compMac>();
try{
String query = "SELECT * FROM online";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()){
String nn = rs.getString("nickname");
String loc = rs.getString("location");//mac addresses
String cX=getCoorX(loc);
String cY=getCoorY(loc);
String building=getBuilding(loc);
String floor=getFloor(loc);
locArray.add(new compMac(nn,loc,cX,cY,building,floor));
}
rs.close();
st.close();
}
catch(Exception e){e.printStackTrace();}
return locArray;
}
public void clean()
{
long currentTime = System.currentTimeMillis();
long acceptableTime = currentTime-120000;
try{
String query = "SELECT * FROM online";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()){
String nn = rs.getString("nickname");
Long ls = rs.getLong("lastSeen");
if(ls<acceptableTime)//{}
{stClean.executeUpdate("DELETE FROM online WHERE nickname='"+nn+"'");}
}
}
catch(Exception e){e.printStackTrace();}
}

Related

No suitable driver found for jdbc:mysql//localhost/sakila

I'm trying to set up JDBC but I'm getting this error.
I tried adding the dependency in pom.xml and even jar file nothing works. I tried the methods mentioned in previous questions, nothing works.
public class FilmLength {
public static void main(String[] args) throws SQLException {
Connection dbCon = null;
PreparedStatement st = null;
ResultSet rs = null;
String url = "jdbc:mysql//localhost:3306/sakila";
String username = "devuser";
String password = "Demo#123";
String query = "select * from film ";
try {
Class.forName("com.mysql.jdbc.Driver");
dbCon = DriverManager.getConnection(url,username,password);
st = dbCon.prepareStatement(query);
rs = st.executeQuery();
while(rs.next()) {
String title = rs.getString(1);
System.out.println(title);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
dbCon.close();
st.close();
rs.close();
}
}
}
Instead of
String url = "jdbc:mysql//localhost:3306/sakila";
it should be
String url = "jdbc:mysql://localhost:3306/sakila";

Using two combobox to set conditions for a search in a database and displaying in jtable

I need to display the details of students in a particular stream of a schoolclass in Jtable from a database containing all the names of students in the school. I have two jComboboxes, on to select which class and the other to select the stream. I am asking for a way to define these two conditions in order to display all the students in a particular stream in a jtable. I apologize in advance if my code is messy.
public Classes() {
initComponents();
show_student();
}
public Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sms", "root", "");
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return con;
}
public ArrayList<Individualclass> studentList(String ValToSearch) {
ArrayList<Individualclass> list = new
ArrayList<Individualclass>();
Statement st;
ResultSet rs;
try {
Connection con=getConnection();
st = con.createStatement();
String searchQuery = "SELECT * FROM `students` WHERE CONCAT(`firstName`, `surname`, `otherNames`, `regNo`) LIKE '%"+ValToSearch+"%'";
rs = st.executeQuery("searchQuery ");
Individualclass ic;
while(rs.next()) {
ic = new Individualclass(
rs.getString("firstName"),
rs.getString("surname"),
rs.getString("otherNames"),
rs.getInt("regNo")
);
list.add(ic);
}
} catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
return list;
}
public void findStudents() {
}
private void sClassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sClassActionPerformed
try {
Connection con = getConnection();
String fetch_row = "SELECT * FROM students where sClass=?";
PreparedStatement pst = con.prepareStatement(fetch_row);
pst.setString(1, (String) sClass.getSelectedItem());
ResultSet rs = pst.executeQuery();
while(rs.next()) {
Individualclass ic = new Individualclass(rs.getString("firstName"),rs.getString("surname"),rs.getString("otherNames"),rs.getInt("regNo"));
}
} catch(Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_sClassActionPerformed
private void streamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_streamActionPerformed
try {
Connection con = getConnection();
String fetch_row = "SELECT * FROM students where stream=?";
PreparedStatement pst = con.prepareStatement(fetch_row);
pst.setString(1, (String)stream.getSelectedItem());
ResultSet rs = pst.executeQuery();
while(rs.next()) {
Individualclass ic = new Individualclass(rs.getString("firstName"),rs.getString("surname"),rs.getString("otherNames"),rs.getInt("regNo"));
}
} catch(Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_streamActionPerformed
public void show_student() {
ArrayList<Individualclass> list = new ArrayList<Individualclass>();
DefaultTableModel model = (DefaultTableModel)jTable_Display_Student.getModel();
Object [] row = new Object[13];
for(int i = 0; i < list.size(); i++) {
row[0] = list.get(i).getFirstName();
row[1] = list.get(i).getsurname();
row[2] = list.get(i).getOtherNames();
row[3] = list.get(i).getregNo();
model.addRow(row);
}
}

Ambiguous behavior of ResultSet

I have a requirement to create separate POJO which will set/get sql ResultSet and use its methods throughout my project code like below. I have created below 2 classes
public class Tester3
{
public MyResultSet test() throws SQLException{
MyResultSet mrs = new MyResultSet();
PreparedStatement ps = null;
String values = null;
boolean flag = false;
String one = "'12'";
String two = "'jt'";
String a = null;
String b = null;
try {
if(flag==true)
{
values = "'3%'";
a =null;
b = "OR id IN(\'" +a+ "\')";
}else
{
values = "'%'";
a = one + "," + two;
b = "AND id IN("+a+")";
}
String sql = "SELECT * FROM veracodetable where orts like PARAM RAMAN";
sql = sql.replaceFirst("PARAM", values);
sql = sql.replaceFirst("RAMAN", b);
System.out.println("SQL: "+sql);
ps = new Connection1().getConnection().prepareStatement(sql);
ps.executeQuery();
mrs.setRs(ps.executeQuery());
System.out.println("ResultSet: "+mrs.getRs().next());
} catch (SQLException e) {
e.printStackTrace();
}
return mrs;
}
public static void main(String[] args) throws SQLException {
Tester3 t = new Tester3();
MyResultSet rs = t.test();
System.out.println("ResultSet: "+rs.getRs().next());
}
}
public class MyResultSet {
ResultSet rs = null;
public ResultSet getRs() {
return rs;
}
public void setRs(ResultSet rs) {
this.rs = rs;
}
}
When executed above code with separate POJO MyResultSet, I don't get any result in ResultSet. However if I skip POJO implementation and use resultSet directly, I am able to get results.
Is rs.getRs() invoking at all? If not, why?
I would separate the statements as they dont't perform the same function, and then populate;
PreparedStatemet ps = null;
ResultSet rs = null;
if(flag){
String stmt = "...?...?";
ps = con.preparedStatement(stmt);
ps.setString(0,a);
ps.setString(1,b);
rs = ps.executeQuery;
}else{
String stmt = "...?...?";
ps = con.preparedStatement(stmt);
ps.setString(0,a);
ps.setString(1,b);
rs = ps.executeQuery;
}
}

Could not load create coonection in addProduct method

package com.Foodmart;
import javax.jws.*;
import java.sql.*;
#WebService(name = "FoodMart", serviceName = "FoodMartService", portName = "FoodMartHtt)
public class FoodmartWS {
ProductDetails prod = new ProductDetails();
#WebMethod(operationName = "check")
public boolean Authenticate(String user, String pass) {
PreparedStatement psmt = null;
Connection c = null;
try {
c = ConnectionDB.getConnection();
String selectSQL = "select * from Employee where Username=? and Password=?";
psmt = c.prepareStatement(selectSQL);
psmt.setString(1, user);
psmt.setString(2, pass);
psmt.executeQuery();
c.close();
return true;
} catch (SQLException e) {
return false;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
In this Method Error in AddProduct
#WebMethod(operationName = "AddProduct")
public ProductDetails ProdcutAdd(int prodid, double qty) {
PreparedStatement preparedStatement = null;
Connection con = null;
try {
System.out.println("try");
//here i am not able to create another one connection
con = ConnectionDB.getConnection();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Food", "root", "manager1");
String selectSQL = "select Product_Id,Product_Name,Product_Price,Product_Qty from Products where Product_Id=?;";
System.out.println("bbefore prepared");
preparedStatement = con.prepareStatement(selectSQL);
preparedStatement.setInt(1, prodid);
System.out.println("before result set");
ResultSet rs = preparedStatement.executeQuery();
System.out.println("query Executed");
rs.next();
prod.setProductId(rs.getInt("Product_Id"));
prod.setProductName(rs.getString("Product_Name"));
prod.setProductPrice(rs.getDouble("Product_Price"));
prod.setProductQty(rs.getInt("Product_Qty"));
System.out.println("obj set");
con.close();
System.out.println("in" + prod);
return prod;
} catch (SQLException e) {
System.out.println(e);
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
Why you add this line after you get your connection :
con = ConnectionDB.getConnection();
//con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Food", "root", "manager1");
So just delete it or comment it.
Note
you missed a ") here in the end, so this can also make a problem :
#WebService(name = "FoodMart", serviceName = "FoodMartService", portName = "FoodMartHtt)
Hope this can help you.

getting values in jtable upon seletio on jcombox

1.i have a jcombobox which is getting the value from database ,
2. upon the selection on the value i want to display that particular row in the jtable ,
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Object obj = jComboBox1.getSelectedItem();
String tmpr = obj.toString();
Rtable rObj = new Rtable();
rObj.setUserName(tmpr);
}
private void Update_table(){
String Sql = "SELECT * FROM r_db1.dbo.user_names " + jComboBox1.getSelectedItem()
I am getting a error like "UnsupportedOperationException("Not supported yet.")"
Try this
use loadcombo() method to load ur jcombobox.
void loadcombo()
{
try
{
Connection con=null;
Statement st=null;
ResultSet rs=null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url=null,userID=null,password=null;
String dbFileName=null;
String sql=null;
dbFileName = "C:/db.accdb";
//userID = "Admin";
password = "***";
url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};"+
"DBQ="+dbFileName+";"+
"Pwd="+password+";";
//sql = "SELECT * FROM tblUserProfile";
con=DriverManager.getConnection(url);//,"system","manager"
//con=DriverManager.getConnection("jdbc:odbc:shop","system","manager");
st=con.createStatement();
rs= st.executeQuery("select distinct(Name) from Table");
while(rs.next())
{
jComboBox.addItem(rs.getString(1));
}
st.close();
con.close();
}
catch(Exception e)
{
System.out.println("GG"+e);
}
}
use jcombobx actionlistener to load data into jtable.
jComboBox.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
try
{
Connection con=null;
Statement st=null;
ResultSet rs=null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url=null,userID=null,password=null;
String dbFileName=null;
String sql=null;
dbFileName = "C:/db.accdb";
url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};"+
"DBQ="+dbFileName+";";
//sql = "SELECT * FROM tblUserProfile";
Object name=jComboBox.getSelectedItem();
con=DriverManager.getConnection(url);//,"system","manager"
//con=DriverManager.getConnection("jdbc:odbc:shop","system","manager");
st=con.createStatement();
model.setRowCount(0);
data = getvalue(name);
JTable table1=new JTable(data,header);
for(int i=0;i<table1.getRowCount();i++){
Object[] d={data.get(i).get(0),data.get(i).get(1),data.get(i).get(2)};model.addRow(d);
}
con.close();
}
catch(Exception e)
{
System.out.println("GG"+e);
}
}
public Vector getvalue(Object name)throws Exception
{
Vector<Vector<String>> vector = new Vector<Vector<String>>();
Connection conn = dbConnection();
PreparedStatement pre = conn.prepareStatement("select * from Table where Name='"+name+"'");
ResultSet rs = pre.executeQuery();
while(rs.next())
{
Vector<String> c = new Vector<String>();
c.add(rs.getString(4));
c.add(rs.getString(5));
c.add(rs.getString(6));
vector.add(c);
}
/*Close the connection after use (MUST)*/
if(conn!=null)
conn.close();
return vector;
}
});

Categories