Firstly, I'm reading the product name and number of products from user using jTextFields. For that product I read the product id and price from database using sql query. But in the below code I display the product price in a jtextField but while running tha file I get query executed successfully but I'm not getting anything in the jtextField.
And please check the sql query and resultset use,
table name is "item" and database name is "myshop",
I declared variables globelly and this code is in a jButton's 'ActionPeformed" part.
String item_name=name.getText();
int item_no=Integer.parseInt(no.getText());
String sql="SELECT id,price FROM item WHERE item.name='item_name'";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con(Connection)DriverManager.getConnection("jdbc:mysql://localhost:3306/myshop","root","mysql");
java.sql.Statement stmt=con.createStatement();
if (stmt.execute(sql)) {
rs = stmt.getResultSet();
JOptionPane.showMessageDialog(this, "succes","executed query",JOptionPane.PLAIN_MESSAGE);
} else {
System.err.println("select failed");}
int idIndex = rs.findColumn("id");
int priceIndex = rs.findColumn("price");
while(rs.next()){
item_id=rs.getInt(idIndex);
item_price=rs.getInt(priceIndex);
jTextField1.setText(""+item_price);//displaying product price in a jTextField1
jTextField2.setText(""+item_id);//displaying product id in a jTextField2
}
}
catch(Exception e){
JOptionPane.showMessageDialog(this, e.getMessage());
}
This line should be
String sql="SELECT id,price FROM item WHERE item.name='item_name'";
like this
String sql="SELECT id,price FROM item WHERE item.name='"+item_name+"'";
Use a PreparedStatement so you don't have to worry about delimiting all the variables:
String sql="SELECT id, price FROM item WHERE item.name = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, item_name);
ResultSet rs = stmt.executeQuery();
Then the prepared statement will replace the variable for you with the proper quotes.
you would need to take item_name as param and put in quotes,
String sql="SELECT id,price FROM item WHERE item.name='"+ item_name+"'";
Try to avoid this type of mistake by using PreparedStatement
String sql="SELECT id,price FROM item WHERE item.name=?";
PreapredStatement ps = con.prepareStatement(sql);
ps.setString(1,item_name);
ResultSet rs = ps.executeQuery();
Use of PreparedStatement also prevent SQL injection attack.
try this code .
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/myshop","root","mysql");
PreparedStatement pt=con.prepareStatement("SELECT id,price FROM item WHERE item.name=?");
pt.setString(1,"item_name");
ResultSet rs;
if(pt.execute())
{
rs=pt.getResultSet();
JOptionPane.showMessageDialog(this, "succes","executed query",JOptionPane.PLAIN_MESSAGE);
}
else {
System.err.println("select failed");
}
while(rs.next()){
item_id=rs.getInt(1);
item_price=rs.getInt(2);
jTextField1.setText(""+item_price);//displaying product price in a jTextField1
jTextField2.setText(""+item_id);//displaying product id in a jTextField2
}
First, you need an reader, like this
private static void reader() throws SQLException {
DataBaseName db = new DataBaseName ();
names = db.getNames();
}
Related
I have sql query which is shown below its a select statement I want to pass dynamically the values but I am not aware how can we do it .here I want to pass product and location dynamically
can anyone help in this ..
public static ResultSet RetrieveData() throws Exception {
PreparedStatement statement;
String sql = "select * FROM Courses WHERE "
+ "product = product? "
+ "and location = location? ";
System.out.println(sql);
DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
String mysqlUrl = "jdbc:mysql://localhost:3306/wave1_build";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "root");
statement = con.prepareStatement(sql);
ResultSet rs = statement.executeQuery(sql);
return rs;
One approach is to use plain ? placeholders along with the appropriate setters to bind values:
String sql = "SELECT * FROM Courses WHERE product = ? AND location = ?";
statement = con.prepareStatement(sql);
statement.setString(1, "some product");
statement.setString(2, "some location");
// NOTE: executeQuery() when used with prepared statements does NOT take any parameters
ResultSet rs = statement.executeQuery();
When I debug, I get this error :
Column 'place1' not found.
I was able to verify that it has column place1 in sql.
Is it because I can not have two database connection in one function? I am unsure on how to further debug the problem.
Case.java
System.out.println("The highest value is "+highest+"");
System.out.println("It is found at index "+highestIndex+""); // until now it works fine
String sql ="Select Day from menu where ID =?";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, highestIndex);
ResultSet rs = ps.executeQuery();
if (rs.next())
{
int kb=rs.getInt("Day");
System.out.println(kb);
if(kb==k) // k is a value getting from comboBox
{
String sql1 ="Select * from placeseen where ID =?";
DatabaseConnection db1 = new DatabaseConnection();
Connection conn1 =db1.getConnection();
PreparedStatement ps1 = conn.prepareStatement(sql);
ps.setInt(1, highestIndex);
ResultSet rs1 = ps.executeQuery();
if (rs1.next())
{
String aaa=rs1.getString("place1");
String bbb=rs1.getString("place2");
Tourism to =new Tourism();
to.setPlace1(aaa);
to.setPlace2(bbb);
DispDay dc=new DispDay();
}
ps1.close();
rs1.close();
conn1.close();
}
else
{
System.out.print("N");
System.out.println("Sorry!!!");
}
}
ps.close();
rs.close();
conn.close();
Trace your code to see where you're getting the data. The error is on this line:
String aaa=rs1.getString("place1");
Where does rs1 come from?:
ResultSet rs1 = ps.executeQuery();
Where does ps come from?:
PreparedStatement ps = conn.prepareStatement(sql);
Where does sql come from?:
String sql ="Select Day from menu where ID =?";
There's no column being selected called place1. This query is only selecting a single column called Day.
Maybe you meant to get the result from the second prepared statement?:
ResultSet rs1 = ps1.executeQuery();
There are probably more such errors. Perhaps several (or many) more. Because...
Hint: Using meaningful variable names will make your code a lot easier to follow. ps, ps1, rs1, etc. are very easy to confuse. Name variables by the things they conceptually represent and your code starts to read like a story which can be followed. Variable names like daysQuery and daysResults and placesResults make it more obvious that something is wrong when you try to find a "place" in a variable which represents "days".
In your second query:
PreparedStatement ps1 = conn.prepareStatement(sql);
you are accidentally using the variable sql instead of your previously defined sql1. Replace it and it will be ok.
I am implementing a search method, i want to search a data in a Jtable ( wich contains 2 columns id and name) based in id and name both. Till now I can search using just one of, id or name but cannot do that using them both. I tried a solution, but it is not working it just search for the last one ( id or name). For example if i start with try and catch by name and then id, it only goes with id search. And if I start with id and the name, it searches just by name. Can u help me please.
The code :
`private void textField1KeyReleased(java.awt.event.KeyEvent evt) {
PreparedStatement pst=null;
ResultSet rs=null;
if (textField1.getText().length() > 0){
try{
String sql = "select * from compte_utilisateur where nom=?";
pst=maConnexion.ObtenirConnexion().prepareStatement(sql);
pst.setString(1, textField1.getText());
rs=pst.executeQuery();
TableUtilisateur.setModel(DbUtils.resultSetToTableModel(rs));}
**catch(Exception e){JOptionPane.showMessageDialog(null, e);}
try{
String sql = "select * from compte_utilisateur where id_utilisateur=?";
pst=maConnexion.ObtenirConnexion().prepareStatement(sql);
pst.setString(1, textField1.getText());
rs=pst.executeQuery();
TableUtilisateur.setModel(DbUtils.resultSetToTableModel(rs));}
catch(Exception e){JOptionPane.showMessageDialog(null, e);}
}
else update_table();
}`**
Use just one SQL call passing the same value from the field twice
select * from compte_utilisateur where nom=? or id_utilisateur=?
You should to add jar/folder this rs2xml.jar in your project
String sql="Select * From Inventarizimi where Regjistrimi=?";
Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con= (Connection) DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","Inventarizimi"); PreparedStatement preStatement = con.prepareStatement(sql); preStatement.setString(1, txtRegjistrimi.getText());
ResultSet result = preStatement.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(result));
I have been searching and trying different stuff for awhile, but have not found an answer. I'm trying to make a connection to sql using JDBC from eclipse. I am having trouble when I need to select a string in the database. If I use:
Select name from data where title = 'mr';
That works with terminal/command line but when I try to use eclipse where I use
statement sp = connection.createstatement();
resultset rs = sp.executequery("select name from data where title = '" + "mr" + "'");
It does not give me anything while the terminal input does. What did I do wrong in the eclipse? Thanks
Heres a part of the code. Sorry, its a bit messy, been trying different things.
private boolean loginChecker(String cid, String password) throws SQLException{
boolean check = false;
PreparedStatement pstatment = null;
Statement stmt = null;
//String query = "SELECT 'cat' FROM customer";
String query = "select '"+cid+"' from customer where password = '"+password+"'";
try {
System.out.println("in try......");
//stmt = con.createStatement();
//ResultSet rs = stmt.executeQuery(query);
PreparedStatement prepStmt = con.prepareStatement(query);
ResultSet rs = prepStmt.executeQuery();
//System.out.print(rs.getString("cid"));
while(rs.next()){
check = true;
System.out.print(rs.getString("cid"));
}
} catch (SQLException e ) {
e.printStackTrace();
} finally {
if (stmt != null) {
//stmt.close();
}
}
return check;
}
Second try on a simpler query:
public List<Object> showTable() {
List<Object> result = new ArrayList<Object>();
String name = "bob";
try
{
PreparedStatement preStatement = con.prepareStatement("select total from test where name = ?");
preStatement.setString(1, name);
ResultSet rs1 = preStatement.executeQuery();
while(rs1.next()){
System.out.println("there");
System.out.println(rs1.getInt("total"));
}
}
catch (SQLException ex)
{
System.out.print("Message: " + ex.getMessage());
}
return result;
}
Remove the quotes around the column name.
String query = "select "+cid+" from customer where password = '"+password+"'";
You've not mentioned which database you're working with but many databases like Oracle change the column case to upper case unless they're quoted. So, you only quote table columns if that's how you had created them. For example, if you had created a table like
CREATE TABLE some_table ( 'DoNotChangeToUpperCase' VARCHAR2 );
Then you would have to select the column with quotes as well
SELECT 'DoNotChangeToUpperCase' FROM some_table
But, if you didn't create the table using quotes you shouldn't be using them with your SELECTs either.
Make sure you are not closing the ResultSet before you are trying to use it. This can happen when you return a ResultSet and try to use it elsewhere. If you want to return the data like this, use CachedRowSet:
CachedRowSet crs = new CachedRowSetImpl();
crs.populate(ResultSet);
CachedRowSet is "special in that it can operate without being connected to its data source, that is, it is a disconnected RowSet object"
Edit: Saw you posted code so I thought I add some thoughts. If that is your ACTUAL code than the reason you are not getting anything is because the query is probably not returning anything.
String query = "select '"+cid+"' from customer where password = '"+password+"'";
This is wrong, for two reasons. 1) If you are using prepared statements you should replace all input with '?' so it should look like the following:
String query = "select name from customer where password = ?";
Then:
PreparedStatement prepStmt = con.prepareStatement(query);
prepStmt.setString(1, password);
ResultSet rs = prepStmt.executeQuery();
2)
System.out.print(rs.getString("cid"));
Here are are trying to get the column named "cid", when it should be the name stored in cid. You should actually never be letting the user decide what columns to get, this should be hardcoded in.
I'm trying to make my validation class for my program. I already establish the connection to the MySQL database and I already inserted rows into the table. The table consists of firstName, lastName and userID fields. Now I want to select a specific row on the database through my parameter of my constructor.
import java.sql.*;
import java.sql.PreparedStatement;
import java.sql.Connection;
public class Validation {
private PreparedStatement statement;
private Connection con;
private String x, y;
public Validation(String userID) {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test", "root", "");
statement = con.prepareStatement(
"SELECT * from employee WHERE userID = " + "''" + userID);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
x = rs.getString(1);
System.out.print(x);
System.out.print(" ");
y = rs.getString(2);
System.out.println(y);
}
} catch (Exception ex) {
System.out.println(ex);
}
}
}
But it doesn't seem work.
You should use the setString() method to set the userID. This both ensures that the statement is formatted properly, and prevents SQL injection:
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
There is a nice tutorial on how to use PreparedStatements properly in the Java Tutorials.
If you are using prepared statement, you should use it like this:
"SELECT * from employee WHERE userID = ?"
Then use:
statement.setString(1, userID);
? will be replaced in your query with the user ID passed into setString method.
Take a look here how to use PreparedStatement.
There is a problem in your query..
statement =con.prepareStatement("SELECT * from employee WHERE userID = "+"''"+userID);
ResultSet rs = statement.executeQuery();
You are using Prepare Statement.. So you need to set your parameter using statement.setInt() or statement.setString() depending upon what is the type of your userId
Replace it with: -
statement =con.prepareStatement("SELECT * from employee WHERE userID = :userId");
statement.setString(userId, userID);
ResultSet rs = statement.executeQuery();
Or, you can use ? in place of named value - :userId..
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
Do something like this, which also prevents SQL injection attacks
statement = con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();
You can use '?' to set custom parameters in string using PreparedStatments.
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
ResultSet rs = statement.executeQuery();
If you directly pass userID in query as you are doing then it may get attacked by SQL INJECTION Attack.