unable to compare screen values with sql table value - java

I am trying to compare the screen values input against the value stored in DB. Currently i am trying this code:
cell = sheet.getRow(i).getCell(2);
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection ("jdbc:mysql://madison-dev.czr6vej2htnn.us-east-1.rds.amazonaws.com:3306/madisondb","madisonadmin","t4xuw94$");// + "databasename=madison-dev.czr6vej2htnn.us-east-1.rds.amazonaws.com";
Statement st = con.createStatement();
ResultSet Rs = st.executeQuery("select name, zipcode, state, city, street from business_master where user_id =(\r\n" +
"select id\r\n" +
"from user_master\r\n" +
"where email = 'cell.getStringCellValue()') \r\n");
while (Rs.next()) {
// System.out.println(Rs.getString(1) + " " + Rs.getString(2) + " " + Rs.getString(3) + " "
// + Rs.getString(4) + " " + Rs.getString(5));
System.out.println(Rs.getString(0));
}
The screen is not showing any values.. and when i am trying to print System.out.println(Rs.getString(3)) outside of the loop it gives me an error
java.sql.SQLException: Illegal operation on empty result set.

You are trying to find all the rows where the email address is literally the text 'cell.getStringCellValue()' rather than the value returned by that method.
Whilst you code assemble your query string, that lays you open to SQL injection attacks. Use a prepared statement instead
PreparedStatement st = con.prepareStatement(
"select name, zipcode, state, city, street from business_master where user_id =(" +
"select id " +
"from user_master " +
"where email = ?)");
st.setString(1, cell.getStringCellValue());
ResultSet Rs = st.executeQuery();

Related

Why am I getting this error: E/ERROR: The executeQuery method must return a result set.?

I'm trying to connect my project with an SQL-Server database. But I always get this error E/ERROR: The executeQuery method must return a result set.
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String username = "un";
String password = "pass";
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://ip/db;user=" + username + ";password=" + password);
Log.w("Connection","open");
String sql = "INSERT INTO TABLE" +
"(Cliente, NomePessoa, Email, NivelSatisfacao, Nota) " +
"VALUES ('" + informacao.getNomeCliente() + "', '" + informacao.getNome() + "', '" + informacao.getEmail() + "', '" + informacao.getSatisfacao() + "', '" + informacao.getNota() + "') ";
Statement stmt = conn.createStatement();
ResultSet rSet = stmt.executeQuery(sql); // error here
I tried to change stmt.executeQuery to stmt.executeUpdate, but it underlines it red, and says that the output is int, so it is incompatible.
Using PreparedStatement is much safer.
Class.forName("net.sourceforge.jtds.jdbc.Driver");
String username = "un";
String password = "pass";
conn = DriverManager.getConnection("jdbc:jtds:sqlserver://ip/db;user=" + username + ";password=" + password);
Log.w("Connection","open");
String sql = "INSERT INTO TABLE" +
"(Cliente, NomePessoa, Email, NivelSatisfacao, Nota) " +
"VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setString(1, informacao.getNomeCliente())
pstmt.setString(2, informacao.getNome())
pstmt.setString(3, informacao.getEmail())
pstmt.setString(4, informacao.getSatisfacao())
pstmt.setString(5, informacao.getNota())
int result = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
I think you should use the executeQuery method while querying tables in the database (when you have the SELECT keyword). When you want to execute SQL statements (like INSERT, UPDATE and others) you should use execute method, as seen in here.
In your case you could try:
Boolean rSet = stmt.execute(sql);

can't insert data to mysql

I can connect fine in Netbeans using this:
Connection conn = null;
try{
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/librarymangementsystem","root","root");
if(conn!= null)
{
System.out.println("connected");
}
}catch(Exception e)
{
System.out.println("not connected");
}
}
But when it comes to adding data to the columns, i just cant.
try{
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/librarymangementsystem","root","root");
Statement stmt=conn.createStatement();
String Query = "INSERT into librarian_details(username, name, email, password) VALUES("+ uname +", "+ fname +", " + emails + ", " + psword +")";
stmt.executeUpdate(Query);
JOptionPane.showMessageDialog(null, "Success!");
}
Anyone knows the problem?
Updated Problem:
String Query = "insert into book_details(Book_Name, ISBN, Author, Category, >Quantity, BookShelfNo,Row,Column) VALUES('" +bookname + "','" + ISBN + "','" + >AuthorName + "','" + Category + "','" + Quantity + "','" + ?BookShelfNo +"', '" >+ Row + "', '" + Column + "')";
I cant seem to insert any data to Row and Column using this:
String Row = jTextField9.getText();
String Column = jTextField10.getText();
Row and Column Datatype is int.
I guess the username, name, email and password fields are of String type and Data type used while creating the columns username, name, email and password of librarian_details is Varchar .
If so, then you need to update your query string to the below code:
String Query = "INSERT into librarian_details(username, name, email, password)
VALUES('"+ uname +"','"+ fname +"','" + emails + "','" + psword +"')";
If your input String has an apostrophe (') character then you need to add an extra apostrophe (') character as an escape sequence.
For Example:your password is abc'aa
String uname = "abc";
String fname = "xyz";
String emails = "abc#xyz.com";
String psword = "abc''aa";//extra apostrophe (') character added
String Query = "INSERT into librarian_details(username, name, email, password) VALUES('"+ uname+ "','"+ fname+ "','"+ emails+ "','"+ psword+ "')";
Note: Adding extra apostrophe (') to the existing (') character is different than a double quote.
Below code is for your updated query
String bookname ="abc";
String ISBN="qwerty123";
String AuthorName="user3213";
String Category="New";
String Quantity="1";
String BookShelfNo="5";
int Row=1;
int Column=5;
String Query = "insert into book_details(Book_Name, ISBN, Author, Category, Quantity, BookShelfNo,`Row`,`Column`) VALUES('" +bookname + "','" + ISBN + "','" + AuthorName + "','" + Category + "','" + Quantity + "','" + BookShelfNo +"', " + Row + ", " + Column + ")";
stmt.execute(Query);
Note: you are using reserved keywords of sql like Row and Column.
I guess your column names in DB are Book_Name, ISBN, Author, Category, Quantity, BookShelfNo, Row and Column.
Suggestion:
Using PreparedStatement will save your time for writing a query (no need to remember datatype of variable and columns.)
PreparedStatement uses query caching functionality.
Hence, execution is faster than simple statement.
Below code depicts the usage of prepared statement for your query.
//query parameters will be dynamically set
String Query = "INSERT INTO book_details VALUES (?,?,?,?,?,?,?,?)";
//create a Prepared statement using connection object.
PreparedStatement pstmt = con.prepareStatement(Query);
//assign the query parameter values
pstmt.setString(1, bookname);
pstmt.setString(2, ISBN);
pstmt.setString(3, AuthorName);
pstmt.setString(4, Category);
pstmt.setString(5, Quantity);
pstmt.setString(6, BookShelfNo);
pstmt.setInt(7, Row);
pstmt.setInt(8, Column);
//display query string generated by PreparedStatement.
System.out.println("Query: "+pstmt.toString());
//Display result; result=1 means success.
int result = pstmt.executeUpdate();
System.out.println("result: "+result);
Escape the text values or even better - use prepared statements.
String Query = "INSERT into librarian_details(username, name, email, password)
VALUES('"+ uname +"', '"+ fname +"', '" + emails + "', '" + psword +"')";
Prepared statements:
String Query = "INSERT into librarian_details(username, name, email, password)
VALUES(?, ?, ?, ?)";
Concatenating values into a query is unsafe, it opens you up to SQL injection. You need to use a prepared statement instead:
try (PreparedStatement pstmt = connection.prepareStatement(
"INSERT into librarian_details(username, name, email, password) "
+ "VALUES(?, ?, ?, ?)")) {
pstmt.setString(1, uname);
pstmt.setString(2, fname);
pstmt.setString(3, emails);
pstmt.setString(4, psword);
pstmt.executeUpdate();
}

Populating jTable from postgresql

I am doing java project in NetBeans 8 using databases and GUI.The problem is appearing when I search through the database and add the found values to JTable: all values are being added only to first column of JTable while I need them added separately to corresponding columns. I tried getColumnCount() and it also gave me 1 meaning that I have only one column. How to add database values to JTable's corresponding columns?
I've tried all the populating functions adviced here
My code:
jTable1 = new javax.swing.JTable();
String sql = "SELECT (flight_id, plane_name, dep_city, arival_city, date_month, date_day, eclassnumberofseats, bclassnumberofseats, fclassnumberofseats) FROM flight "
+ "WHERE (dep_city = '" + SearchFlight.getFromCity() + "' AND "
+ "arival_city = '" + SearchFlight.getToCity() + "' AND "
+ "date_month = '" + SearchFlight.getMonth() + "');";
PreparedStatement stat = conn.prepareStatement(sql);
ResultSet rs = stat.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs)
);
jScrollPane1.setViewportView(jTable1);
SearchFlight is a GUI class, and its methods return strings obtained in GUI.
DbUtils.resultSetToTableModel(rs)is a method in net.proteanit.sql.DbUtils;
So, it is expected that the data will be filled into 9 columns, hoewever it fills all the data into one column.
SELECT ( ... )
must be
SELECT ....
And better use the PreparedStatement as intended. Otherwise SQL injection still is possible. And try-with-resources closes the things under all circumstances.
String sql = "SELECT flight_id, plane_name, dep_city, arival_city, date_month, "
+ "date_day, eclassnumberofseats, bclassnumberofseats, fclassnumberofseats "
+ "FROM flight "
+ "WHERE dep_city = ? AND "
+ "arival_city = ? AND "
+ "date_month = ?";
try (PreparedStatement stat = conn.prepareStatement(sql)) {
stat.setString(1, SearchFlight.getFromCity());
stat.setString(2, SearchFlight.getToCity());
stat.setString(3, SearchFlight.getMonth());
try (ResultSet rs = stat.executeQuery()) {
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
}
}

Inserting values in specific row sql java

"SELECT * FROM PlayerClass WHERE Username = '" + p.getName() + "'"
So I have selected the specific row and how would I go about inserting a value in column ExColumn in the same exact row?
If you're allowed to use JDBC and PreparedStatement, I would suggest you do this:
String sql = "UPDATE PlayerClass SET ExColumn = ? WHERE Username = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setObject(1, exColumnValue); // exColumnValue is the data you're trying to insert
ps.setString(2, p.getName());
ps.executeUpdate();
This way you'll be avoiding SQL injection attacks.
You have to use UPDATE
"Update PlayerClass set Username = '" +someValue + "'"
That will update all rows
To update secific rows with some condition ,add where clause.
"Update PlayerClass set Username = '" +someValue + "'
WHERE Username = '" + p.getName() + "'"
May be your are trying to update specific row. then this will help you
UPDATE PlayerClass SET ExColumn='YOUR_INSERTION_DATA_IN_THIS'
WHERE Username = 'XYZ'

Querying to Oracle DB through JDBC gives null while direct query gives the output

I have a sql query which when I manually sends to an Oracle DB through SQLDeveloper Application gets me the output I want. But the same query returns nothing while I try to connect and query through JDBC driver why this is happening so. Please help me.
code:
String sql = "select * from tablename where id='" + id + "' AND case_id = '" + case_id + "'";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
System.out.println(sql);
System.out.println("next = " + rs.next());
output:
select * from tablename where id='1' AND case_id = '1000'
next = false
Both connections (JDBC and SQLDeveloper) are using same username and password. So no issue of privilege or security i think.
Try to pass the "id" as a number. As you are passing the ID as String, the JDBC driver will convert it to CHAR, VARCHAR, or LONGVARCHAR.
String sql = "select * from tablename where id=" + id + " AND case_id = '" + case_id + "'";
Resulting string:
select * from tablename where id=1 AND case_id = '1000'
Consider to use PreparedStatement with bind parameters, to avoid sql injection:
String sql = "select * from tablename where id = ? AND case_id = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, 1);
ps.setString(2, "1000");
ResultSet rs = ps.executeQuery();
References:
http://docs.oracle.com/javase/6/docs/technotes/guides/jdbc/getstart/mapping.html
http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html

Categories

Resources