Using two LIKE's in different columnName? - java

I'm trying to make a search function in JTable in my program, but i got sql syntax error when i use this syntax. I've been read much question and answer in this problem and i never got the right syntax. Hope you can help me.
private void fillTable(String keyword) throws SQLException{
if (!keyword.equals("")){
try( Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/inventory?zero"
+ "DateTimeBehavior=convertToNull","root","");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM basis"
+ "WHERE barcode LIKE '%"+keyword+"%' or "
+ "namaProduk LIKE '% "+keyword+" %'");
){
jTable1.setModel(buildTableModel(rs));
}
}
else fillTable();
}

You are missing 1 space between basis and WHERE (reason for the syntax error).
There is 1 unwanted space between % and your keyword (makes your query irrelevant).
private void fillTable(String keyword) throws SQLException{
if (!keyword.equals("")){
try( Connection con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/inventory?zero"
+ "DateTimeBehavior=convertToNull","root","");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM basis "
+ "WHERE barcode LIKE '%"+keyword+"%' or "
+ "namaProduk LIKE '%"+keyword+" %'");
){
jTable1.setModel(buildTableModel(rs));
}
}
else fillTable();
}

What I can see here is that there's a space missing behind the table name "basis". Generally, you should test your SQL statements manually via an existing DB client and then copy them into your code.
If you're open to tools that will ease your pain, try QueryDSL.

Related

How can I only get 1 element from a SQL Database?

I have a small problem. I wrote a method in which I have an SQL query that should output a correct string after 2 parameters. When debugging, however, the result is not the right element. I don't know why this happens.
public static String findRightTemplate(String user_name, int template_id)
throws Exception {
Connection conn = DriverManager.getConnection(
"xxx", "xxx", "xxx");
Statement st = conn.createStatement();
st = conn.createStatement();
ResultSet rs = st.executeQuery(
"SELECT template FROM templates " +
"where template_id=template_id AND user_name=user_name"
);
String temp="";
while(rs.next())
{
temp=rs.getString("template");
}
rs.close();
st.close();
conn.close();
I ask for the username and template_id and I just want to get an element out of the template column.
The SQL query is correct. I've already tested that. But it seems that the query runs through all elements with the same username. As a result, I only get the last element and not the right one.
UPDATE
Currently you do not use the method parameters inside your query. As already suggested you should use a PreparedStatement to fix that. You should basically do the following:
public static String findRightTemplate(String userName, int templateId) throws SQLException {
try (final Connection connection = DriverManager.getConnection("...")) {
final PreparedStatement preparedStatement = connection.prepareStatement(
"SELECT template " +
"FROM templates " +
"WHERE user_name = ? " +
"AND template_id = ? " +
"LIMIT 1"
);
preparedStatement.setString(1, userName);
preparedStatement.setInt(2, templateId);
final ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) {
return resultSet.getString(1);
}
}
return null;
}
If you do not use a PreparedStatement and build the query manually as suggested in the comments your application could be vulnerable to SQL injection attacks.

SQL command from eclipse using JDBC

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.

ResultSet.next() Throwing SQLException: Result Set Closed

I've tried to debug the code and read the Oracle doc and I don't see any reason why the result set would be closed.
Statement statement = DatabaseConnector.connect();
String sql = "Select * from Room where Room_Type like '*"+roomType+"*' "+availability;
boolean foundResults = statement.execute(sql);
if(foundResults){
ResultSet rs = statement.getResultSet();
StringBuilder row = new StringBuilder();
if(rs!=null){
while(rs.next()){
RE: SQLException
I'm not quite sure what DatabaseConnector is supposed to do in the question code, but the following test code works for me.
RE: Wildcard character
When using the LIKE operator in a query from within the Access application itself then the asterisk * is the wildcard character to use. When querying an ACE (Access) database from some other application one needs to use the "standard" percent % wildcard character. Note that the following code uses %; using * won't work here.
import java.sql.*;
public class JDBCQuery {
public static void main( String args[] )
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection(
"jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};" +
"Dbq=C:\\Users\\Public\\Database1.accdb;");
String RoomTypeToMatch = "suite";
PreparedStatement s = conn.prepareStatement(
"SELECT Room_No, Room_Type " +
"FROM Room WHERE Room_Type LIKE ?"
);
s.setString(1, "%" + RoomTypeToMatch + "%");
s.execute();
ResultSet rs = s.getResultSet();
if (rs!=null)
{
while (rs.next())
{
System.out.println("[Room_No]: " + rs.getString(1) +
", [Room_Type]: " + rs.getString(2));
}
}
s.close();
conn.close();
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
SQL LIKE wildcard charcaters are represented as % not *
String sql =
"Select * from Room where Room_Type like '%"+roomType+ "%' "+availability;
Aside: Always use a PreparedStatement to project against SQL Injection attacks

Java MYSQL Nullpointerexception

Hey guys i'm trying to connect to my database and run a query. it all works apart from the query execution (after narrowing it down i found it to be this) Below i my code:
Statement statement = null;
ResultSet result;
result = statement.executeQuery(query);//this is where error is being caused
while(result.next())
{
Print("ID: " + result.getString("id"));
Print("USER: " + result.getString("username"));
Print("PASS: " + result.getString("password"));
}
I get this returned:
database!java.lang.NullPointerException
Thanks for any help you give me
The query looks right. Surely the statement variable is NULL and you are trying to call executeQuery.
UPDATE:
Try this:
Statement statement = conn.createStatement ();
where conn is a Connection object. I'm sure you have one of those objects somewhere in your code.
Fixed my problem by using a prepared statement:
String query = "SELECT * FROM users";
PreparedStatement statement = null;
ResultSet result;
statement = conn.prepareStatement(query);
result = statement.executeQuery(query);
while(result.next())
{
Print("ID: " + result.getString("id"));
Print("USER: " + result.getString("username"));
Print("PASS: " + result.getString("password"));
}
Thanks for your help

java.sql.SQLException: SQL logic error or missing database, SQLite, JDBC

I have created a database connection with SQLite using JDBC in Java. My SQL statements execute properly, but sometimes I get the following error while I use conn.commit():
java.sql.SQLException: SQL logic error or missing database
Can anyone please help me how to avoid this type of problem. Is there a better approach of calling JDBC programs?
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:/home/Data/database.db3");
conn.setAutoCommit(false);
String query = "Update Chits set BlockedForChit = 0 where ServerChitID = '" + serverChitId + "' AND ChitGatewayID = '" + chitGatewayId + "'";
Statement stmt = conn.createStatement();
try {
stmt.execute(query);
conn.commit();
stmt.close();
stmt = null;
}
Can your variables serverChitId & chitGatewayId contain characters that would corrupt the SQL? It is usually safer to use PreparedStatements:
PreparedStatement ps = conn.prepareStatement("Update Chits set BlockedForChit = 0 where ServerChitID = ? AND ChitGatewayID = ?");
ps.setString(1, serverChitId);
ps.setString(2, chitGatewayId);
ps.executeUpdate();
This way the JDBC driver is responsible for making sure the necessary escapes are made to the strings.
Try setting conn.setAutoCommit to true. Also you need to delete conn.commit();.
If you are doing this inside of a function, make your function synchronized.
It's even more better if you use PreparedStatement instead of Statement.
All this is happening because sometimes you are trying to connect and modify your database at a same time and since the last connection hasn't commited yet, it throws that exception. When you set it to autoCommit it will handle the flow by itself.(it was really painful for me cause it says nothing more, I read all of the org.sqlite.DB files to find this out)
Class.forName("org.sqlite.JDBC");
conn = DriverManager.getConnection("jdbc:sqlite:/home/Data/database.db3");
conn.setAutoCommit(true);
PreparedStatement ps = "Update Chits set BlockedForChit = 0 where ServerChitID = ? AND ChitGatewayID = ? ";
ps.setString(1, serverChitId);
ps.setString(2, chitGatewayId);
try {
ps.executeUpdate();
}

Categories