I want to fill the jComboBox with values from database. and these values depend on the text written in the textfield.
eg: if I write a in the texfield, the combobox will have all values starting with a. The values are from a databse
Here's my code:
private void FillCombo(){
String url = "jdbc:mysql://localhost:3306/pharmacy";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "test";
String sql = "select medicinename from medicine where medicinename like '%"+jTextField5.getText()+"%'";
try{
Class.forName(driver).newInstance();
System.out.println("1");
Connection con = (Connection)DriverManager.getConnection(url,user,pass);
System.out.println("Connected");
Statement st=(Statement) con.createStatement();
PreparedStatement pst = con.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while(rs.next()){
String name = rs.getString("medicinename");
jComboBox1.addItem(name);
}
} catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}}
I want not just one caracter eg: if i write a, as, asp it fill aspirine myproblem is that the combobox is already filled. want it empty when i start.
Simply use JComboBox#removeAllItems() to removes all items from the item list on each stroke of any key in the JTextField.
Points to Remember
Don't load driver each time you enter a new character. Move it outside the FillCombo() method.
Use PreparedStatement instead of using single quoted query string that may cause issue. Find a sample on Using Prepared Statements
Don't forget to close the resources such as connection, result set and statement.
Use finally block to handle it or Read more about Java7 -The try-with-resources Statement
Related
This is probably a easy question for you guys but I'm trying to access a variable set by an SQL statement to then be passed into another SQL statement in another class.
The idea is that when the user logs in, I get their StaffID then I want to use that number in another SELECT statement.
I've tried to make the variable public and access it from the other class but it returns empty.
LOGIN CODE:
public static String StaffID;
// SignIn ActionListener
signIn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try{
Class.forName(DRIVER);
// Connection to the Database
con = DriverManager.getConnection(DATABASE_URL,"root","");
// Gets text from textfields and assigns them to variables
s1 = tfUsername.getText();
s2 = tfPassword.getText();
Statement st = con.createStatement();
// SQL Statements
st.executeQuery("SELECT * FROM login WHERE UName= '"+s1+"' and PWord = '"+s2+"'");
// Extracts data from statement to a result set
ResultSet rs = st.getResultSet();
if (rs.next())
{
// Gets text from Textfields and assigns them to variables
StaffID = rs.getString("StaffID");
}
OTHER CLASS:
try{
Class.forName(DRIVER);
// Connection to the Database
con = DriverManager.getConnection(DATABASE_URL,"root","");
signIn sign = new signIn();
//Creates Statement Connection
Statement st = con.createStatement();
// SQL Statements
st.executeQuery("SELECT * FROM rota WHERE StaffID = '"+sign.StaffID+"'");
// Extracts data from statement to a result set
ResultSet rs = st.getResultSet();
if (rs.next()) {
tfRotaTask1.setText(rs.getString("Task1"));
tfRotaTask2.setText(rs.getString("Task2"));
tfRotaTask3.setText(rs.getString("Task3"));
tfRotaTask4.setText(rs.getString("Task4"));
tfRotaTask5.setText(rs.getString("Task5"));
tfRotaTask6.setText(rs.getString("Task6"));
tfRotaTask7.setText(rs.getString("Task7"));
tfRotaTask8.setText(rs.getString("Task8"));
}
else{
//JOptionPane.showMessageDialog(null, "Staff Member Not Found");
}
To put this into context, I'm making a staff managment rota system.
Sorry if my Java seems poor :(
Any help will do.
Ok first thing first, wrap your Queries in One Class for more easy use.
public class QueryUtils
{
public static String staffId(...yourArgs)
{
String staffId = "";
// Make the logic for getting the StringId
return staffId;
}
}
Ok so you can call this query from anywhere in your application. Even from other queries. Use basic OOP and Patter Desings and you will solve this issues.
you don't inti the value of the StaffID until the condition of rs.next() is be true
try to make else statement like this
if (rs.next())
{
// Gets text from Textfields and assigns them to variables
StaffID = rs.getString("StaffID");
}
and then test the value of the StaffID in the other class if it null then you have somthing wrong in the executeQuery
because i don't see any thing wrong in your code
Code snippet:
On a button click, actionevent will be called
public void actionPerformed(ActionEvent e)
{
Function f = new Function();
Function is a nested class which i have used to establish the connection with the database.
The code snippet for function class is also provided in the end.
ResultSet rs = null;
String Cid ="cust_id";
String Pno="cust_phone";
String cat="cust_cat";
String start_date="st_date";
String Adv_amt="adv";
String Adv_end="end_date";
String Address="addr";
t2 is the Textfield name which i have used to get entry of customer name. I want to use this customer name as a PK to fetch all the other data about that customer from DB.
rs=f.find(t2.getText());
try{
if(rs.next())
{
t1.setText(rs.getString("cust_id"));
t3.setText(rs.getString("cust_phone"));
t4.setText(rs.getString("cust_cat"));
t5.setText(rs.getString("st_date"));
t6.setText(rs.getString("adv"));
t7.setText(rs.getString("end_date"));
t8.setText(rs.getString("addr"));
}
else
JOptionPane.showMessageDialog(null,"No data for this name");
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,ex.getMessage());
}
}
Here is the code snippet for nested class Function which is inside the main class:
class Function{
Connection con=null;
ResultSet rs= null;
PreparedStatement ps = null;
public ResultSet find(String s)
{
try
{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con = DriverManager.getConnection("jdbc:oracle:thin:#Localhost:1521:xe","system","qwerty");
ps= con.prepareStatement("Select * from gkkdb where cust_name='?'");
ps.setString(1,s);
rs= ps.executeQuery();
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.getMessage());
}
return rs;
}
}
Please help figure out the problem.
Don't put the parameter placeholder ? in single quotes.
This:
ps = con.prepareStatement("Select * from gkkdb where cust_name='?'");
should be
ps = con.prepareStatement("Select * from gkkdb where cust_name = ?");
The ? is not recognized as a placeholder if you enclose it in single quotes.
Sorting out the bind variable will fix your immediate issue.
You should explicitly specify what columns you want selected and that way you'll only get what you need (someone might add a BLOB column later) and you'll get them in the right order (someone might change the table create script before running on another DB instance, although you are looking up the columns by name, a different order would only impact if you were using positional indexes).
Ditto on the other answer re: bind variables (i.e. no quotes)
Plus, "select * from" is never a good idea, ask your DBA.
Obviously your code is for example, but you should make sure you free up any resources (Connection, Statement, ResultSet) as soon as they are done with. Use Java 7 try-with-resources.
I'm trying to display database item into a JComboBox and this is my code.
public static void checkItemName(){
Connection conn = SQLite.SQLite();
String sql = "select itemname from item";
try{
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
String list = resultSet.getString("itemname");
purcItemName.addItem(list);
conn.close();
}
} catch (SQLException lol){
System.out.println(lol.toString());
}
}
I did declare static JComboBox purcItemName; and purcItemName = new JComboBox();
The method/function will be called then user press login button.
The problem I'm having now is that, it only shows one item while my database has multiple items.
Anyone got an idea why?
Vector v = new Vector();
while (resultSet.next()){
String list = resultSet.getString("itemname");
v.add(list);
}
conn.close();
purcItemName.setModel(new DefaultComboBoxModel(v));
store the data you got from database in a vector object and once that is completed set the vector object in your combobox as a new model. try this one
and don't close the connection inside your loop.
you are closing connection inside resultSet.next() check, put the conn.close() outside, to the end
I have many JTextField objects and I want to read, in one of them, a string that contains apostrophes and then, this It will be saved on a database. The problem is when I try to save this string, because I obtain this error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error
in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near 'k')' at line 1
I put the apostrophe in a JTextField and the "k" letter is in the next JTextField. I can't understand if who can't read this kind of character is the database (I have a database written in SQL and I use MySQL), or the JTextField object. What can I do?
This is the code that save the strings caught from the JTextField objects (I get the strings into another method, simply using the method jTextField.getText();):
public void setNuovaAzienda(){
try {
int contCliente = 0;
Class.forName(NOMEDRIVER); //avvio il driver
conn = DriverManager.getConnection(SERVERURL, USER, PASSWORD);
Statement st = conn.createStatement();
Statement st1 = conn.createStatement();
Statement st2 = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT MAX(IdCliente) FROM cliente");
while (rs.next())
contCliente = rs.getInt(1);
contCliente++;
int showConfirmDialog = JOptionPane.showConfirmDialog(null,"Vuoi confermare l'inserimento del nuovo cliente?", "Conferma Inserimento", JOptionPane.YES_NO_OPTION);
if (showConfirmDialog == 0) {
try {
st1.executeUpdate("INSERT INTO cliente () VALUES ('"+contCliente+"', '"+citta+"', '"+indirizzo+"', '"+nCivico+"', '"+telefono+"')");
st2.executeUpdate("INSERT INTO personagiuridica () VALUES ('"+contCliente+"', '"+partitaIva+"', '"+nomeAzienda+"', '"+ragSociale+"', '"+fax+"')");
ImageIcon icon = new ImageIcon("C:\\Users\\salva\\Documents\\NetBeansProjects\\JavaApplication10\\src\\javaapplication7\\Icons\\icona v.png");
JOptionPane.showMessageDialog(null, "Cliente Inserito", "Conferma Inserimento", JOptionPane.INFORMATION_MESSAGE, icon);
InserisciOrdine linkInserisciOrdine;
linkInserisciOrdine = new InserisciOrdine();
linkInserisciOrdine.setLocationRelativeTo(null);
linkInserisciOrdine.setVisible(true);
dispose();
} catch (SQLException ex) {
Logger.getLogger(NuovaAzienda.class.getName()).log(Level.SEVERE, null, ex);
}
}
conn.close();
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(NuovaAzienda.class.getName()).log(Level.SEVERE, null, ex);
}
}
contCliente, citta, indirizzo, etc. are global variable.
Sounds like you construct your SQL statements as a String, embedding the data directly, like
String dataString = ...; //get value from field
String sql = "INSERT INTO `mytable` (`col`) VALUES ('"+dataString+"')";
This is wrong, since if you have single quote in your string, this will result in invalid statement. Try outputting that string to System.out and executing it in the SQL worksheet, you should see what goes wrong. You should use Prepared Statements instead:
//Assuming you have jdbc Connection named conn
String dataString = ...; //get value from field
PreparedStatement ps = conn.prepareStatement("INSERT INTO `mytable` (`col`) VALUES (?)");
ps.setString(1, dataString);
ps.execute();
ps.close();
It will give you a decent protection against SQL injections as a bonus.
If you are unable to rewrite your code with prepared statements (e.g. legacy third-party API), then you should escape single quotes in your string, by replacing them with two single quotes (' -> '').
UPDATE
Indeed you do construct the statements using concatenation. AVOID THIS, unless you want to get hacked by a random script kiddie one day. Read about SQL injections, there's plenty of info, and they are one of the main vectors of hacker attacks.
I need to assign a string taken by a query from the database to a Jlabel. I tried many methods but failed. How can i do it?
try{
String sql="SELECT MAX(allocationID) FROM allocation where unit='"+ dept + " ' ";
pst=conn.prepareStatement(sql);
String x= (pst.execute());
}
catch(Exception e){
}
Need to study the steps to connect to the database in java First db steps
Get the resultset from the statment by calling ResultSet rs = pst.execute();
Iterate through the list of rows by using the resultset object.
After that assign the value to the JLabel.
You just made several errors in your tiny program, take a look at the code below as an example:
// your way of using prepared statement is wrong.
// use like this
String sql="SELECT MAX(allocationID) FROM allocation where unit=?;";
Connection conn = getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
// assign values to the variables in the query string
ps.setString(1, dept);
// execute the query
ResultSet rst = ps.executeQuery();
// parse the result set to get the value
// You'd better do some check here to ensure you get the right result
rst.next();
String x = rst.getInt(1) + "";
ps.close();
conn.close();
}
Have a look at the article if you are interested:https://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html