search in postgreSQL - java

I have been able to link postgresql with java. I want the user to input a name in a text box in java and a search is performed and checks if the name exists in the database.
My code so far:
String hostname=this.hostNameText.getText();
try
{
s = connection.createStatement();
String q="SELECT * FROM hostdetails WHERE \"HOSTNAME\" = "+hostname;
rs = s.executeQuery(q);
}catch(Exception e)
{
System.out.println("Problem in searching the database 1");
}
I am getting problem to link to the table hostdetails. Please note that hostdetails contain a field nammed HOSTNAME(in capital letters). When I run the above code, I get "Problem in searching the database 1"is displayed. Kindly please help me:)

Try using parameterized queries to protect against SQL injection. Use as follows:
String hostname=this.hostNameText.getText();
try
{
String q="SELECT * FROM hostdetails WHERE \"HOSTNAME\" = ?"; //notice change here
//and use params like this
PreparedStatement pStmnt = connection.prepareStatement(q);
pStmnt.setString(1, hostname);
rs = pStmnt.executeQuery(q);
}catch(Exception e)
{
//error handling here
}

Related

Displaying data in JTextfield from two different mysql tables

Cheers everyone, beginner here!.
I'm currently working on a Java application to keep track of the inventory in our warehouse. It's all on localhost until it's finished. I've created two tables in MySQL database: one table shows the article code, location and quantity (VOORRAADSYSTEEM); the other table shows article code and description (STAMDATA).
In my GUI, I've got a JTable which loads data from VOORRAADSYSTEEM, and on mouseclickevent (getSelectedRow) shows the data in the corresponding JTextFields (so far so good). The only field not showing is the description field (which should be read from the STAMDATA table).
I've tried creating a method for this specific part of the program. The method runs a query to the second table using a inner join to the first table. Here's the code below.
private void LoadDescription() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ABEL?zeroDateTimeBehavior=convertToNull", "root", "");
String sql = "SELECT DESCRIPTION FROM VOORRAADSYSTEEM JOIN STAMDATA ON ARTICLECODE = ARTICLENUMBER WHERE ARTICLECODE="+jComboBox1.getSelectedItem();
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
pst.setString(2, sql);
descriptionTxt.setText(rs.getString(sql));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
At this moment I'm not exactly sure how to approach this problem. I'm also going to try using foreign keys. Any help would be appreciated.
There are better ways to handle what you want to do. For instance you could get all the information you need with one query by joining the table on a common column (ARTICLENUMBER and ARTICLECODE) and then display it.
Right now it looks/sounds like you might be trying to get all the information with two queries.
However, there are some errors with your load description method:
private void LoadDescription() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ABEL?zeroDateTimeBehavior=convertToNull", "root", "");
String sql = "SELECT DESCRIPTION FROM VOORRAADSYSTEEM JOIN STAMDATA ON ARTICLECODE = ARTICLENUMBER WHERE ARTICLECODE="+jComboBox1.getSelectedItem();
ResultSet results = conn.createStatment().executeQuery(sql);
if(results.next()) //make sure something was returned to avoid null pointer exception
descriptionTxt.setText(rs.getString("DESCRIPTION"));
else
JOptionPane.showMessageDialog(null, "no results returned");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
This should work a little better for you.

Getting "java.sql.SQLException: Values not bound to statement" exception

I was trying to make a program which consists of connecting an user by a login system with SQL, then if the credentials are good the user is redirected to an another frame.
But I had a problem, I want to have some information in the SQL base, so I have tried to use while loop and it was working, but after I encountered an error :
java.sql.SQLException: Values not bound to statement
See the following code :
String pseudo2 = null;
String rank2 = null;
try {
String searchname2 = "select * from AdminsInfos where pseudo=?";
PreparedStatement name2 = connection.prepareStatement(searchname2);
ResultSet rspseudo2 = name2.executeQuery();;
while (rspseudo2.next())
{
pseudo2 = rspseudo2.getString("Pseudo");
rank2 = rspseudo2.getString("Rank");
}
} catch (Exception e2) {
e2.printStackTrace();
}
JOptionPane.showMessageDialog(null, "Username and password are correct, connection Admin !");
frame.setVisible(false);
new LoginMain().setVisible(true);
LoginMain.usernameField.setText(pseudo2);
LoginMain.ranklabel.setText("Rank : " + rank2);
and you can check the SQL base too by the following picture :
sql base
Can someone help me?
Since you have a bound variable you need to set the value before executing the statement.
for example , if psuedo is of type String then you will be doing something like below.
String searchname2 = "select * from AdminsInfos where pseudo=?";
PreparedStatement name2 = connection.prepareStatement(searchname2);
name2.setString(1,"value");
ResultSet rspseudo2 = name2.executeQuery();
where first parameter in the setString means you want to set the first value for the bound variable.

2 SQL queries in one try/catch. Not working

Basically, I have to show a list with the data from a database table [that part is working] and afterwards I have to show the highest Date [a date variable in the table]. The second part is not working no matter what I do.
Here's the code
try {
String SQL = "SELECT * FROM tb_rafael";
ResultSet rs = BD.consultar(SQL);
String tab = "";
int numReg = 0;
while (rs.next()) {
tab+="<TR>";
tab+="<TD>" + rs.getString("nme_rafael") + "</TD>";
tab+="<TD>" + rs.getString("dta_rafael") + "</TD>";
tab+="</TR>";
numReg++;
//mDat = rs2.getString("dta_rafael");
}
rs.close();
dados.put("DADOS", tab);
dados.put("NUM_REG", String.valueOf(numReg));
//Pegar Data Maior
String SQL2 = "SELECT MAX(dta_rafael) FROM tb_rafael";
ResultSet rs2 = BD.consultar(SQL2);
String mDat = "";
//while(rs2.next()){
mDat = rs2.getString("dta_rafael");
//}
rs2.close();
dados.put("MDA", mDat);
} catch (Exception ex) {
dados.put("MSG", "Erro: " + ex.getMessage());
}
What you want to look at is past the commentary line "Pegar Data Maior". That's the part that is not working. I've tried adding a while, using a different ResultSet, using the same ResultSet and none of those worked. I know it's not an issue with the SQL query since I tested it with the workbench and it returned me the data I want.
To be more specific, I don't get an error message or anything, the dados.put simply does not work and I get just this:
How the HTML code looks:
The data should show up where the {MDA} is. Anyone have any ideas?
The query SELECT MAX(dta_rafael) FROM tb_rafael may not return a column name, which you later try to retrieve, rs2.getString("dta_rafael");
I'd change the query to SELECT MAX(dta_rafael) AS Max_date..., and reference to MAX_date thereafter.

How to perform a search in an SQL database with a java application?

I'm planning to build a very very simple java application done on Netbeans that accepts basic individual information like ID number, name, and address and stores it on an sql database.
I want to put a search function on my program that accepts ID numbers. When the user inputs the ID number that is stored in the database, it will show the Name and address on a pop up message dialog.
I know this is possible but can you link me to some guides or documentations about the search function? or maybe you could give me a very short example of a sample code done in the search button?
Have a look at this link
It is using classes such as Connection and PreparedStatement
Pseudo-code being
String selectSQL = "SELECT USER_ID, USERNAME FROM DBUSER WHERE USER_ID = ?";
dbConnection = getDBConnection();
preparedStatement = dbConnection.prepareStatement(selectSQL);
preparedStatement.setInt(1, 1001);
// execute select SQL stetement
ResultSet rs = preparedStatement.executeQuery();
try {
while (rs.next()) {
String userid = rs.getString("USER_ID");
String username = rs.getString("USERNAME");
System.out.println("userid : " + userid);
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
preparedStatement.close();
dbConnection.close();
}
http://docs.oracle.com/javase/tutorial/jdbc/basics/
Look into how to use JDBC.
A very basic example:
Connection c = null; //need to initialize a java.sql.Connection from JDBC.
String sql = "SELECT * FROM Users WHERE name = ?";
PreparedStatement ps = c.prepareStatement(sql);
ps.setString(1, "John Smith");
ResultSet rs = ps.executeQuery();
List<String> matchingNames = new ArrayList<>();
while (rs.next())
{
String name = rs.getString("name");
matchingNames.add(name);
}
for (String name: matchingNames)
{
//Display dialog.
}
This link is a very good JDBC tutorial. JDBC is the way that java uses database, but this is so basic that almost no real project use JDBC directly.
If you want to learn more, try MyBatis and Hibernate which are the most popular ORM framework, and both of them are based on JDBC.
PS. http://www.mkyong.com/ this site has many good tutorials for Java developer

Loading entries from MySQL into Java table based on search field

I have a MySQL table with entries already in it and I have it connected to my Java program so it displays the table values whenever the program is run. I'm basically trying to implement a search field where the user can type any attribute's value and all the entries that match that value will be loaded into the table. Then the user will be able to select the right entry that matches and they can edit, or update that entry's information. This would be useful for me particularly when you have entries that have the same value, for instance first name, last name, or zip code.
try {
String sql = "SELECT * FROM donors WHERE donor_id = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, txtSearch1.getText());
rs = ps.executeQuery();
tblDonors.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
try {
String sql = "SELECT * FROM donors WHERE first_name = ?";
ps = conn.prepareStatement(sql);
ps.setString(1, txtSearch1.getText());
rs = ps.executeQuery();
tblDonors.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
The search field only searches for the second query, but not the first, so I can type a name and the matching names will load into the table, but when I try to input an id number, nothing happens. I'm fairly new to this, but I think it has something to do with my resultset object? Not exactly sure though. Any help would be great.
What happens here is that the second result overwrites the first. I think the easiest solution is to use or in the where clause, like this:
String sql = "SELECT * FROM donors WHERE (donor_id = ?) or (first_name = ?)";
ps.setString(1, txtSearch1.getText());
// but of course there are 2 ?'s now, we have to give the value to the second one
// as well
ps.setString(2, txtSearch1.getText());
Due to the way placeholders work in JDBC you'll have to provide a value for each ?.

Categories