The following code doesn't show any error and the code executes but the data that is calculated and stored in rfv is not updated in the database.
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
com.mysql.jdbc.Connection con = (com.mysql.jdbc.Connection) DriverManager.getConnection("jdbc:mysql://localhost:3308/rk","root","root");
ResultSet rsfact=null;
PreparedStatement psfact=(PreparedStatement) con.prepareStatement("SELECT * FROM fact");
PreparedStatement psgraph=(PreparedStatement) con.prepareStatement("INSERT INTO graph values(?,?,?,?)");
int cp,ic,rc,fi,ct,tr;
while(rsfact.next())
{
cp=rsfact.getInt("1");
ic=rsfact.getInt("2");
rc=rsfact.getInt("3");
fi=rsfact.getInt("4");
ct=rsfact.getInt("5");
tr=rsfact.getInt("6");
int rfv;
rfv=(cp+ic+rc+fi+ct+tr)/6;
graph.setInt(1, rfv);
graph.executeUpdate();
}
}
catch(Exception e){
System.out.println(e);
}
I checked the code and everything seems to be fine for me but i couldn't figure out the reason for the data which is not inserted into the table.
I get the following when this is executed
java.lang.NullPointerException
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
com.mysql.jdbc.Connection con = (com.mysql.jdbc.Connection) DriverManager.getConnection("jdbc:mysql://localhost:3308/rk","root","root");
ResultSet rsfact=null;
ResultSet rsfault=null;
ResultSet rspriority=null;
ResultSet rsreq=null;
PreparedStatement psfact=(PreparedStatement) con.prepareStatement("SELECT * FROM fact");
PreparedStatement psfault=(PreparedStatement) con.prepareStatement("SELECT * FROM fault");
PreparedStatement pspriority=(PreparedStatement) con.prepareStatement("SELECT * FROM priority");
PreparedStatement psreq=(PreparedStatement) con.prepareStatement("SELECT * FROM req");
PreparedStatement graph=(PreparedStatement) con.prepareStatement("INSERT INTO gr values(?)");
int cp,ic,rc,fi,ct,tr;
rsfact = psfact.executeQuery();
rsfault=psfault.executeQuery();
rspriority=pspriority.executeQuery();
rsreq=psreq.executeQuery();
while(rsfact.next())
{
cp=rsfact.getInt(1);
ic=rsfact.getInt(2);
rc=rsfact.getInt(3);
fi=rsfact.getInt(4);
ct=rsfact.getInt(5);
tr=rsfact.getInt(6);
int rfv;
rfv=(cp+ic+rc+fi+ct+tr)/6;
graph.setInt(1, rfv);
graph.executeUpdate();
}
while(rsfault.next()){
cp=rsfact.getInt(1);
fic=rsfact.getInt(2);
frc=rsfact.getInt(3);
ffi=rsfact.getInt(4);
fct=rsfact.getInt(5);
ftr=rsfact.getInt(6);
int tsfv;
tsfv=((fcp*2)+(fic*3)+(frc*4)+(ffi*3.14)+(fct-4)+(ftr+9))/6;
graph.setInt(2, tsfv);
graph.executeUpdate();
}
}
you are not instatiating rsfact(ResultSet object) and trying to invoke methods of result set thus NULLPOINTEREXCEPTION.
ResultSet rsfact=null; // **rsfact is null**
int colCount=1;
PreparedStatement psfact=(PreparedStatement) con.prepareStatement("SELECT * FROM fact");
PreparedStatement psgraph=(PreparedStatement) con.prepareStatement("INSERT INTO graph values(?,?,?,?)");
int cp,ic,rc,fi,ct,tr;
rsfact = psFact.executeQuery(); **// this instantiates ResultSet, if you dont includee this statement rsfact would still be null.**
while(rsfact.next()) // **if rsfact null and u execute this line it would throw nullpointer exception(cuz rsfact is null)**
{
cp=rsfact.getInt("1");
ic=rsfact.getInt("2");
rc=rsfact.getInt("3");
fi=rsfact.getInt("4");
ct=rsfact.getInt("5");
tr=rsfact.getInt("6");
int rfv;
rfv=(cp+ic+rc+fi+ct+tr)/6;
graph.setInt(colCount, rfv);
colCount++;
}
graph.executeUpdate();
Related
Good Day
I am trying to retrieve data from a database into jTable. When the user writes in the textfield the required data it displays it in the table.
What I get is
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
Here is my codes
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/hr","root","MZaa8891#");
String Sql="Select recName,phoneNo,quali,major,Uni,status,IntDate,interviewer from rect ";
ps= con.prepareStatement(Sql);
ps.setString(1, jTextField1.getText());
rs =ps.executeQuery();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.setRowCount(0);
while(rs.next()){
Object obj [] = {
rs.getString("recName"),
rs.getString("phoneNo"),
rs.getString("quali"),
rs.getString("major"),
rs.getString("Uni"),
rs.getString("status"),
rs.getDate("IntDate"),
rs.getString("interviewer")
};
model.addRow(obj);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
Any Ideas?
You have missed some parameter in the where clause:
Query: Select
recName,phoneNo,quali,major,Uni,status,IntDate,interviewer from rect
where something = ?
String Sql="Select recName,phoneNo,quali,major,Uni,status,IntDate,interviewer from rect where something = ?";
ps= con.prepareStatement(Sql);
ps.setString(1, jTextField1.getText());
rs =ps.executeQuery();
Why am I getting a SQLException with my query?
PreparedStatement stmt = con.prepareStatement("SELECT note FROM NOTES4EME WHERE id=?");
stmt.setString(1,"1");
ResultSet a = stmt.executeQuery();
return a.getInt(1);
What am I missing?
I have a method :
public int afficheNote(int id) throws ClassNotFoundException, SQLException {
Class.forName("org.apache.derby.jdbc.ClientDriver");
String url = "jdbc:derby://localhost:1527/TLdb;create=true;user=root;password=root";
Connection con = DriverManager.getConnection(url);
String query = "SELECT NOTES FROM NOTES4EME WHERE ID = '" + id + "'";
//PreparedStatement stmt = con.prepareStatement(query);
PreparedStatement stmt = con.prepareStatement("SELECT note FROM NOTES4EME WHERE id=?");
stmt.setString(1,"1");
ResultSet a = stmt.executeQuery();
if (a.next()) {
return a.getInt(1);
}
return -1;
}
and I call this method in a .JSP :
<%
int a = mybean.afficheNote(1);
%>
Call next before invoking getInt
ResultSet a = stmt.executeQuery();
if (a.next()) {
return a.getInt(1);
} else {
throw new IllegalArgumentException("Nothing found for 1...");
}
The ResultSet Javadoc says (in part) initially the cursor is positioned before the first row. So you need to call next. Add something like
if (a.next()) {
return a.getInt(1);
}
return -1;
The function below will pick the highest value and it will display value which are in column place1(in table placeseen) as output based on the ID.So far I only can get the highest value but not the value in place1.
I don't know what's wrong with my coding because the output is always shows empty.
private void pick_highest_value_here_and_display(ArrayList<Double> value) throws Exception {
// TODO Auto-generated method stub
double aa[]=value.stream().mapToDouble(v -> v.doubleValue()).toArray();
double highest=aa[0+1];
for(int i=0;i<aa.length;i++)
{
if(aa[i]>highest){
highest=aa[i];
String sql ="Select* from placeseen where ID =aa[i]";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
String aaa;
aaa=rs.getString("place1");
System.out.println(aaa);
}
ps.close();
rs.close();
conn.close();
}
}
System.out.println(highest);
}
instead of
String sql ="Select * from placeseen where ID =aa[i]";//aa[i] taking a value
use
String sql ="Select place1 from placeseen where ID =?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, aa[i]);
passing aa[i] variable value .
Avoid sql injection
You can try this
// as you are using preparedStatement you can use ? and then set value for it to prevent sql injection
String sql = "Select * from placeseen where ID = ?";
DatabaseConnection db = new DatabaseConnection();
Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, aa[i]); // 1 represent first attribute represented by ?
System.out.println(ps); // this will print query in console
ResultSet rs = ps.executeQuery();
if (rs.next()) {
System.out.println("Inside rs.next()"); // for debug purpose
String aaa;
aaa=rs.getString("place1");
System.out.println(aaa);
}
// remaining code
I have searched to insert a value from application java into a mysql table.
Following there's my code. The result of it is a long row of error, but the first row is: java.sql.SQLException: Before start of result set
Connection con = null; //oggetto di connessione
try {
Class.forName("com.mysql.jdbc.Driver"); //connessione
con = DriverManager.getConnection("jdbc:mysql://localhost/autonoleggio", "root", "");//connessione vera e propria
//quarto va cambiato col nome del database creato
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM dati"); // persone ->tabella presente nel database
if(targa.getText().equals(rs.getString("Targa")))
{
Statement insideStatement = con.createStatement();
ResultSet insideResultsSet = insideStatement.executeQuery(
"INSERT INTO dati (Cliente) VALUES ('"+inserisci.getText()+"');"
);
/*String query;
query="INSERT INTO dati (Cliente) VALUES ('"+inserisci.getText()+"');";
PreparedStatement statement = con.prepareStatement(query);
statement.executeUpdate();
statement.close(); */
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(con != null) {
con.close();
}
}
The ResultSet object is sort of an iterator on the result returned from the database. Like any iterator, it starts before the first element, and needs to be advanced to point to it. In short, you're missing a call to ResultSet#next():
ResultSet rs = st.executeQuery("SELECT * FROM dati");
if (rs.next() && targa.getText().equals(rs.getString("Targa"))) {
// Here -^
I need a way to view the preparedStatement for debugging here is my java code that I wish to print the preparedStatement to the console for.
public class UnitTestDMUtility_Select {
#Test
public void testQUERY_CHECKBOTHPARTS() throws Exception{
UnitTestHelper helper = new UnitTestHelper();
Connection con = helper.getConnection(helper.sourceDBUrl);
Connection conTarget = helper.getConnection(helper.targetDBUrl);
PreparedStatement stmt = con.prepareStatement(DMUtility.QUERY_CHECKBOTHPARTS);
stmt.setInt(1, 101);
ResultSet sourceVal = stmt.executeQuery();
//Here is the QUERY
//select count(*) from tr_demand where demandtypeid=101
stmt = conTarget.prepareStatement(DMUtility.QUERY_CHECKBOTHPARTS);
stmt.setInt(1, 101);
ResultSet targetVal = stmt.executeQuery();
assertTrue(helper.resultSetsEqual2(sourceVal,targetVal));
}
}
To answer your question, I output my queries to a log file ( and console ) by doing the following:
PreparedStatement stmt = con.prepareStatement(DMUtility.QUERY_CHECKBOTHPARTS);
stmt.setInt(1, 101);
//Write stmt to console:
System.out.println(stmt.toString());
For query debug I usually use the library jamon, it is a JDBC proxy that logs every statement is invoked