This is the code from DBUtil
public class DBUtil {
static Connection conn = null;
public static Connection getConnected() {
try {
Class.forName("org.h2.Driver");
conn = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test", "sa", "");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}//end method
}//end DBUtil
and here is the code from the method I'm trying to use:
private class SearchForEdit implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e) {
String clientNumber = tfieldMiniSearchNumber.getText();
int number;
conn = DBUtil.getConnected();
if(conn == null) return;
String names=null, address=null;
String sql ="select names from clients where client_number = ?;";
String sql2 ="select address from clients where client_number = ?;";
try {
state = conn.prepareStatement(sql);
state.setInt(1, number);
state.execute();
state = conn.prepareStatement(sql2);
state.setInt(1, number);
state.execute();
labelWarning.setForeground(new Color(22, 205, 5));
labelWarning.setText("<html>TEXT SUCCESS</html>");
//names = select names from clients where client_number = number;
//address = select address from clients where client_number = number;
//if(names!=null && address!=null)
//tfieldEditClientNumber to be number
tfieldEditClientNumber.setText(""+number);
//tfieldEditNames to be names, where names = select names from clients where client_number = number;
//tfieldEditAddressда to be address, where address = select address from clients where client_number = number;
} catch (SQLException e1) {
labelWarning.setForeground(Color.RED);
labelWarning.setText("<html>Try again later</html>");
e1.printStackTrace();
}
}
}//end
I want to take the value of column NAME from the database and then put in in the string name. Then the same for address. I know only how to execute statements. Any help is very apreciated!
You need to store the results of the query in a ResultSet, and then iterate over that ResultSet. You can assign the values from the ResultSet into variables as you iterate over them.
Below code is an example of iterating over a ResultSet, as mentioned in my comment below.
while (rs.next()) {
// ResultSet columns: 1 = UserName 2 = FirstName 3 = LastName 4 = Organization
userInfo[0] = rs.getString(1); // assign UserName result to variable
userInfo[1] = rs.getString(2); // assign First_Name result to variable
userInfo[2] = rs.getString(3); // assign Last_Name result to variable
userInfo[3] = rs.getString(4); // assign Organization result to variable
}
The while loop will end when there are no ResultSet rows left to iterate over.
Related
I have code, where I have single quote or APOSTROPHE in my search
I have database which is having test table and in name column of value is "my'test"
When running
SELECT * from test WHERE name = 'my''test';
this works fine
If I use the same in a Java program I am not getting any error or any result
But If I give the name with only single quote then it works
SELECT * from test WHERE name = 'my'test';
Could you please help me out to understand.
Java code is
Connection con = null;
PreparedStatement prSt = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.
getConnection("jdbc:oracle:thin:#localhost:1521:orcl"
,"user","pwd");
String query = "SELECT * from "
+ "WHERE name = ? ";
prSt = con.prepareStatement(query);
String value = "my'mobile";
char content[] = new char[value.length()];
value.getChars(0, value.length(), content, 0);
StringBuffer result = new StringBuffer(content.length + 50);
for (int i = 0; i < content.length; i++) {
if (content[i] == '\'')
{
result.append("\'");
result.append("\'");
}
else
{
result.append(content[i]);
}
}
prSt.setObject(1, result.toString());
int count = prSt.executeUpdate();
System.out.println("===============> "+count);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally{
try{
if(prSt != null) prSt.close();
if(con != null) con.close();
} catch(Exception ex){}
}
You don't have to escape anything for the parameter of a PreparedStatement
Just use:
prSt = con.prepareStatement(query);
prSt.setString("my'mobile");
Additionally: if you are using a SELECT statement to retrieve data, you need to use executeQuery() not executeUpdate()
ResultSet rs = prst.executeQuery();
while (rs.next())
{
// process the result here
}
You might want to go through the JDBC tutorial before you continue with your project: http://docs.oracle.com/javase/tutorial/jdbc/index.html
I can only get results from a SQL query execution when I use select columnname from tablename, but not when I use select * from tablename
public static void connectAndExecute(String host, String uName, String uPass, String sqlQuery) {
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
} catch (SQLException e) {
e.printStackTrace();
}
try {
Connection con=DriverManager.getConnection(host, uName, uPass);
String[] conData = null;
Statement stmt = null;
try {
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sqlQuery);
/*this is the place of my problem*/
}
catch (SQLException e) {
e.printStackTrace();
}
}
catch (SQLException err) {
System.out.println(err.getMessage());
}
}
Use ResultSet.class methods to get the desired result. You can give the column names or column index.
getInt(int columnIndex)
Retrieves the value of the designated column in the current row of
this ResultSet object as an int in the Java programming language.
getString(int columnIndex)
Retrieves the value of the designated column in the current row of
this ResultSet object as a String in the Java programming language.
Here is how you can implement it:
while(rs.next()){
//Retrieve by column index
int id = rs.getInt(1); //assume id is at 1st index
int age = rs.getInt(4); //assume age is at 4th index
String first = rs.getString(2); // assume first name is at 2nd index
String last = rs.getString(3); // assume last name is at 3rd index
//Display values
System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last);
System.out.println(" End of one row");
}
I create this code for get column name in sql databases. But now I ant to modify above code for get all table data with column name. Then get all data and convert to jsonarray and pass. How I modify this code for get all table data with column name.
#Override
public JSONArray getarray(String sheetName) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
con.setAutoCommit(false);
PreparedStatement pstm = null;
Statement stmt = null;
//-----------------------Drop earliye table -------------------------------------------------------------
try {
String sqldrop = "select COLUMN_NAME from information_schema.COLUMNS where TABLE_NAME='" + sheetName.replaceAll(" ", "_") + "'";
System.out.println(sqldrop);
PreparedStatement mypstmt = con.prepareStatement(sqldrop);
ResultSet resultSet = mypstmt.executeQuery();
JSONArray jsonArray = new JSONArray();
while (resultSet.next()) {
int total_rows = resultSet.getMetaData().getColumnCount();
JSONObject obj = new JSONObject();
for (int i = 0; i < total_rows; i++) {
String columnName = resultSet.getMetaData().getColumnLabel(i + 1).toLowerCase();
Object columnValue = resultSet.getObject(i + 1).toString().replaceAll("_", " ");
// if value in DB is null, then we set it to default value
if (columnValue == null) {
columnValue = "null";
}
/*
Next if block is a hack. In case when in db we have values like price and price1 there's a bug in jdbc -
both this names are getting stored as price in ResulSet. Therefore when we store second column value,
we overwrite original value of price. To avoid that, i simply add 1 to be consistent with DB.
*/
if (obj.has(columnName)) {
columnName += "1";
}
obj.put(columnName, columnValue);
}
jsonArray.put(obj);
}
mypstmt.close();
con.commit();
return jsonArray;
} catch (Exception e) {
System.out.println("There is no exist earlyer databases table!..... :( :( :( **************** " + sheetName.replaceAll(" ", "_"));
}
//----------------------------------------------------------------------------
} catch (ClassNotFoundException e) {
System.out.println(e);
} catch (SQLException ex) {
Logger.getLogger(PassArrayDaoImpl.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("%%%%%%%%%%");
return null;
}
My target is get all data with column name and above data pass html page as a json. So if you have any method for get all data with column name is suitable for me.
// code starts here
// This method retrieves all data from a mysql table...
public void retrieveAllData( String host, String user, String pass, String query) {
JTextArea textArea = new JTextArea();
try(
Connection connection = DriverManager.getConnection( host, user, pass )
Statement statement = connection.createStatement()
ResultSet resultSet = statement.executeQuery(query)) {
ResultSetMetaData metaData = resultSet.getMetaData();
int totalColumns = metaData.getColumnCount();
for( int i = 1; i <= totalColumns; i++ ) {
textArea.append( String.format( "%-8s\t", metaData.getColumnName(i) ) );
}
textArea.append( "\n" );
while( resultSet.next() ) {
for( int i = 1; i <= totalColumns; i++ ) {
Object object = resultSet.getObject(i).toString();
textArea.append( String.format("%-8s\t", object) );
}
textArea.append( "\n" );
}
}
}
I want this function to display the highest value and the index in the array.If the index is the highest, it will retrieve all the value in sql. But when I run this program, it displays a lot of values...How to solve it?
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];
System.out.println(highest); // display value in aa[0]
for(int i=1;i<aa.length;i++)
{
if(aa[i]>highest)
{
highest=aa[i];
System.out.println(highest); //print the highest value only
System.out.println(i);
String sql ="Select * from placeseen where ID =?";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setDouble(1, i+1);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
String aaa=rs.getString("place1");
String bbb=rs.getString("place2");
String cc=rs.getString("place3");
String dd=rs.getString("place4");
String ee=rs.getString("place5");
String ff=rs.getString("place6");
String gg=rs.getString("place7");
String hh=rs.getString("place8");
String iii=rs.getString("place9");
String jj=rs.getString("place10");
String kk=rs.getString("place11");
String ll=rs.getString("place12");
String mm=rs.getString("place13");
String nn=rs.getString("place14");
String oo=rs.getString("place15");
String pp=rs.getString("budget");
Tourism to =new Tourism();
to.setPlace1(aaa);
to.setPlace2(bbb);
to.setPlace3(cc);
to.setPlace4(dd);
to.setPlace5(ee);
to.setPlace6(ff);
to.setPlace7(gg);
to.setPlace8(hh);
to.setPlace9(iii);
to.setPlace10(jj);
to.setPlace11(kk);
to.setPlace12(ll);
to.setPlace13(mm);
to.setPlace14(nn);
to.setPlace15(oo);
to.setBudget(pp);
DispDay dc=new DispDay();
dc.setVisible(true);
}
ps.close();
rs.close();
conn.close();
}
else if(highest==aa[0])
{
String sql ="Select * from placeseen where ID =1";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
String aaa=rs.getString("place1");
String bbb=rs.getString("place2");
String cc=rs.getString("place3");
String dd=rs.getString("place4");
String ee=rs.getString("place5");
String ff=rs.getString("place6");
String gg=rs.getString("place7");
String hh=rs.getString("place8");
String iii=rs.getString("place9");
String jj=rs.getString("place10");
String kk=rs.getString("place11");
String ll=rs.getString("place12");
String mm=rs.getString("place13");
String nn=rs.getString("place14");
String oo=rs.getString("place15");
String pp=rs.getString("budget");
Tourism to =new Tourism();
to.setPlace1(aaa);
to.setPlace2(bbb);
to.setPlace3(cc);
to.setPlace4(dd);
to.setPlace5(ee);
to.setPlace6(ff);
to.setPlace7(gg);
to.setPlace8(hh);
to.setPlace9(iii);
to.setPlace10(jj);
to.setPlace11(kk);
to.setPlace12(ll);
to.setPlace13(mm);
to.setPlace14(nn);
to.setPlace15(oo);
to.setBudget(pp);
DispDay dc=new DispDay();
dc.setVisible(true);
}
ps.close();
rs.close();
conn.close();
}
}
Use MAX
Please change your approach, and use the SQL MAX function. Something like,
String sql = "SELECT * FROM placeseen WHERE budget = ("
+ "SELECT MAX(budget) FROM placeseen)";
You could then use something like
int id = rs.getInt("id");
float budget = rs.getFloat("budget");
And I would recommend limiting the columns (if you only want the two) like
String sql = "SELECT id, budget FROM placeseen WHERE budget = ("
+ "SELECT MAX(budget) FROM placeseen)";
Why not use a for (int i = 0; i < array.lenght; i++)?
Store array[i] in a variable, and the actual int found in that index in another variable. Then, when you loop through it more: if (array[i] > biggestInt), store the new index number and new biggest integer in their appropriate variables.
I am currently using these two methods to set certain text fields equal to the row currently selected in the JTable. I run into a problem though when I filter that table. When the data is filtered, the text fields are not populated with the correct data. The fields are being populated with the row data that would be in that place if there was no filter on the table. Anyone have any suggestions or another way I can bind the table fields with the text fields?
private void tblEmployeeMouseClicked(java.awt.event.MouseEvent evt) {
try {
int row = tblEmployee.getSelectedRow();
String Table_click = (tblEmployee.getModel().getValueAt(row, 0).toString());
String sql = "select * from Employee where EmployeeID = " + Table_click + " ";
newDatabase.populateEmployee(sql);
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
}
public void populateEmployee(String sql) throws Exception{
Constructor("newDatabase");
pst = connection.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
if(rs.next()) {
String add1 = rs.getString(1);
NewJFrame.txtEmpID.setText(add1);
String add2 = rs.getString(2);
NewJFrame.txtEmpFN.setText(add2);
String add3 = rs.getString(3);
NewJFrame.txtEmpLN.setText(add3);
String add4 = rs.getString(4);
NewJFrame.txtEmpMI.setText(add4);
String add5 = rs.getString(5);
NewJFrame.txtEmpAddress.setText(add5);
String add6 = rs.getString(6);
NewJFrame.txtEmpState.setText(add6);
String add7 = rs.getString(7);
NewJFrame.txtEmpZIP.setText(add7);
String add8 = rs.getString(8);
NewJFrame.txtEmpDOB.setText(add8);
String add9 = rs.getString(9);
NewJFrame.txtEmpHire.setText(add9);
String add10 = rs.getString(10);
NewJFrame.txtEmpTerm.setText(add10);
String add11 = rs.getString(11);
NewJFrame.txtEmpLic.setText(add11);
String add12 = rs.getString(12);
NewJFrame.txtEmpActive.setText(add12);
String add13 = rs.getString(13);
NewJFrame.txtEmpMan.setText(add13);
String add14 = rs.getString(14);
NewJFrame.txtEmpMod.setText(add14);
}
connection.close();
}