Mysql: Get Strings? - java

I try to receive all names out of my database.
I did write this code:
public static String getCmdCommand(int resultCount) throws Exception {
try {
// This will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
connect = DriverManager.getConnection(""+MyBot.mysqlDbPath+"",""+MyBot.mysqlDbUsername+"",""+MyBot.mysqlDbPassword+"");
PreparedStatement zpst=null;
ResultSet zrs=null;
zpst=connect.prepareStatement("SELECT `befehlsname` FROM `eigenebenutzerbefehle`");
zrs=zpst.executeQuery();
if(zrs.next()){
return zrs.getString(resultCount);
}else{
return "-none-";
}
}catch (Exception e) {
throw e;
} finally {
close();
}
}
and i start the method by running a loop:
for(int i = 0; i <= cmdAmount-1; i++){
try {
eebBenutzerBefehl = dao.getCmdCommand(i);
} catch (Exception e) {
e.printStackTrace();
}
}
cmdAmount is a integer with the valuable of the total fields inside the database.
so i.e My database holds name1 name2 name3, is it wrong to call them like this? :
return zrs.getString(resultCount);
which should be:
zrs.getString(0) = name1
zrs.getString(1) = name2
zrs.getString(2) = name3
I always receive java.sql.SQLException: Column Index out of range, perhaps it just continue to check the first entry only in the database :confused:

return zrs.getString(resultCount);
The getString() method should be given the index of the column you want to return which is always going to be the same. You should pass in a constant here such as 0.
Also, you should open the database only once rather than over and over again in that one method by passing in the "connect" variable as a parameter.
Here's what I would do if you are wanting to retrieve the name from each row of the table.
public static ArrayList<String> getCmdCommand(Connection connect) throws Exception {
try {
PreparedStatement zpst=null;
ResultSet zrs=null;
ArrayList<String> names = new ArrayList<String>();
zpst=connect.prepareStatement("SELECT `befehlsname` FROM `eigenebenutzerbefehle`");
zrs=zpst.executeQuery();
// The result set contains all the names retrieved from the call to the database, so
// you just need to iterate through them all and store them in a list.
while(zrs.next()) {
names.add(zrs.getString(0));
}
} catch (Exception e) {
throw e;
} finally {
close();
}
return names;
}
You don't need to tell it how many fields there are because it will figure that out itself.
Class.forName("com.mysql.jdbc.Driver");
Connection connect = DriverManager.getConnection(""+MyBot.mysqlDbPath+"",""+MyBot.mysqlDbUsername+"",""+MyBot.mysqlDbPassword+"");
try {
ArrayList<String> names = dao.getCmdCommand(connect);
} catch (Exception e) {
e.printStackTrace();
}
if(names.size() < 1) {
// " - none - "
}

Related

Java SQL problem executing query through CallableStatement with parameter

I have a problem in a CallableStatement that execute a stored procedure query which accept a parameter.
I have a list of string that contains the query like:
{call query5_immatricolati(?)}
I have a list of string that contains the parameter like
String cds = "L-INF";
I have no SQL syntax error when I run but the result set doesn't have any value.
The expected result of the execution is that i could create an object by receiving data from the result set.
Here is the code:
for (int i = 0; i < INDICATORI.getInstance().getListaIndicatori().size();) {
for (int j = 0; j < INDICATORI.getInstance().getListaQuery().size();) {
if (INDICATORI.getInstance().getListaIndicatori().get(i).equals("iC00a")) {
for (String cds : CDS.getInstance().getCds().values()) {
ArrayList<indicatore> lista = new ArrayList<indicatore>();
String query = INDICATORI.getInstance().getListaQuery().get(j);
try {
CallableStatement cb = DB.getInstance().getConnection().prepareCall(query);
cb.setString(1, cds);
DB.getInstance().setResultSet(cb.executeQuery());
} catch (SQLException e) {
e.printStackTrace();
}
try {
while (DB.getInstance().getResultSet().next()) {
iC00a obj = new iC00a();
obj.setId(counter);
obj.setAnnoIscrizione(DB.getInstance().getResultSet().getString(1));
obj.setIscrittiPrimoAnno(DB.getInstance().getResultSet().getInt(2));
lista.add(obj);
counter++;
}
} catch (SQLException e) {
e.printStackTrace();
}
map.getInstance().getMap().put(INDICATORI.getInstance().getListaIndicatori().get(i)+cds, lista);
counter=0;
}
}
i++;
j++;
}
}
I tried to manually set in cb.setString(1,cds) the value like cb.setString(1,"L-INF") AND IT WORKS !!!
But I can't set manually the parameter, I need to iterate with for each loop each string and dynamically insert as parameter.
Why if I set the parameter manually like a string it works instead if i give a string variable not ?
Could anyone tell me what I'm doing wrong?
After a lot of attempts, I've found the solution.
The problem is in your variable cdsbecause it could have white spaces before or after.
Try:
cb.setString(1,cds.strip());
For me it worked.

Java Null pointer exception [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
We are trying to display information in a textarea from a database table.
public void displayEmployees()
{
String sqlDisplayQuery ="";
sqlDisplayQuery+= "Select * from JAVAUSER.Employee";
System.out.println(sqlDisplayQuery);
Driver.sendDBCommand(sqlDisplayQuery);
try
{
while (dbResults.next())
{
int employeeID= dbResults.getInt(1);
String employeeFName = dbResults.getString(2);
String employeeLName = dbResults.getString(3);
System.out.println("Employee " +employeeID + employeeFName + employeeLName);
txtaOutput.appendText("Employee" +employeeID + employeeFName + employeeLName);
}
}
catch (SQLException e)
{
System.out.println(e.toString());
}
}
public static boolean isNumeric(String string)
{
try
{
double num = Double.parseDouble(string);
}
catch(NumberFormatException e)
{
return false;
}
return true;
}
public static void sendDBCommand(String sqlQuery)
{
String URL = "jdbc:oracle:thin:#localhost:1521:XE";
String userID = "javauser";
String userPASS = "javapass";
OracleDataSource ds;
try
{
ds = new OracleDataSource();
ds.setURL(URL);
dbConn= ds.getConnection(userID, userPASS);
commStmt = dbConn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
dbResults= commStmt.executeQuery(sqlQuery);
}
catch (SQLException e)
{
System.out.println(e.toString());
}
}
We are getting an null pointer exception at the while loop within the try statement. The SQL does not have any errors. Any help would be appreciated
Looks like the dbResults field is static on the Driver class - this could cause serious problems with multi-threading, and does not utilize proper object-orientation - but that's beyond the scope of the question i guess.
Looking at the loop:
int employeeID= dbResults.getInt(1);
This is fine-ish, even though getInt() won't throw an NPE, you might want to check if the value was SQL null with ResultSet.wasNull().
String employeeFName = dbResults.getString(2);
String employeeLName = dbResults.getString(3);
These can be null, but won't throw NPE either.
System.out.println("Employee " +employeeID + employeeFName + employeeLName);
txtaOutput.appendText("Employee" +employeeID + employeeFName + employeeLName);
Here, in both lines, you concat strings that could be null, so these two are potential sources of NullPointerExceptions. I am just wondering if you got line numbers in your stacktrace that could help identifying the exact location...?
If you want to check what can/cannot return null from an SQL ResultSet, check this.

extracting from DB using JDBC and creating array

i'm trying to extract from mysql database, but my code keeps throwing nullpointerexception and think its because no array is beeing created, what am i doing wrong ?
here's the code: -- thanks !
public ArrayList<String> getRow(String quEry, String db){
String url = "jdbc:mysql://localhost:3306/"+db;
try {
conn = DriverManager.getConnection(url, "root", "");
} catch (SQLException e) {
}
try{
query = conn.prepareStatement(quEry);
}catch(Exception e){
}
try {
getRow_Method_Result = query.executeQuery();
} catch (SQLException e) {
}
try{
while(getRow_Method_Result.next()){
row_result.add(getRow_Method_Result.getString(1));
row_result.add(getRow_Method_Result.getString(2));
row_result.add(getRow_Method_Result.getString(3));
row_result.add(getRow_Method_Result.getString(4));
}
}catch(Exception e){
}
return row_result;
}
public static void main(String[] args) {
ConectorBaseDatos OBJ_testGetRowMethod = new ConectorBaseDatos();
ArrayList<String> rowListResult_ofMethos = OBJ_testGetRowMethod.getRow("SELECT * FROM `arbitros`", "fifa");
System.out.println(rowListResult_ofMethos.toString());
}
i have tried to create this as a String[][] array but since this is a little more complicated decided to create it first as an ArrayList then this result insert it into ArrayList<ArrayList<String>> but just STUCK HERE
I will write here, as this may get a little long for comment.
rowListResult_ofMethods being null implies that your call to OBJ_testGetRowMethod.getRow("SELECT * FROMarbitros", "fifa") returned null.
Looking at your public ArrayList<String> getRow(String quEry, String db) method, I do not see where row_result is first initialized.
So, you should find and make sure row_result is initialized somewhere. (Probably something like row_result = new ArrayList<String>() somewhere.)
In addition, you should NEVER (I would say never, may vary for others) do nothing after catching an exception!
Do not do this:
try{
while(getRow_Method_Result.next()){
row_result.add(getRow_Method_Result.getString(1));
row_result.add(getRow_Method_Result.getString(2));
row_result.add(getRow_Method_Result.getString(3));
row_result.add(getRow_Method_Result.getString(4));
}
} catch(Exception e){
//Do not leave this blank!!! you must handle exception here !
// At least do e.printStackTrace(); to see exception during development.
}
As long as connection and query to your database was successful, I'm guessing the above row_result.add(getRow_Method_Result.getString(1)); would have thrown a NullPointerException. But this exception was discarded and no action was taken, as you left that part blank.
Where are you declaring ArrayList<String> row_result?(statically may be)
If you are initializing as ArrayList<String> row_result=null and you don't have any result set return then it will throw you NPE. And if you have result set then NPE will be inside very first line of while. Make sure you are initializing it as ArrayList row_result=new ArrayList();

how to get detail from a prepareCall when it gets a row of an array

I have a program that connects to Db, using prepareCall. there is a function that browse some element from Db. this is part of this function:
Resource f = new Resource();
if (rs.next()) {
f.setAreaSrl(rs.getInt(1));
f.setAreaId(rs.getInt(2));
f.setAreaName(rs.getString(3));
f.setCenterX(rs.getFloat(4));
f.setCenterY(rs.getFloat(5));
f.setCenterZ(rs.getFloat(6));
}
return f;
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "problem in accessing DB");
e.printStackTrace();
return null;
}
and I have the folloing code in java:
Resource mzone = new Resource();
mzone.getOneEntityBase("areasrl=i");
that will give me a row of table. how can i access to them, element by element?
I want to do some calculation by this numbers, so i need to have them separately.
I have found some way to do it, but it doesn't work.
Resource mzone = new ResourceAreaZone();
mzone.getOneEntityBase("areasrl=1");
String name = mzone.getAreaName();
centerX = (int) mzone.getCenterX();

How can I bind an auto incremented column value of a database table to a textbox?

I have a MySql table in which I have a column named payslip_no which is set as an AUTO_INCREMENT. I want to set this auto incremented value to the value of a text box at the time of page load.
Another way is I am trying to increment this number programatically without setting the column as 'AUTO_INCREMENT'. Following is the code:
public void get_payslip_no()
{
int n1 =0;
try
{
rs2=st2.executeQuery("select max(payslip_no) from tbl_add_payroll");
if(rs2.next())
{
n1=rs2.getInt("payslip_no");
n1=n1+1;
String n2 = Integer.toString(n1);
txt_payslip_no.setText(n2);
System.out.println(n2);
}
}//try
catch(SQLException e2)
{
JOptionPane.showMessageDialog(this,"Payroll-Serial no Storing Error!!!","Serial No Error",JOptionPane.INFORMATION_MESSAGE);
}//catch
}
This code is throwing A NullPointerException because the current database is null. How might I resolve this?
You can try this answer..:)
int no=101;
int no1;
try
{
dbStatement = con.createStatement();
dbResult= dbStatement.executeQuery("select payslip_no from tbl_add_payroll ORDER BY payslip_no DESC LIMIT 1");
if(dbResult.next()==false)
{
jTextField3.setText(String.valueOf(no));
}
else
{
dbResult= dbStatement.executeQuery("select payslip_no from tbl_add_payroll ORDER BY payslip_no DESC LIMIT 1");
while(dbResult.next())
{
deptno=dbResult.getInt("payslip_no");
}
no1=deptno+1;
jTextField3.setText(String.valueOf(no1));
}
}catch(Exception E)
{
}

Categories