Lets say I have this table:
CREATE TABLE T (col varbinary(100));
Now I would like to do a "LIKE" query on this column using java, something like this -
String query="SELECT * from T WHERE col LIKE ?";
PreparedStatement st = connection.prepareStatement(query); // Assuming I already have connection object
byte[] prefixBytes = somePrefixBytesIWouldLikeToSearchFor;
String likeString = new String(bytes) + "%";
st.setString(1, likeString);
st.executeQuery();
Is that right way to go about it? If not, what is the correct way. Thanks.
You could use string concat inside sql command eg:
String query="SELECT * from T WHERE col LIKE concat(?, '%')";
PreparedStatement st = connection.prepareStatement(query); // Assuming I already have connection object
byte[] prefixBytes = somePrefixBytesIWouldLikeToSearchFor;
String likeString = new String(bytes)
st.setBytes(1, bytes);
st.executeQuery();
Related
My Jtable is connected to the database that I made so that it can show all the data right in my GUI. But Im trying to fetch the data from my JTable to the JTextField. Its like when you click the row of the table the data from the database thats inside the table will go to the TextField. But when I clicked the table it shows an error like this:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near 'NO.='1
RASCHEL" at line 1
I've been searching for the answer but I was unable to find one. Please help me I've been stuck to this error since friday.
table = new JTable();
scrollPane.setViewportView(table);
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
int row = table.getSelectedRow();
String table_click = (table.getModel().getValueAt(row, 0).toString());
try {
String query = "SELECT * FROM `raschel` where MACHINE NO.='" + table_click + "'";
Connection con;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
String machine = rs.getString("MACHINE NO.");
String type = rs.getString("TYPE");
String product = rs.getString("PRODUCT");
txtMachine.setText(machine);
txtType.setText(type);
txtProd.setText(product);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
});
The column you are using MACHINE NO. contains a space and a dot in the end to work with like names you have to put the name between two :
`MACHINE NO.`
So your query should look like this :
String query = "SELECT * FROM `raschel` where `MACHINE NO.`='" + table_click + "'";
But this still not secure agains syntax error or SQL Injection so instead you can use :
String query = "SELECT * FROM `raschel` where `MACHINE NO.` = ?";
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root","");
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, table_click);//<<-----------set the parameter like this
ResultSet rs = ps.executeQuery();
You sould not use blanks and dots in column names. If you have to use blank and dot you have to escape the column name with a backtick:
String query = "SELECT * FROM `raschel` where `MACHINE NO.`='"+table_click+"'";
But i would strongly recommand to not use blanks and dots (or other special character) in column or table names.
String query = "SELECT * FROM `raschel` where MACHINENO='"+table_click+"'";
Also change to prepared statements to prevent SQL injection
Try this on your
String query = "SELECT * FROM `raschel` where `MACHINE NO.`='"+table_click+"'";
I have asked this beacause i was not able to find the answer.
what i am doing is
String selectTableSQL = "SELECT * FROM diseaseinfo WHERE diseaseName =""+diseaseName +'" AND name = '"+username+"'";
it is perfecty running unless and until diseases does not contain 's type of word like
Wilms' tumor
Addison's disease
etc....
so query like
SELECT * FROM diseaseinfo WHERE diseaseName = 'Adult Still's disease' AND name = 'add';
wont execute because of ' 's on 'Adult Still's
and also in java i cant start string with String selectTableSQL = ' '; it will always be in String selectTableSQL = " ";
any solution?
To avoid this case and any syntax error or SQL Injection you have to use PreparedStatement instead :
String selectTableSQL = "SELECT * FROM diseaseinfo WHERE col1 = ? and col2 = ?";
try (PreparedStatement ps = connection.prepareStatement(selectTableSQL)) {
ps.setString(1, value_1);
ps.setString(2, value_2);
ResultSet rs = ps.executeQuery();
while(rs.next()){
//...
}
}
The correct way to use queries in JDBC is to use PreparedStatement and bind variables.
But in your case, try replacing the single quotes ' in your values with \'.
You can use a simple diseaseName.replace("'", "\\'"); to do it.
Can anyone tell me how I can compare two resultset values? Only getting error in if statement, but the rest is working.
Statement s = con.createStatement();
Statement stmnt = con.createStatement();
String query = "select * from tbl_product";
s.execute(query);
ResultSet rs = s.getResultSet();
while(rs.next())
{
String strOuter=rs.getString(2);
System.out.println(strOuter);
String query1 = "select * from PRODUCTS_AJ";
stmnt.execute(query1);
ResultSet rs1 = stmnt.getResultSet();
while(rs1.next())
{
System.out.println("-------"+rs1.getString(2));
if(rs.getString(2).equals(rs1.getString(2)))// Getting Error here for this line
{
System.out.println("Found");
}
}
}
java.sql.Exception data not found
This types of error occurs when you try to read same column of the same cursor multiple times. And what you encountered is a typical scenario. Just store the string temporarily like bellow:
String col3 = rs1.getString(2);
and use col3 instead of rs1.getString(2), whenever needed.
System.out.println("-------"+ col3);
if(col3.equals(rs1.getString(2)))
{
...
You cannot re-read a column value again. So, copy it in a local variable for logging.
String val = rs1.getString(2);
System.out.println("-------" + val);
if (rs.getString(2).equals(val)) {
What you could possibly do is
use SQL where clause
String query1 = "select * from PRODUCTS_AJ where fieldNmae = 'something'";
ResultSetMetaData rsm = rs.getMetaData();
int colCount = rsm.getColumnCount();
if (colCount > 1)
{
// found
}
For ResultSetMetaData
or possibly do
ResultSet rsOLD = null;
ResultSet rs = s.getResultSet();
// rs will be new ResultSet
while(condition)
{
// check from second row (maintain if case)
.
.
.
// end of loop
rsOLD = rs;
}
Ok ! This is a typical error while using JDBC-ODBC bridge driver with MS Access. I have experienced.I solved it in following way. Retrieving the same data more than once from the result set.
Please try like this
ResultSet rs = s.getResultSet();
String str=rs.getString(2);
Use this string to compare
str.equals(rs2.getString(2)
Thanks!
rs.getSting(2) is executed the number of row times of rs1 in the while loop of rs1. You may not have the that many number of rows in rs as rs1.
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 get a parameter is called 'id' in my function and want to print the cell of the name of this id row.
for example:
this is my table:
id name email
1 alon alon#gmail.com
I send to my function: func(1), so I want it to print 'alon'.
this is what I tried:
static final String url = "jdbc:mysql://localhost:3306/database_alon";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "Admin");
String query_txt = "SELECT * FROM authors WHERE id = " + id;
Statement ps2 = con.createStatement();
ResultSet my_rs = ps2.executeQuery(query_txt);
System.out.println(my_rs.getString("name"));
con.close;
Everything is fine, but just one problem. You need to move your ResultSet cursor to the first row before fetching any values: -
Use: -
ResultSet my_rs = ps2.executeQuery(query_txt);
while (my_rs.next()) {
System.out.println(my_rs.getString("name"));
}
As a side note, consider using PreparedStatement to avoid getting attacked by SQL Injection.
Here's how you use it: -
PreparedStatement ps2 = con.prepareStatement("SELECT * FROM authors WHERE id = ?");
ps2.setInt(1, id);
ResultSet my_rs = ps2.executeQuery();
while (my_rs.next()) {
System.out.println(my_rs.getString("name"));
}
You need to use ResultSet.next() to navigate into the returned data:
if (my_rs.next()) {
System.out.println(my_rs.getString("name"));
}
Call my_rs.next(), which will move the ResultSet cursor onto the first row (which you are extracting data out of).
If this is a real application, use PreparedStatements instead of generic Statements. This is an extremely important matter of security if you plan on using user input in SQL queries.